How to Pass Variables to Ansible Playbook CLI


If you need to pass a variable to Ansible playbook, using the command line, then you can do the following:

Option 1 – Specifying command line arguments

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

N.B. --extra-vars specified variables will override any variables with the same name defined inside the playbook.

You can also read up on Passing Variables On The Command Line (Wayback Machine link to maintain versioning)

Option 2 – Specify a YML file

You can also specify a .yml file with the variables:

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

This can also be enhanced with environment variables:

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