Skip to main content

How to use variables as arguments in Ansible

Learn how to use variables on the command line to pass data into your Ansible playbook at runtime.
How to pass extra variables to an Ansible playboook

Image by Chuk Yong from Pixabay

When you write an Ansible playbook, you sometimes need to pass data into your play at runtime. To do that, you can use a variable, a sort of placeholder for data that's meant to be determined at some point in the future.

There are lots of places to create variables for your playbooks, such as an inventory file, included files, or even dynamically in your playbook itself. However, you can also pass variables in the terminal when you launch your playbook.

[ AnsibleFest is the automation experience. Join us October 18-19 in Chicago. ]

Using a variable

To use a variable in a playbook, you reference it in curly braces ({{ }}). For example, this simple playbook uses the debug module to print the value of a variable to the terminal:

- hosts: localhost
    - name: echo a variable
        msg: "{{ my_var }}"

Because the variable hasn't been defined, the play results in an error:

$ ansible-playbook ./example.yaml
fatal: [localhost]: FAILED! =>
{"msg": "The task includes an option with an undefined variable.
The error was: 'my_var' is undefined...

[ Get started with IT automation with the Ansible Automation Platform beginner's guide. ]

To define a variable dynamically when you run a playbook, use the --extra-vars option along with the key and value of the variable you want to define. In this example, the key is my_var because that's the string referenced in the playbook, and the value is any string you want the variable to contain.

$ ansible-playbook --extra-vars my_var=foo  ./example.yaml
TASK [echo a variable] ****************************
ok: [localhost] => {
    "msg": "foo"

PLAY RECAP ****************************************
localhost : ok=2    changed=0    failed=0 [...]

This time, the variable's value is passed into Ansible through the command option and successfully printed to the terminal.

Variables and Ansible

Ansible supports many ways of passing variables into scripts, generating variables within scripts, and even processing variables as part of a playbook's tasks. For more information on how to process variables in a playbook using filters, read 2 practical ways to use filters to manipulate data in Ansible and Network configuration with Ansible filters.

Check out these related articles on Enable Sysadmin

Topics:   Ansible   Automation  
Author’s photo

Seth Kenlon

Seth Kenlon is a UNIX geek and free software enthusiast. More about me

Red Hat Summit 2022: On Demand

Get the latest on Ansible, Red Hat Enterprise Linux, OpenShift, and more from our virtual event on demand.

Related Content