Pick a variable based on if another variable is set

13 views
Skip to first unread message

John Simmons

unread,
Apr 24, 2019, 3:02:49 PM4/24/19
to Ansible Project
I want to add a var of testing to my playbook, and when that var is set to true i want var1 to be used but if its nor set to true, i want it to use var2. Is this possible?

below is a non working example but  I hope it illustrates what i want it to do.
-----------------------------------------------------------------------------------

- name: Check logs and report to slack
  hosts: 
  become: yes
  remote_user: "{{ platform_user }}"

  vars:
    testing: true

  vars_files:
    - "../../vault/slack.yml"

  tasks:

    - name: check logs for step took
      shell: "some command"
      register: command_output

    - name: sucess notification message via Slack
      slack:
        token: "{% if {{ testing }} == 'true' %}{{ slack_slacktesting }}{% else %}{{ slack_devops }}{% endif %}"
        msg: "*{ command_output.stdout }}"
        channel: "{% if {{ testing }} == 'true' %}#slacktesting{% else %}#devops{% endif %}"
        username: 'Ansible'
        link_names: 0
        parse: 'full'
        color: 'good'
      delegate_to: localhost
      when: command_output_completed.stdout | search("COMPLETED")
      ignore_errors: yes

------------------------------------------------------------------------------------------------

Hope you can help or at least point me in the right direction.

Kai Stian Olstad

unread,
Apr 24, 2019, 3:40:22 PM4/24/19
to ansible...@googlegroups.com
On 24.04.2019 21:02, John Simmons wrote:
> I want to add a var of testing to my playbook, and when that var is set to
> true i want var1 to be used but if its nor set to true, i want it to use
> var2. Is this possible?
>
> below is a non working example but I hope it illustrates what i want it to
> do.
> -----------------------------------------------------------------------------------
>
> - name: Check logs and report to slack
> hosts:
> become: yes
> remote_user: "{{ platform_user }}"
>
> * vars:*
> * testing: true*
>
> vars_files:
> - "../../vault/slack.yml"
>
> tasks:
>
> - name: check logs for step took
> shell: "some command"
> register: command_output
>
> - name: sucess notification message via Slack
> slack:
> token: *"{% if {{ testing }} == 'true' %}{{ slack_slacktesting }}{% else %}{{ slack_devops }}{% endif %}"*

You are already in template mode so you can't use {{ }} inside {% %}, so delete the {{ }} and it will work

{% if testing == 'true' %}{{ slack_slacktesting }}{% else %}{{ slack_devops }}{% endif %}


There are some shorter version you could use:

{{ slack_slacktesting if testing == 'true' else slack_devops }}

or

{{ (testing == 'true') | ternary(slack_slacktesting, slack_devops) }}


--
Kai Stian Olstad
Reply all
Reply to author
Forward
0 new messages