Passing a list on the command line

Is it possible to pass a list as an extra-vars variable on the command line?

I have tried various syntax but it doesn’t work.

E.g.

ansible-playbook my_playbook.yml -i local --extra-vars roles_to_deploy=role1,role2
ansible-playbook my_playbook.yml -i local --extra-vars roles_to_deploy=[role1,role2]
ansible-playbook my_playbook.yml -i local --extra-vars roles_to_deploy=[‘role1’,‘role2’]

Hi Rob, this is possible, you just need to format the extra variables as JSON, as documented here: http://docs.ansible.com/playbooks_variables.html#passing-variables-on-the-command-line

Hi Rob,

Like James said, something like this should work:

ansible-playbook my_playbook.yml -i local -e ‘{ “roles_to_deploy” : [‘role1’,‘role2’]}’

An alternative approach using tags:

variables file: host_vars/ubuntu-trusty64-01

Hmmm, this doesn’t seem to work for the roles parameter.

I tried the following command:

ansible-playbook test.yml -i inventories/local -e ‘{“roles_to_deploy”:[“role1”,“role2”]}’

The test.yml playbook just had:

`
tasks:

  • name: Debug
    debug: msg=“{{ item }}”
    with_items:
    “{{ roles_to_deploy }}”
    `

All good.

I then tried the same command with my original playbook which has:

roles: "{{ roles_to_deploy }}"

I get an error “ERROR: value of ‘roles:’ must be a list”

Hi Rob,

That error occurs because roles were not really designed to be included dynamically like that, so the value is not run through the template engine. This is similar to the problem of using includes + with_* loops in v1, where the variables could come from an inventory source, which would lead to errors or unexpected behavior, as inventory sources are not available at the time the roles are parsed/loaded.

I would recommend using Oswaldo’s method, where available, or simple create more specific playbooks depending on your situation.