Home > OS >  Ansible: Merge variable values into new variable
Ansible: Merge variable values into new variable

Time:02-18

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 !

CodePudding user response:

One option is to build the dbs value in a loop:

- hosts: localhost
  gather_facts: false
  tasks:
    - set_fact:
        dbs: "{{ dbs   [hostvars[item].ansible_host] }}"
      loop: "{{ groups.database }}"
      vars:
        dbs: []

    - debug:
        var: dbs

Given your example inventory, this would produce:

TASK [debug] ********************************************************************************************
ok: [localhost] => {
    "dbs": [
        "192.168.0.125",
        "192.168.0.126",
        "192.168.0.127"
    ]
}

CodePudding user response:

Create the variable dynamically in the inventory. For example

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(',') }}"
  • Related