How to add optional variables to a managed command line and check their existence in the tutorial?

I would like to run a specific task only if a flag is specified on the command line. For example, I would like to run the ansible-playbook command with the following: --extra-vars "composer-install=true" . I will need a task that checks if the composer-install variable is set, and if it is set and true, run the task that composer install runs. I'm not quite sure how to do this last part.

+6
source share
2 answers

The reason you get the error message is because you are accessing a variable that has never been set. It seems you are using the existence of extra-var as an indication that you want to install the composer (i.e. you never go through --extra-vars = "composer-install = false"), so you can go with is defined :

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

But variables can be passed through filters, which can be useful for this case, because it still allows you to pass true / false, until it determines that the variable still works:

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

Some additional conditions can be found here: http://docs.ansible.com/playbooks_conditionals.html

Jinja2 filters are very useful for several reasons, so more here: http://docs.ansible.com/playbooks_variables.html#jinja2-filters

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

+8
source

I think what you are looking for when the parameter .

 - name: optional composer install shell: composer install when: composer-install 
+1
source

Source: https://habr.com/ru/post/977783/


All Articles