Reputation: 1529
I am trying to get a random host in a group that contains a list of IP's. We are running into some issues as our group name uses a variable, but the line is already in {{
's due to the Jinja random
call.
- hosts: "{{ {{ env }}_as_group | random }}"
ERROR! template error while templating string: expected token 'end of print statement', got '{'. String: {{ {{ env }}_as_group | random }}
The env variable is passed into the playbook on execution with ansible-playbook "-e env=stage" myplaybook.yml
Looking around online, most people solve this with vars[env]
, however that doesnt seem to quite work for us -
- hosts: "{{ vars[env]_as_group | random }}"
ERROR! template error while templating string: expected token 'end of print statement', got '_as_group'. String: {{ tag_aws_autoscaling_groupName_[ env ]_as_group | random }}
If I make it - hosts: "{{ stage_as_group | random }}"
, it works as expected.
How can I set the host to pull a random value in the group {{ env }}_as_group
?
Upvotes: 1
Views: 953
Reputation: 39089
In Ansible, moustache should not be stacked.
So you should use the proper Jinja concatenation operator: ~
.
Ending with:
- hosts: "{{ vars[env ~ '_as_group'] | random }}"
This said it is not totally clear to me what stage_as_group
really is: is it a list or a hosts group?
If this is a group in you inventory, this won't work because random
works on a sequence, and a host group is a string, not a sequence.
For that use case, you probably want this instead:
- hosts: "{{ groups[env ~ '_as_group'] | random }}"
Upvotes: 3