Search code examples
ansibleansible-inventory

Ansible - How to add the client list in inventory file through environment variable


I have the following inventory file

[vm_group]
xyz001.hq.company.com
xyz002.hq.company.com


[vm_group:vars]
ansible_connection=winrm
ansible_winrm_transport=ntlm
ansible_port=5986
ansible_winrm_server_cert_validation=ignore  

I have a environment variable called CLIENT_LIST

echo $CLIENT_LIST
xyz001.hq.company.com,xyz002.hq.company.com

How can I do something like this

[vm_group]
${CLIENT_LIST}

so that the inventory group can be set dynamically.
I tried doing it the way I have shown above but it is not picking up the environment variable values.
Do you have any other recommendation for dynamic list. Environment variable would be my first preference though.


Solution

  • There are two answers to your question: multiple plays, or a dynamic inventory plugin; there is no such thing as variable substitution in the static inventory files

    For the multiple-plays version, one would use add_host::

    - hosts: localhost
      connection: local
      tasks:
      - add_host:
          name: '{{ item }}'
          groups:
          - vm_group
        with_items: '{{ lookup("env", "CLIENT_LIST").split(",") }}'
    
    - hosts: vm_group
      # and you're of to the races
    

    For the dynamic inventory version, the world is your oyster: https://docs.ansible.com/ansible/2.9/plugins/inventory.html#plugin-list