Search code examples
azureazure-devopsansibleansible-inventory

How to execute ansible-playbook with Azure Dynamic Inventories along with keyed groups conditional


I am trying to use azure_rm plugin in ansible to generate dynamic hosts on Azure platform. With keyed group conditional, I am able to successfully make it work with an ansible ad-hoc command. However, it does not work when I try to pass the same with "ansible-playbook". Can anyone please help how could I run an ansible-playbook the same way ?

Below is my dynamic inventory generation file:

---
plugin: azure_rm
auth_source: msi
keyed_groups:
- prefix: tag
  key: tags

When I use the file to ping the target VM, below is a success response.

Command used:

ansible -m ping tag_my_devops_ansible_slave -i dynamic_inventory_azure_rm.yml

Response:

devops-eastus2-dev-ansibleslave-vm_2f44 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

However, when I use the same with ansible-playbook, I get the below error. Command used:

ansible-playbook  tag_cdo_devops_ansible_slave -i dynamic_inventory_azure_rm.yml test-playbook.yml

Error:

ansible-playbook: error: unrecognized arguments: test-playbook.yml

Can anyone please help on how to execute an ansible-playbook for the above use case ?


Solution

  • The ansible-playbook command does not accept a list of targets on the command line, rather the playbook file has hosts: as a top-level key indicating the hosts to which the playbook will apply.

    So, if the playbook is always going to be used with that tag, you can just indicate that in the playbook:

    - hosts: tag_cdo_devops_ansible_slave
      tasks:
      - debug: var=ansible_host
    

    It also appears that hosts: does honor jinja2 templating, so you can achieve what you're trying to do via:

    - hosts: '{{ azure_playbook_hosts }}'
      tasks:
      - debug: var=ansible_host
    

    and then ansible-playbook -e azure_playbook_hosts=tag_cdo_devops_ansible_slave -i dynamic_inventory_azure_rm.yml test-playbook.yml

    Or you can create a dedicated inventory file that only returns hosts matching your desired tag, and then use -i for that inventory along with hosts: all in the playbook file.