Created
July 17, 2017 15:35
-
-
Save OldCrowEW/b562a6bf950534446d14533a2ecb48dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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 |
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).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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"}