Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic variable name in Ansible playbook?

Tags:

ansible

I have a number of lists with names, that were created by appending ec2_public_dns_name to seeds_

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

I need in config for each host to access it's list and loop over it. I try to do it like this:

In playbook assign to 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 seems like seeds in config file is just text, I can't access list elements. How can this be done?

like image 434
sergeda Avatar asked Nov 10 '22 14:11

sergeda


1 Answers

Task:

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

creates text variable seeds which value is seeds_ec2-50-8-1-43.us-west-1.compute.amazonaws.com.

If you want seeds to be list that you will iterate, you need to add seeds_{{ec2_public_dns_name}} to seeds list:

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

But this will add to array seeds one element. Probably you have ec2_public_dns_names that 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 such list, you can create list of seeds with following task:

- set_fact:
    seeds: "{{seeds + ['seeds_' + item]}}"
  with_items: "{{ec2_public_dns_names}}"
like image 80
reynev Avatar answered Jan 04 '23 02:01

reynev