Create a new list after setting fact - ansible

I have a playbook that looks like this
---
- hosts: localhost
gather_facts: false
connection: local
vars:
addresses: ['10.10.10.0/28', '10.11.11.0/28']
list_address: []
tasks:
- name: set empty list for cidr
set_fact:
ips_and_masks: []
- name: set up address fact
set_fact:
address: "{{ item.split('/')[0] }} {{ item | ipaddr('netmask') }}"
loop: "{{ item.addresses }}"
- name: create new list
set_fact:
list_address: "{{ list_address + [address] }}"
- name: debug new list
debug:
msg: "Addresses: {{ list_address }}"
I'm trying to get the output to be
"Address": [
"10.10.10.0 255.255.255.240",
"10.11.11.0 255.255.255.240"
]
But the second iteration of the loop overwrites the first so I end up with
"Address": [
"10.11.11.0 255.255.255.240"
]
Is there a way to append it rather than overwrite it?

You don't need address fact at all. Change your task to this:
- name: set up address fact
set_fact:
list_address: "{{ (list_address | default([])) + [ (item.split('/')[0]) + (item | ipaddr('netmask')) ] }}"
loop: "{{ addresses }}"
Then, you can remove create new list task.
You can remove list_address var declaration as well, because it's been initialized in set_fact (as #Zeitounator says in comments)

Related

How to create a list of dictionary of users and list of folders for each user?

I would like to create a dictionary of users which has list of folders in it.
users:
name: user1
folders:
- user1-1
- user1-2
name: user2
folders:
- user2-1
- user2-2
name: userN
folders:
- userN-1
- userN-2
I am trying to create this user dictionary list dynamically.
- hosts: localhost
gather_facts: no
vars:
userCount: 5
folderCount: 5
tasks:
- set_fact:
user_lists: []
- name: creating list of users
set_fact:
user_lists: "{{ user_lists + [ 'user-' ~ item ] }}"
with_sequence: count="{{userCount|int}}"
- debug:
var: user_lists
- set_fact:
usersObj: []
userDict: {}
- name: add each user to dict
set_fact:
usersObj: "{{ usersObj + [userDict| combine({'name': item})] }}"
with_items: "{{user_lists}}"
- debug: var=usersObj
I have created 5 users in dictionary. Now each user should have folder list created based on folderCount. How to resolve this? Can Jinja2 templates be used to simplify this?
The task below does the job
- set_fact:
user_lists: []
- name: creating dictionary of users with lists of folders
set_fact:
user_lists: "{{ user_lists|combine({key: val}) }}"
with_sequence: start=1 end="{{ userCount }}"
vars:
folder_range: "{{ range(1, folderCount|int + 1)|list }}"
key: "{{ 'user-' ~ item }}"
val: "{{ [key]|
product(folder_range)|
map('join', '-')|
list }}"
- debug:
var: user_lists
gives (abridged)
"user_lists": {
"user-1": [
"user-1-1",
"user-1-2",
"user-1-3",
"user-1-4",
"user-1-5"
],
"user-2": [
"user-2-1",
"user-2-2",
"user-2-3",
"user-2-4",
"user-2-5"
],
"user-3": [
"user-3-1",
"user-3-2",
"user-3-3",
"user-3-4",
"user-3-5"
],
"user-4": [
"user-4-1",
"user-4-2",
"user-4-3",
"user-4-4",
"user-4-5"
],
"user-5": [
"user-5-1",
"user-5-2",
"user-5-3",
"user-5-4",
"user-5-5"
]
}

VARIABLE IS NOT DEFINED when trying to register output in playbook

