Is it possible to change a role variable default value according to some condition (i.e. the value of another variable)?
Details
I have two related variables for a command, env
and composer_opts
.
If both are left at default (env = "prod"
and composer_opts = "--no-dev"
) everything is ok.
If I change env
to dev
, the default for the other one will break my command, so I always need to set both. Would it be possible to avoid this by setting a conditional default value with a custom script / if?
Important: I don't want to always set the composer_opts
value according to the env
value. I want to set it only if it's not already set (i.e. a dynamic default value).
Pseudocode
I would like to do something like this (following code is not valid, just pseudocode to express my need)
---
# defaults/main.yml
env: prod
composer_opts:
when: "{{env}}" = 'prod'
'--no-dev --optimize-autoloader --no-interaction'
when: "{{env}}" = 'dev'
''
I suggest this solution:
It will set
composer_opts
variable to string""
when variableenv
is equal to 'dev
'.Here is example of playbook based on updated question:
Sample output:
While @Navern's answer does work, I found the embedded Jinja2 notation (
"{% if env == 'prod' %} ...
) to be extremely susceptible to notation and thus rather fragile. For example, when wrapping the line in question for better readability such as in this untested code:I ended up with unexpected results, such as additional whitespace or
\n
incomposer_opts
.The approach I use is much dumber, but also more stable:
I also found this blog post to be useful which essentially follows the same approach.
Ansible set_fact based on condition in one liner :
set_fact: path_install: | {% if reportviewer_state == 'absent' and reportviewer_handler[reportviewer_package].name == 'ReportViewer_2010.exe' %} C:\Windows\System32\msiexec.exe {% else %} {{ url_base_repository }}{{ reportviewer_handler[reportviewer_package].name }} {% endif %}