0

Maybe I am approaching this the wrong way. I just started with Ansible and I couldn't solve this problem lately:

So this is a snippet of what I am trying to do:

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"

So the idea is to set var1 to var3 to "true" or "false" and then make the value of env1 to env3 depending on the vars.

So for example:

If var1 is true, the env1 should contain "some value". But if var1 is false, the env1 should contain "an other value".

I would also use AWX and change the value of the vars by "SURVEYS".

I am open to other suggestions, of course. How would you guys solve this?

Lauro
  • 3
  • 2
  • I'd probably just directly set `env1` as a variable and make `env1: "{{ env1_value }}"`, but there are [lots of inline templating options](https://docs.ansible.com/ansible/latest/user_guide/playbooks_templating.html). – David Maze Feb 14 '19 at 12:26

2 Answers2

1

Set the default value for all the environment variables and use set_facts to set/modify the value according to the condition.

Below is the sample code:

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}}"
Sriram
  • 626
  • 7
  • 11
  • Wow, this is it! The set_fact directive was the thing I didn't come across during my google research. Thanks! – Lauro Feb 14 '19 at 15:31
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') }}"
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193