I'm trying to register a variable with the output to a query of a F5 pool and I'm getting this error:
"<type 'list'>": "VARIABLE IS NOT DEFINED!",
What is that I'm doing wrong?
Any help appreciated.
Thanks!
---
- name: GRAB F5 FACTS
hosts: f5
connection: local
gather_facts: no
tasks:
- name: Collect BIG-IP facts
bigip_device_facts:
gather_subset: ltm-pools
provider: "{{ prov }}"
register: bigip_device_facts
- name: FACTS OUTPUT
debug:
var: "{{ item.members | rejectattr('state', 'match', '^present$') | map(attribute='name') | list }}"
register: jkout
with_items: "{{ bigip_device_facts.ltm_pools }}"
when: item.full_path == "/Common/mypool"
- name: Set a variable
debug:
msg: "jkvar={{ jkout }}"
You are using the debug: module with the option var: and this expects a variable, not a jinja2 template.
So either change it to:
debug:
var: item.members
or
debug:
msg: "{{ item.members }}"
Like said by #dgw, the problem is with the var option of debug module.
https://docs.ansible.com/ansible/latest/modules/debug_module.html#parameters
This playbooks works:
- name: test rejectattr
hosts: localhost
gather_facts: no
vars:
members:
- { name: "one", state: "present" }
- { name: "two", state: "absent" }
- { name: "three", state: "present" }
tasks:
- name: FACTS OUTPUT
debug:
msg: "{{ members | rejectattr('state', 'match', '^present$') | map(attribute='name') | list }}"
Thanks for your responses. I'll investigate it further.
Apart from that, I think I've been able to solve it another way.
- name: FACTS OUTPUT
set_fact:
listado: "{{ item.members | rejectattr('state', 'match', '^present$') | map(attribute='name') | list }}"
with_items: "{{ bigip_device_facts.ltm_pools }}"
when: item.full_path == "/Common/mypool"
- debug: msg={{ listado }}
register: jkout
- name: Set a variable
debug:
msg: "jkvar={{ jkout }}"
Is that a right way to do it?
Thanks!!

How to get all the node list IP addresses?

In my case, there are four nodes which runs ansible. I want to get each and every node ip address. Therefore i tried these.
In my playbook.yml
- name: Ansible
hosts: all
gather_facts: true
vars:
ansible_ec2_local_ipv4: "{{ ansible_default_ipv4.address }}"
roles:
- role: "ansible-mongo/roles/mongo"
- role: "ansible-mongo/roles/replication"
In my main.yml
- name: ensure file exists
copy:
content: ""
dest: /tmp/myconfig.cfg
force: no
group: "{{ mongodb_group }}"
owner: "{{ mongodb_user }}"
mode: 0555
- name: Create List of nodes to be added into Cluster
set_fact: nodelist={%for host in groups['all']%}"{{hostvars[host].ansible_eth0.ipv4.address}}"{% if not loop.last %},{% endif %}{% endfor %}
- debug: msg=[{{nodelist}}]
- name: Set Cluster node list in config file
lineinfile:
path: "/tmp/myconfig.cfg"
line: "hosts: [{{ nodelist }}]"
But as a result when i tried to view /tmp/myconfig.cfg file. I only get one IP.
cat /tmp/myconfig.cfg
hosts: ["10.1.49.149"]
Any idea on this?
Your set_fact loop is overwriting the value of 'nodelist' on each pass, effectively meaning you only ever end up with the last element in the loop. Try this:
- set_fact:
nodelist: "{{ ( nodelist | default([]) ) + [ hostvars[item].ansible_eth0.ipv4.address ] }}"
loop: "{{ groups['all'] }}"
- debug:
var: nodelist | join(',')
(nodelist | default([])) outputs the current value of 'nodelist' or an empty list if it is not set (first pass)
+ [] merges the existing list with a new list, containing a single element - the IP of the host
So 'nodelist' ultimately ends up containing a list of IP's. You can then use | join(',') to turn that into a CSV.

Adding field to dict items

Consider the following play. What I am trying to do is add a field, tmp_path which is basically the key and revision appended together to each element in the scripts dict.
---
- hosts: localhost
connection: local
gather_facts: no
vars:
scripts:
a.pl:
revision: 123
b.pl:
revision: 456
tasks:
- with_dict: "{{ scripts }}"
debug:
msg: "{{ item.key }}_{{ item.value.revision }}"
# - with_items: "{{ scripts }}"
# set_fact: {{item.value.tmp_path}}="{{item.key}}_{{item.value.revision}}"
# - with_items: "{{ scripts }}"
# debug:
# msg: "{{ item.value.tmp_path }}"
...
Obviously the commented code doesn't work, any idea how I can get this working? Is it possible to alter the scripts dict directly, or should I somehow be creating a new dict to reference instead?
By the way welcome to correct the terminology for what I am trying to do.
OK, I think I got a solution (below), at least to let me move forwards with this. Disadvantages are it has removed the structure of my dict and also seems a bit redundant having to redefine all the fields and use a new variable, If anyone can provide a better solution I will accept that instead.
---
- hosts: localhost
connection: local
gather_facts: no
vars:
scripts:
a.pl:
revision: 123
b.pl:
revision: 456
tasks:
- with_dict: "{{ scripts }}"
debug:
msg: "{{ item.key }}_{{ item.value.revision }}"
- with_dict: "{{ scripts }}"
set_fact:
new_scripts: "{{ (new_scripts | default([])) + [ {'name': item.key, 'revision': item.value.revision, 'tmp_path': item.key ~ '_' ~ item.value.revision}] }}"
# - debug:
# var: x
# - with_dict: "{{ scripts }}"
- with_items: "{{ new_scripts }}"
debug:
msg: "{{ item.tmp_path }}"
...
BTW credit to the following question which pointed me in the right direction:
Using Ansible set_fact to create a dictionary from register results

