Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload Ansible's dynamic inventory

I'm using Ansible to setup EC2 instances and deploy an app. There's a hosts script which gathers tags related servers and groups info. I'd like to run these actions as a single playbook, so

  1. New instances are created if needed
  2. Hosts script loads inventory (including servers' facts)
  3. Deployment playbook works

However, inventory loaded in advance so there is no servers/groups data if servers created/updated during the play. I can 1) separate provision and deployment playbooks 2) use add_host trick to emulate dynamic inventory when servers are updated, but there are drawbacks in those approaches.

Can I force Ansible to reload inventory? My test files are: hosts script:

#!/bin/sh
echo `date` >> log.log
echo "{\"standalone\":[\"localhost\"]}"

Sample playbook.yml:

---
- hosts: all
  tasks:
    - name: show inventory_hostname
      command: echo {{ inventory_hostname }}

I run it ansible-playbook -i hosts playbook.yml -v and see two runs:

$> cat log.log
Thu Mar 12 09:43:16 SAMT 2015
Thu Mar 12 09:43:16 SAMT 2015

but I haven't found a command to double it.

like image 915
Vladimir Chervanev Avatar asked Mar 12 '15 06:03

Vladimir Chervanev


People also ask

How do you maintain dynamic inventory in Ansible?

Ways to manage inventories in AnsibleConvert inventories from legacy formats into Ansible. Use dynamic inventories with plugins, specifically Nmap. Write your own inventory script to generate inventories dynamically. Write an Ansible inventory plugin.

What is a dynamic inventory?

Dynamic Inventory is an inventory management solution that provides inventory control and tracking features. The solution is for small and midsize businesses and can either be installed on-premises or be hosted in the cloud.


2 Answers

With Ansible 2.0+, you can refresh your inventory mid-play by running the task:

- meta: refresh_inventory 
like image 180
James Orenthal Avatar answered Sep 19 '22 12:09

James Orenthal


I found the meta: refresh_inventory to be insufficient.
I had to add an explicit call to ec2.py --refresh-cache first.

- name: refresh inventory
  hosts: localhost
  connection: local
  gather_facts: False
  tasks:
    - name: Refresh EC2 cache
      command: /etc/ansible/ec2.py --refresh-cache
    - name: Refresh in-memory EC2 cache
      meta: refresh_inventory
like image 42
dsz Avatar answered Sep 20 '22 12:09

dsz