Search code examples
stringvariablesansiblehostvars

Ansible: Merge variable values into new variable


Let's say I have an inventory like this:

database:
  hosts:
    database1:
      ansible_host: 192.168.0.125
    database2:
      ansible_host: 192.168.0.126
    database3:
      ansible_host: 192.168.0.127

Now I'll have to replace a string in a file that has the IP addresses of all hosts and hosts from the future as well. So in short, I need a variable that looks like this:

192.168.0.125,192.168.0.126,192.168.0.127

Now, I could just do this:

Inventory:

database:
  hosts:
    database1:
      ansible_host: 192.168.0.124
    database2:
      ansible_host: 192.168.0.126
    database3:
      ansible_host: 192.168.0.127
  vars:
      dbs: "{{ hostvars['database1']['ansible_host'] + ',' + hostvars['database2']['ansible_host'] + ',' + hostvars['database3']['ansible_host'] }}"

Playbook:

- name: Show host's ip
    debug:
      msg: "{{ dbs }}"

But this clearly is not good, cause if a new instance comes in this list, I'll have to add manualla + ',' + hostvars['databaseX']['ansible_host'] to the inventory and I wish to avoid that.

Can you guys recommend a way to use a loop or items list to get the string in a variable with all the IP addresses?

Thanks !


Solution

  • Create the variable dynamically in the inventory. For example,

    shell> cat hosts
    database:
      hosts:
        database1:
          ansible_host: 192.168.0.124
        database2:
          ansible_host: 192.168.0.126
        database3:
          ansible_host: 192.168.0.127
      vars:
        dbs: "{{ groups.database|
                 map('extract', hostvars, 'ansible_host')|
                 join(',') }}"
    

    Example of a complete playbook for testing

    shell> cat pb.yml 
    - hosts: all
      tasks:
        - debug:
            var: dbs
    

    gives

    shell> ansible-playbook pb.yml 
    
    PLAY [all] ***********************************************************************************
    
    TASK [debug] *********************************************************************************
    ok: [database1] => 
      dbs: 192.168.0.124,192.168.0.126,192.168.0.127
    ok: [database3] => 
      dbs: 192.168.0.124,192.168.0.126,192.168.0.127
    ok: [database2] => 
      dbs: 192.168.0.124,192.168.0.126,192.168.0.127
    
    PLAY RECAP ***********************************************************************************
    database1: ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    database2: ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    database3: ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0