1

I am using aws ec2 inventory for Ansible and have a jinja template like this (linebreaks are readability - it's all one line):

my_variable: "{% if tags.Id == '1' -%}
      {{groups['tag_Name_myinstance'] | sort | hostvars[last].tags.dns}}
      {% else -%}
      {{groups['tag_Name_myinstance'] | sort | hostvars[first].tags.dns}}
      {% endif %}:123"

This fails with Error was a <class 'ansible.errors.AnsibleError'>, original message: template error while templating string: expected token 'end of print statement', got '['

The intent is to always use the last instance (i.e. with the highest Id value) as the value to pass into the instance with Id=1, and use this first instance to pass into all other ones.

If I just do something like this, it gives the ansible hostname, like i-0123456789 (ec2 instance id):

my_variable: "{% if tags.Id == '1' -%}
      {{groups['tag_Name_myinstance'] | sort | last}}
      {% else -%}
      {{groups['tag_Name_myinstance'] | sort | first}}
      {% endif %}:123"

How can I convert first or last in jinja to a way where I can get hostvars from it, given that it resolves to the hostname (aws ec2 instance id)? I want to specifically grab the tag for dns. In other parts of my yaml I reference it like:

other_variable: "{{ tags.dns }}"

and that works fine.

swagrov
  • 1,510
  • 3
  • 22
  • 38

1 Answers1

1

Like in an arithmetic expression, you can group a list of Jinja filters with parenthesis (). Or use a complex expression as a key in the hostvars dictionary.
Then get the properties you want out of the dictionary this yield.

my_variable: >-
    {%- if tags.Id == '1' -%}
        {{ hostvars[groups['tag_Name_myinstance'] | sort | last].tags.dns }}
    {%- else -%}
        {{ hostvars[groups['tag_Name_myinstance'] | sort | first].tags.dns }}
    {%- endif %}:123

Also regarding your

line breaks are readability - it's all one line

Well, this is exactly what YAML multiline is for.
So the YAML snippet here above is a totally valid one, on multiple lines.

Extra tip on YAML multiline: this site is a of neat "tick the box and see how it renders" kind: https://yaml-multiline.info/

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
  • I didn't think to use the complex expression as a key. This works now, and thanks for the YAML tip too! – swagrov Feb 08 '21 at 22:30