0

也许我以错误的方式接近这个。我刚开始使用 Ansible,最近无法解决这个问题:

所以这是我想要做的一个片段:

vars:
    var1: "true"
    var2: "false"
    var3: "true"


  tasks:
  - name: my-name
    docker_container:
      name: my-name
      image: image/image
      state: started
      cap_drop: all
      pull: yes
      recreate: yes
      restart_policy: always
      env:
        env1: "value"
        env2: "value"
        env3: "value"

所以想法是将var1到var3设置为“true”或“false”,然后根据vars将env1的值设置为env3。

例如:

如果 var1 为真,则 env1 应包含“某个值”。但如果 var1 为假,则 env1 应包含“另一个值”。

我还将使用 AWX 并通过“SURVEYS”更改变量的值。

当然,我愿意接受其他建议。你们会怎么解决这个问题?

4

2 回答 2

1

为所有环境变量设置默认值,并根据条件使用 set_facts 设置/修改值。

下面是示例代码:

vars:
    var1: "true"
    var2: "false"
    var3: "true"
    envValue1: "some value"
    envValue2: "some value"
    envValue3: "some value"

  tasks:
  - set_fact:
      envValue1: "another value"
    when: "{{var1}}" != "true"

  - set_fact:
      envValue2: "another value"
    when: "{{var2}}" != "true"

  - set_fact:
      envValue3: "another value"
    when: "{{var3}}" != "true"

  - name: my-name
    docker_container:
      name: my-name
      image: image/image
      state: started
      cap_drop: all
      pull: yes
      recreate: yes
      restart_policy: always
      env:
        env1: "{{envValue1}}"
        env2: "{{envValue2}}"
        env3: "{{envValue3}}"
于 2019-02-14T13:06:52.057 回答
0

Don't clutter your code with set_facts, you can use Jinja2 if expression or ternary filter:

  - name: my-name
    docker_container:
      name: my-name
      image: image/image
      state: started
      cap_drop: all
      pull: yes
      recreate: yes
      restart_policy: always
      env:
        env1: "{{ 'some value' if not var1 else 'another value' }}"
        env2: "{{ var2 | ternary('some value', 'another value') }}"
于 2019-02-14T19:27:30.620 回答