-
-
Save OldCrowEW/b562a6bf950534446d14533a2ecb48dc to your computer and use it in GitHub Desktop.
## tasks: | |
- name: Build hosts file | |
lineinfile: dest=/etc/hosts regexp='.*{{ item }}$' line="{{ hostvars[item].ansible_default_ipv4.address }} {{ item }}" state=present | |
when: hostvars[item].ansible_default_ipv4 is defined | |
with_items: "{{ groups['all'] }}" | |
- name: Add aliases for hosts excluded in playbook to hosts file | |
lineinfile: dest=/etc/hosts regexp='.*{{ item }}$' line="{{ hostvars[hostvars[item].ansible_host].ansible_default_ipv4.address }} {{ item }}" state=present | |
when: hostvars[item].ansible_default_ipv4 is not defined | |
with_items: "{{ groups['all'] }}" | |
## inventory: | |
[jenkins] | |
jenkins | |
[logstash] | |
logstash1 ansible_host=web1 | |
logstash2 ansible_host=web2 | |
logstash3 ansible_host=web3 | |
[web] | |
web1 | |
web2 | |
web3 |
halberom
commented
Jul 17, 2017
•
cool. this is an improvement over the current task. its actually the second giving us problems. thanks for the help!
fatal: [loststash1: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'dict object' has no attribute 'ansible_default_ipv4'\n\nThe error appears to have been in 'ansible/roles/hostname/tasks/main.yml': line 34, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Build hosts file\n ^ here\n"}
ah, sorry, should have realised - I always forget that address is a sub key of ansible_default_ipv4
. You need an interim default. I can't think of the ansible filter way at present - here it is in the python way.
## tasks:
- name: Build hosts file
lineinfile:
dest: /etc/hosts
regexp: '.*{{ item }}$'
line: "{{ hostvars[item].get('ansible_default_ipv4', {}).get('address', hostvars[item]['ansible_host']) }} {{ item }}"
state: present
with_items: "{{ groups['all'] }}"
in summary, try and get the key (if not defined use empty dict) then get address key (if not defined use ansible_host).