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.