大网数据广告活动
服务器运维问答

Ansible change default value according to a condition

· 52CE 我爱测

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 ( en…

问题原文

原帖链接 · Francesco Abeni · CC BY-SA 3.0

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'
        '' 

社区高分解答

原帖链接 · ssc · CC BY-SA 3.0

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:

composer_opts: >
               "{% if env == 'prod' %}
                   '--no-dev --optimize-autoloader --no-interaction'
                {% else %}
                   ''
                {% endif %}"

I ended up with unexpected results, such as additional whitespace or \n in composer_opts.

The approach I use is much dumber, but also more stable:

- name: set composer_opts for dev env
  set_fact:
     composer_opts: ''
     when: "{{env}}" == 'dev'

- name: set composer_opts for prod env
  set_fact:
     composer_opts: '--no-dev --optimize-autoloader --no-interaction'
     when: "{{env}}" == 'prod'

I also found this blog post to be useful which essentially follows the same approach.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2015-08-21)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。