I’d like to access a variable set by the ec2.py dynamic inventory script in a Jinja2 template, but I can’t work out how to do it.
ec2.py returns a variable called ec2_tag_elasticbeanstalk_environment-name for EC2 instances that are part of an Elastic Beanstalk environment:
`
ec2.py --host=ec2-54-196-159-144.compute-1.amazonaws.com
{
“ec2__in_monitoring_element”: false,
“ec2_ami_launch_index”: “0”,
“ec2_architecture”: “x86_64”,
…snip
“ec2_tag_elasticbeanstalk_environment-name”: “production”,
“ec2_virtualization_type”: “paravirtual”,
“ec2_vpc_id”: “”
}
`
I’d like to access that variable in a template I’m running as part of a playbook on that host:
`
- name: Create Diamond conf file
template: src=diamond_elasticbeanstalk.conf.j2 dest=/etc/diamond/diamond.conf
notify :
`
The template contains:
`
path_prefix = servers.{{ ec2_tag_elasticbeanstalk_environment-name }}
`
I’m guess I have the wrong syntax, but I can’t find anywhere in the docs that tells me the correct approach.
Roger
After further investigation…
When the playbook runs, on that task I get:
`
fatal: [ec2-54-196-159-144.compute-1.amazonaws.com] => {‘msg’: “unsupported operand type(s) for -: ‘StrictUndefined’ and ‘StrictUndefined’”, ‘failed’: True}
`
If I define the variable in the group_vars file I get the same error.
However, if I change the variable in both the group_vars file and the template to ec2_tag_elasticbeanstalk_environment_name - i.e. with an underscore instead of a minus as the last separator then it works.
That implies that the - in the variable name is the issue, but I still don’t know the best way to solve it.
You can pull it from the hostvars dictionary with something like
hostvars[inventory_hostname]['ec2_tag_elasticbeanstalk_environment-name']
Really we should probably replace all “-” with “_” in tag names so they can be cleanly used as variables.
But then again, the tag had a “-” in it, so I’m not sure that’s the right thing to do.
Anyway, variables can’t have “-” in them, which is why that happens, so it’s easy to fix with a convention.
I thought about tackling this along with the proposed "downcase_facts"
option for ec2.ini. Something like "normalize_facts" or some such so
that anything that's not a letter or number gets converted to an
underscore. Would default to false just like downcase_facts.
That seems reasonable to me.
The hostvars approach you suggested worked fine - thanks for the advice.
I concur that adding an option to ec2.ini is a good idea. Even for those people that don’t want to use it, it will serve as a warning that they need to be aware of the difference in variable naming requirements between EC2 and Jinja2