Ansible - How to keep appending new keys to a dictionary when using set_fact module with with_items?

I want to add keys to a dictionary when using set_fact with with_items. This is a small POC which will help me complete some other work. I have tried to generalize the POC so as to remove all the irrelevant details from it.
When I execute following code it is shows a dictionary with only one key that corresponds to the last item of the with_items. It seems that it is re-creating a new dictionary or may be overriding an existing dictionary for every item in the with_items. I want a single dictionary with all the keys.
Code:
---
- hosts: localhost
connection: local
vars:
some_value: 12345
dict: {}
tasks:
- set_fact: {
dict: "{
{{ item }}: {{ some_value }}
}"
}
with_items:
- 1
- 2
- 3
- debug: msg="{{ dict }}"
This can also be done without resorting to plugins, tested in Ansible 2.2.
---
- hosts: localhost
connection: local
vars:
some_value: 12345
dict: {}
tasks:
- set_fact:
dict: "{{ dict | combine( { item: some_value } ) }}"
with_items:
- 1
- 2
- 3
- debug: msg="{{ dict }}"
Alternatively, this can be written without the complex one-liner with an include file.
tasks:
- include: append_dict.yml
with_items: [1, 2, 3]
append_dict.yml:
- name: "Append dict: define helper variable"
set_fact:
_append_dict: "{ '{{ item }}': {{ some_value }} }"
- name: "Append dict: execute append"
set_fact:
dict: "{{ dict | combine( _append_dict ) }}"
Output:
TASK [debug]
*******************************************************************
ok: [localhost] => {
"msg": {
"1": "12345",
"2": "12345",
"3": "12345"
}
}
Single quotes ' around {{ some_value }} are needed to store string values explicitly.
This syntax can also be used to append from a dict elementwise using with_dict by referring to item.key and item.value.
Manipulations like adding pre- and postfixes or hashes can be performed in the same step, for example
set_fact:
dict: "{{ dict | combine( { item.key + key_postfix: item.value + '_' + item.value | hash('md5') } ) }}"
Use a filter plugin.
First, make a new file in your ansible base dir called filter_plugins/makedict.py.
Now create a new function called "makedict" (or whatever you want) that takes a value and a list and returns a new dictionary where the keys are the elements of the list and the value is always the same.
class FilterModule(object):
def filters(self):
return { 'makedict': lambda _val, _list: { k: _val for k in _list } }
Now you can use the new filter in the playbook to achieve your desired result:
- hosts: 127.0.0.1
connection: local
vars:
my_value: 12345
my_keys: [1, 2, 3]
tasks:
- set_fact: my_dict="{{ my_value | makedict(my_keys) }}"
- debug: msg="{{ item.key }}={{ item.value }}"
with_dict: "{{my_dict}}"
You can customize the location of the filter plugin using the filter_plugins option in ansible.cfg.
this does not seems to work any more on ansible 2.5
---
- hosts: localhost
connection: local
vars:
some_value: 12345
dict: {}
tasks:
- set_fact:
dict: "{{ dict | combine( { item: some_value } ) }}"
with_items:
- 1
- 2
- 3
- debug: msg="{{ dict }}"
returns only last value {"dict":{"3": "some value"}}
I suggest you could do this :
- set_fact:
__dict: |
{% for item in [1,2,3] %}
{{item}}: "value"
{% endfor %}
- set_fact:
final_dict: "{{__dict|from_yaml}}"
- debug:
var: final_dict
Another solution could be this one, tested in Ansible 2.9.6.
This solutions adds the extra benefit that you do not have to declare _dict beforehand in vars section. This is achieved by the | default({}) pipe which ensures that the loop will not fail in the first iteration when _dict is empty.
In addition, the renaming of dict to _dict is necessary since the dict is a special keyword reserved for <class 'dict'>. Referenced (unfortunately only at devel branch yet) here.
---
- hosts: localhost
connection: local
vars:
some_value: 12345
tasks:
- set_fact:
_dict: "{{ _dict | default({}) | combine( { item: some_value } ) }}"
with_items:
- 1
- 2
- 3
- debug: msg="{{ _dict }}"

Resources