Running Playbooks w/ Dynamic Variables

I am currently using Ansible to deploy a resource in Azure as follows:

- name: Deploy a Resource Group in Azure
  hosts: localhost
gather_facts: no
  connection: local

  vars:
    resource_group: test-rg
    location: eastus2

  tasks:
    - name: Create a resource group in Azure
azure.azcollection.azure_rm_resourcegroup:
name: "{{ resource_group }}"
location: "{{ location }}"
state: present
register: rg_output

My question is how can I define the above playbook for Ansible to run as expected but allowing users to pick or define the value for the vars.

Example, I want to run the above playbook to create a resource group called “dev”. Is there a way I can programmatically define the playbook to allow the user to input the variables at run time?

Something like:
$ ansible-playbook deploy_rg.yaml name = dev region = useast2

Do you mean this - “defining variables at runtime”? Using Variables — Ansible Community Documentation

I think that works. I’m not sure if there’s a more traditional way in Ansible to run playbooks but define the name of the resource I’m building at runtime. Usually this would be a blank field in a form I fill out in some front end. I guess that works but curious how others configure Ansible from a CI/CD automation deployment lens to create resources repeatedly and not hard code variables in the playbook. Is the URL you recommended above the best / default option for Ansible?

If variable values change for each run, then yes, you have to feed the new values every time you run it. I do this in one of two ways, depending on the amount of variables needed:

  1. Many variables needed - I create a variables file for each implementation, and feed the whole file - -e "@config/variable-file.yml"

  2. Minimum amount of variables needed - I feed each variable - -e '{"hosts_used":"server1","url_name":"url-server1.test.com"}'

This was extremely helpful. Thank you!

You’re welcome. You can mark one of my responses as the answer and set this as solved, to help people that might be looking for this information in the future.

You can even use interactive prompts:

https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_prompts.html#interactive-input-prompts

FYI, it won’t prompt if you already passed the info as extra vars.

1 Like