Dynamic variable name in Ansible playbook?

I have a list of named lists that were created by adding ec2_public_dns_name

toseeds_

Example: seeds_ec2-50-8-1-43.us-west-1.compute.amazonaws.com

I need each host to access this list and iterate over it. I am trying to do it like this:

In the playbook, assign a new variable:

- name: Seeds provision
  set_fact:
    seeds: "seeds_{{ec2_public_dns_name}}"

      

And than in config, use it:

{% for seed in seeds %}
{{seed.name ~ ","}}
{% endfor %}

      

But it looks like seeds

in the config file is just text, I can't access the list items. How can I do that?

+3


source to share


1 answer


A task:

- set_fact:
    seeds: "seeds_{{ec2_public_dns_name}}

      

creates a text variable seeds

whose value is seeds_ec2-50-8-1-43.us-west-1.compute.amazonaws.com

.

If you want to seeds

be a list that you will iterate over, you need to add the list seeds_{{ec2_public_dns_name}}

to seeds

:

- set_fact:
    seeds: [] # define seeds as empty list
- set_fact:
    seeds: "{{seeds + ['seeds_' + ec2_public_dns_name]}}"

      



But this will add seeds

one element to the array . You probably have ec2_public_dns_names

, which is a list of public DNS values ​​for your hosts:

ec2_public_dns_names: 
  - ec2-50-8-1-43.us-west-1.compute.amazonaws.com
  - ec2-50-8-2-43.us-west-1.compute.amazonaws.com
  - ...

      

With a list like this, you can create a seed list with the following task:

- set_fact:
    seeds: "{{seeds + ['seeds_' + item]}}"
  with_items: "{{ec2_public_dns_names}}"

      

+1


source







All Articles