Ansible:docker env条件变量

时间:2019-02-14 11:56:39

标签: docker ansible conditional ansible-awx

也许我正在以错误的方式来对待。我刚开始使用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为true,则env1应包含“某些值”。但是,如果var1为false,则env1应该包含“另一个值”。

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

我当然愿意接受其他建议。你们将如何解决呢?

2 个答案:

答案 0 :(得分:0)

设置所有环境变量的默认值,并使用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}}"

答案 1 :(得分:0)

不要用set_facts使代码混乱,可以使用Jinja2 if expressionternary过滤器:

  - 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') }}"