Deano Deano - 1 month ago 21
YAML Question

Ansible Dynamic Inventory

I'm running a playbook which houses multiple roles targets multiple hosts

The goal is to deploy a VM and use it's IP to deploy an app.

My playbook, has two roles, using "build_vm" role I'm able to display IP address via debug, yet when passing ipaddr variable to second role, Ansible complains that the variable is not defined

- hosts: linux
become: true

roles:
- build_vm

- tasks:
- debug: msg="{{ ipaddr }}"

- hosts: "{{ ipaddr }}"
roles:
- deploy_app


I have used set_fact with and ran into same issue, I wonder what I should be using here? dynamic inventory? I have searched sparse docs online and I'm unable to find an intuitive example to follow.

Answer

There are many ways to using add_host. In this example, I am adding the new host to a group and using it in a later play.

- hosts: linux
  become: true

  roles:
  - build_vm

    - tasks:
       - debug: msg="{{ ipaddr }}"  
       - name: Add ipaddr to host inventory
         add_host: name="{{ ipaddr }}" group=NewHostGroup    

- hosts: NewHostGroup
  roles:
  - deploy_app