I have an invnentory file with a group of servers defined

prod1 ansible_host=
prod2 ansible_host=
prod3 ansible_host=
prod4 ansible_host=

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: ",,,"

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


The playbook below does the job

- hosts: prod
  gather_facts: false
    - 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


  list1: prod1_IP,prod2_IP,prod3_IP,prod4_IP

You must log in to answer this question.

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