Issue with yaml in jinja2

Hi Ansible community.,

I’d like to share a problem I’m having while trying lo load a yaml formatted template and perhaps getting feedback from you on how to make it work.

I wrote the following playbook: https://gist.github.com/gaccardo/2c12fc4aab443978fe33829129237cbc

If the content of “policy_content.yaml” is “pure” YAML, i.e: https://gist.github.com/gaccardo/3047c0c06d36d39a69d2d3c60a3daf4e, the task Create IAM Managed Policy works as expected, meaning the IAM policy gets created in my AWS account.

Now, instead if I change the file policy_content.yaml to the following: https://gist.github.com/gaccardo/fc30a3c40f8ff01d44b61ad6fec0a3b7, the task fails with the following error: https://gist.github.com/gaccardo/f27accb0dac958ab83c232bb347a292b.

This is how i’m calling the playbook:

$ ansible-playbook -e “selected_env=dev” policy.yml -vvv

Is it possible that the filter “from_yaml” is getting the template unredered from “lookup”?

The error says: “did not find expected ‘-’ indicator” but I’m starting the lines within the Actions with the required “-”


7 - Effect: Allow
8 Action:
9 - “s3:Get*”
10 {% if env in [“dev”, “stg”] %}
11 - “s3:Put*”
12 {% endif %}
13 Resource:
14 - “arn:aws:s3:::bucket/{{ env }}”
15 - “arn:aws:s3:::bucket/{{ env }}/*”

Check lines 9 and 11.

Thank you in advance for you time. Best!

A few things here:

  1. Your gist of that file, and what you indicate in your email are different, specifically the if env in ["dev", "stg] part
  2. As a result of #1 the YAML renders incorrectly, causing that error

Here is the result of the template when env: dev is set:

A few things here:

  1. Your gist of that file, and what you indicate in your email are different, specifically the if env in ["dev", "stg] part

Sorry about this.

  1. As a result of #1 the YAML renders incorrectly, causing that error

Here is the result of the template when env: dev is set:


Version: 2012-10-17
Statement:

  • Effect: Allow
    Action:
  • “s3:List*”
    Resource: “arn:aws:s3:::bucket”
  • Effect: Allow
    Action:
  • “s3:Get*”
  • “s3:Put*”
    Resource:
  • “arn:aws:s3:::bucket/dev”
  • “arn:aws:s3:::bucket/dev/*”

As such, your template needs to be adjusted with something like this, where the {% if %} and {% endif %} blocks aren’t adding to the indentation, by being completely left justified:


Version: 2012-10-17
Statement:

  • Effect: Allow
    Action:
  • “s3:List*”
    Resource: “arn:aws:s3:::bucket”
  • Effect: Allow
    Action:
  • “s3:Get*”

{% if env in [“dev”, “stg”] %}

  • “s3:Put*”
    {% endif %}
    Resource:

  • “arn:aws:s3:::bucket/{{ env }}”

  • “arn:aws:s3:::bucket/{{ env }}/*”

Thank you for this clarification, what you suggested worked!