5

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

1
  • Please give strong consideration to using Ansible's template module instead of lineinfile. The latter is an antipattern; it tends towards substantial complexity and pain. Commented Nov 6, 2014 at 16:21

1 Answer 1

9

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.