i am using "shell:" to get some data by looping over "with_items:" and registering it as another variable. Later using "lineinfile:" i am trying to apply the contents of earlier variable,but not able to use "{{variable.stdout}}" as it is showing as undefined in "with_items:"
Is there a way to tell ansible that for "variable.stdout" don't look in "with_items:"
---
- include_vars: /root/template.yml
- name: Getting MAC
shell: "cat /sys/class/net/{{item.name}}/address"
register: mac
with_items:
- "{{ interfaces_ipv4 }}"
- name: Setting MAC
lineinfile:
state=present
dest=/etc/sysconfig/network-scripts/ifcfg-{{item.name}}
regexp='^HWADDR=.*'
line="HWADDR={{mac.stdout}}"
with_items:
- "{{ interfaces_ipv4 }}"
tags:
- set_mac
Contents of variable file
#/root/tempplate.yml
- name: ens35
bootproto: dhcp
- name: ens34
bootproto: none
When executing:
TASK: [mac | Setting MAC] ***************************************************** fatal: [192.168.211.146] => One or more undefined variables: 'dict' object has no attribute 'stdout'
FATAL: all hosts have already failed -- aborting
Ansible treats values of the extra variables as strings. To pass values that are not strings, we need to use JSON format. To pass extra vars in JSON format we need to enclose JSON in quotation marks: ansible-playbook extra_var_json.
You can nest two looping tasks using include_tasks . However, by default Ansible sets the loop variable item for each loop. This means the inner, nested loop will overwrite the value of item from the outer loop.
item is not a command, but a variable automatically created and populated by Ansible in tasks which use loops. In the following example: - debug: msg: "{{ item }}" with_items: - first - second. the task will be run twice: first time with the variable item set to first , the second time with second .
Defining multiple when conditions in AnsibleIf both conditions are true, then issue the reboot command using the Ansible reboot module. Otherwise, skip the reboot option.
register
works a bit differently when used inside loops (see here). In that case, your variable will have a results
item, which is a list with the result of each iteration as items. Each item in that list will also have an item
item, with the element iterated on.
For example:
mac: {
msg: "All items completed",
results: [
{
changed: True,
stdout: "some_stdout",
item: {
name: "some_name1"
}
},
{
changed: True,
stdout: "some_stdout2",
item: {
name: "some_name2"
}
}
]
}
You could then loop over that instead of the original list:
- name: Setting MAC
lineinfile:
state=present
dest=/etc/sysconfig/network-scripts/ifcfg-{{item.item.name}}
regexp='^HWADDR=.*'
line="HWADDR={{item.stdout}}"
with_items: mac.results
tags:
- set_mac
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With