Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass variable to ansible playbook in the command line?

People also ask

How do you pass variables in Ansible playbook command?

To pass a value to nodes, use the --extra-vars or -e option while running the Ansible playbook, as seen below. This ensures you avoid accidental running of the playbook against hardcoded hosts.

How do you use Ansible variables in playbook?

Ansible uses variables to manage differences between systems. With Ansible, you can execute tasks and playbooks on multiple different systems with a single command. To represent the variations among those different systems, you can create variables with standard YAML syntax, including lists and dictionaries.

How do you define variables in the command line interface while executing playbook?

To define a variable in a playbook, simply use the keyword vars before writing your variables with indentation. To access the value of the variable, place it between the double curly braces enclosed with quotation marks. In the above playbook, the greeting variable is substituted by the value Hello world!


Reading the docs I find the section Passing Variables On The Command Line, that gives this example:

ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"

Others examples demonstrate how to load from JSON string (≥1.2) or file (≥1.3)


Other answers state how to pass in the command line variables but not how to access them, so if you do:

--extra-vars "version=1.23.45 other_variable=foo"

In your yml file you assign these to scoped ansible variables by doing something like:

vars:
    my_version: "{{ version }}"
    my_other_variable: {{ other_variable }}

An alternative to using command line args is to utilise environmental variables that are already defined within your session, you can reference these within your ansible yml files like this:

vars:
    my_version: "{{ lookup('env', 'version') }}"
    my_other_variable: {{ lookup('env', 'other_variable') }}

ansible-playbook release.yml -e "version=1.23.45 other_variable=foo"

You can use the --extra-vars option. See the docs


For some reason none of the above Answers worked for me. As I need to pass several extra vars to my playbook in Ansbile 2.2.0, this is how I got it working (note the -e option before each var):

ansible-playbook site.yaml -i hostinv -e firstvar=false -e second_var=value2

ansible-playbook test.yml --extra-vars "arg1=${var1} arg2=${var2}"

In the yml file you can use them like this

---
arg1: "{{ var1 }}"
arg2: "{{ var2 }}"

Also, --extra-vars and -e are the same, you can use one of them.