In some cases you may want to create nearly identical objects from a list of values, or another dictionary.
This was a commonly needed ability at VMware on the NSX ALB (Avi) team as for many of our infra, and for our customers have a list of servers that we needed to build into a list of dictionaries as we require more than just a specific IP.
This is how to do it (these are tasks, not the entire playbook)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
--- - name: Generate a list for a dict hosts: localhost connection: local vars: pool_servers: "{{ pool_servers }}" # this is the input information ex. 192.168.1.1,192.168.1.2 tasks: - name: Build server list ansible.builtin.set_fact: servers_list: "{{ servers_list | default([]) + [{'ip': {'addr': item, 'type': 'V4'}, 'enabled': 'true'}] }}" loop: "{{ pool_servers.split(',') }}" # each server_list item has ansible fact as server - name: Print the server_list ansible.builtin.debug: var: servers_list |
So lets review what we did.
We created the servers_list
fact, we set the default value to be a blank list and then for each of the servers in pool_servers
separated by ,
we loop adding the dict
{'ip': {'addr': item, 'type': 'V4'}, 'enabled': 'true'} to the servers_list
.
This can be applied to any kind of situation where you need to create a list of complicated objects.
The returned output would look like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
ansible-playbook list.yml -e 'pool_servers=192.168.1.1,192.168.1.2' [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' PLAY [Generate a list for a dict] ***************************************************************************************** TASK [Gathering Facts] **************************************************************************************************** ok: [localhost] TASK [avinetworks.avisdk : Check ansible version] ************************************************************************* skipping: [localhost] TASK [build server list] ************************************************************************************************** ok: [localhost] => (item=192.168.1.1) ok: [localhost] => (item=192.168.1.2) TASK [debug] ************************************************************************************************************** ok: [localhost] => { "servers_list": [ { "enabled": "true", "ip": { "addr": "192.168.1.1", "type": "V4" } }, { "enabled": "true", "ip": { "addr": "192.168.1.2", "type": "V4" } } ] } PLAY RECAP ************************************************************************************************************** localhost : ok=3 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0 |