2

my below ansible (2.1.1.0) playbook is throwing "skipping: no hosts matched" error when playing for host [ec2-test]. The ansible hosts file has the fqdn of the newly created instance added. It runs fine if if i re run my playbook second time. but 1st time running throws no hosts matched error :(

my playbook:

  ---
 - name: Provision an EC2 instance
   hosts: localhost
   connection: local
   gather_facts: no
   become: False
   vars_files:
   - awsdetails.yml
   tasks:
    - name: Launch the new EC2 Instance
      ec2:
       aws_access_key: "{{ aws_id }}"
       aws_secret_key: "{{ aws_key }}"
       group_id: "{{ security_group_id }}"
       instance_type: "{{ instance_type }}"
       image: "{{ image }}"
       key_name: "{{ ssh_keyname }}"
       wait: yes
       region: "{{ region }}"
       count: 1
      register: ec2
    - name: Update the ansible hosts file with new IP address
      local_action: lineinfile dest="/etc/ansible/hosts" regexp={{ item.dns_name }} insertafter='\[ec2-test\]'line="{{item.dns_name}} ansible_ssh_private_key_file=/etc/ansible/e2-key-file.pem ansible_user=ec2-user"
      with_items: ec2.instances
    - name: Wait for SSH to come up
      wait_for: host={{ item.public_dns_name }} port=22 delay=60 timeout=320 state=started
      with_items: ec2.instances
 - name: playing ec2-test instances
   hosts: ec2-test
   gather_facts: no

my hosts file has these inventories

[localhost]
localhost 
....
[ec2-test]
ec2-54-244-180-186.us-west-2.compute.amazonaws.com

Any idea why i am getting the skipping: no hosts matched error if showing up here? any help would be greatly appreciated

Thanks!

1 Answer 1

0

It seems like Ansible reads the inventory file just once and does not refresh it after you add an entry into it during the playbook execution. Hence, it cannot add the newly added host.

To fix this you may force Ansible to refresh the entire inventory with the below task executed after you update the inventory file:

- name: Refresh inventory to ensure new instaces exist in inventory
  meta: refresh_inventory

or you may not update the inventory file at all and use the add_host task instead:

- add_host:
    name: "{{ item.dns_name }}"
    groups: ec2-test
  with_items: ec2.instances
Sign up to request clarification or add additional context in comments.

2 Comments

Did the person who asked this question say that he added new hosts "during playbook execution". Sorry this answer doesn't make sense to me.
The second tak of the playbook does exactly that: Update the ansible hosts file with new IP address.

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.