Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add optional variables in the ansible command line and check for their existence in the playbook?

I would like to run a particular task only if a flag is given in the command line. For example, I would like to run the ansible-playbook command with the following: --extra-vars "composer-install=true". I would somehow need a task that checks if the composer-install variable is set, and if set and equal to true, run the given task which runs composer install. I'm not quite sure how to do that last part.

like image 665
timetofly Avatar asked Nov 05 '14 20:11

timetofly


1 Answers

The reason you get an error is because you're accessing a variable that has never been set. You seem to be using the existance of the extra-var as an indication that you want composer install to run (i.e. you're never passing --extra-vars="composer-install=false"), so you could go with is defined:

- shell: composer install
  when: composer-install is defined

But the variables can be passed through filters, which can be useful for this case, because it still allows you to pass true/false while not defining the variable at all still works:

- shell: composer install
  when: composer-install|default(false)

Some more on conditionals can be found here: http://docs.ansible.com/playbooks_conditionals.html

The jinja2 filters are very useful for more than one reason, so more on those here: http://docs.ansible.com/playbooks_variables.html#jinja2-filters

And finally the complete list of built-in jinja2 filters here: http://jinja.pocoo.org/docs/dev/templates/#builtin-filters

like image 155
Ramon de la Fuente Avatar answered Sep 30 '22 10:09

Ramon de la Fuente