2

I have an invnentory file with a group of servers defined

[prod]
prod1 ansible_host=10.10.2.30
prod2 ansible_host=10.10.2.40
prod3 ansible_host=10.10.2.50
prod4 ansible_host=10.10.2.60

I want to define a variable that concatenates all servers in prod group delimited by comma. lets say variable is list, variable should contain values like

list: "prod1_IP,prod2_IP,prod3_IP,prod4_IP"    
list: "10.10.2.30,10.10.2.40,10.10.2.50,10.10.2.60"

one could easily put these manually, but catch is, list is supposed to expand in different scenrios.

I guess one can use hostvars[item].ansible_host with for loop. but not sure how

1 Answer 1

1

The playbook below does the job

- hosts: prod
  gather_facts: false
  tasks:
    - block:
        - set_fact:
            list1: "{{ ansible_play_hosts_all|product(['_IP'])|map('join')|
                       join(',') }}"
        - debug:
            var: list1
        - set_fact:
            list2: "{{ ansible_play_hosts_all|map('extract', hostvars, 'ansible_host')|
                       join(',') }}"
        - debug:
            var: list2
      run_once: true

gives

  list1: prod1_IP,prod2_IP,prod3_IP,prod4_IP
  list2: 10.10.2.30,10.10.2.40,10.10.2.50,10.10.2.60

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .