Skip to content

Instantly share code, notes, and snippets.

@OldCrowEW
Forked from rothgar/main.yml
Created February 7, 2017 02:35
Show Gist options
  • Save OldCrowEW/7818e32c14a3868cfbb54023a5734669 to your computer and use it in GitHub Desktop.
Save OldCrowEW/7818e32c14a3868cfbb54023a5734669 to your computer and use it in GitHub Desktop.
Generate /etc/hosts with Ansible
# Idempotent way to build a /etc/hosts file with Ansible using your Ansible hosts inventory for a source.
# Will include all hosts the playbook is run on.
# Inspired from http://xmeblog.blogspot.com/2013/06/ansible-dynamicaly-update-etchosts.html
- 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.address is defined
with_items: groups['all']
@starx
Copy link

starx commented Jun 15, 2017

I get the following:

The conditional check 'hostvars[item].ansible_default_ipv4.address is defined' failed. The error was: error while evaluating conditional (hostvars[item].ansible_default_ipv4.address is defined): 'ansible.vars.hostvars.HostVars object' has no attribute u"groups['all']"\n\nThe error appears to have been in '/home/starx/dev/env/vms/vagrant.packer.centos731611.ansible/ansible/roles/init/tasks/main.yml': line 14, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n- debug: msg="{{ hostvars }}"\n- name: "Build hosts file"\n ^ here\n

Using Ansible 2.3

@juanluisbaptiste
Copy link

Mee too on 2.4.

@cod3fr3ak
Copy link

Same here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment