Ansible add_host not adding to hosts file

amazon ec2ansibleansible-inventoryansible-playbook

Ansible Version: 1.9.2

I'm running a playbook that will launch an EC2 instance. I have the site.yml with all the variables and use a role to launch the EC2 instance. Here's the main.yml for the ec2_launch

---
- name: create EC2 instance
  ec2:
    key_name: "{{ keypair }}"
    group_id: "{{ security_group }}"
    instance_type: "{{ instance_type }}"
    image: "{{ image }}"
    region: "{{ region }}"
    vpc_subnet_id: "{{ vpc_subnet_id }}"
    assign_public_ip: yes
    wait: True
    instance_tags:
      Name: "{{ instance_tag }}"
      Environment: "{{ instance_tag2 }}"
    exact_count: 1
    count_tag:
      Name: "{{ instance_tag }}"
      Environment: "{{ instance_tag2 }}"
    monitoring: yes
  register: ec2
- name: add ec2 instance to hosts
  add_host: name={{ item.private_ip }} groups=group_name
  with_items: ec2.instances
- name: wait for SSH
  wait_for: host={{ item.private_ip }} port=22 delay=60 timeout=320 state=started
  with_items: ec2.instances

When I run with -vvv option, this is the output during the add_hosts:

TASK: [ec2_launch | add ec2 instance to hosts] ********************************
creating host via 'add_host': hostname=10.50.101.93
added host to group via add_host module: group_name

The IP is correct and the group name is correct but when I check the ansible hosts file, it has not been modified. I made sure to include the [group_name] in the hosts file. There are no errors during the run and not sure why it's not being added to the file.

There's an 'add_host' example on this page: http://docs.ansible.com/ec2_module.html
instead of name and groups, they use hostname, groupname (which I believe are old). I've tried those as well. Not sure what I'm missing.

Best Answer

The add_host task does not add it to the host file, it adds it to the in-memory list of hosts.

Adding to the hosts file wouldn't work in all cases- for instance, AWS users often use the ./ec2.py script, which is a binary executable that replaces their text-based hosts file.

Related Topic