Setting Variables Conditionally

32 views
Skip to first unread message

Ryan

unread,
Aug 7, 2017, 11:08:40 PM8/7/17
to Ansible Project
I need to set some variables that are the same no matter the client, and other variables need to be set conditionally based on values from Ansible facts.  Basically I need an if/else case statement.  What is the correct way to do this?

Some simple examples can be found here (http://docs.ansible.com/ansible/latest/playbooks_conditionals.html#conditionals) but  this doesn't cover else conditions, and if I remove the second instance of VAR4, and put in condition that is not met, it still sets VAR4, when the match doesn't exist, so it seems like the "when" is not being evaluated.


---

- name: Playbook Name

  hosts:  all

  gather_facts: yes

  tasks:

 

     - name: Set variables

       vars:

         VAR1: 5

         VAR2: 10

         VAR3: 0

 

         VAR4: 100

         when: (ansible_some_fact == "some_value1") or

               (ansible_some_fact == "some_value2")

 

         VAR4: 200

         when: (ansible_some_fact == "some_value3") or

               (ansible_some_fact == "some_value4")

benno joy

unread,
Aug 8, 2017, 12:58:12 AM8/8/17
to ansible...@googlegroups.com
some ways to do this would be


using filters (clean way)
set_fact:
myvar: "{{ (ansible_os_family == 'RedHat') | ternary(100,200) }}"

or same thing via jinja conditionals

{{ 100 if ansible_os_family == 'RedHat' else 200 }}

with some 'or's

{{ 100 if ansible_os_family == 'RedHat' or ansible_user_id ==
'vagrant' else 200 }}
> --
> You received this message because you are subscribed to the Google Groups
> "Ansible Project" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to ansible-proje...@googlegroups.com.
> To post to this group, send email to ansible...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/ansible-project/bafd7316-db91-47ec-98ee-2f71bc4005aa%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Ryan

unread,
Aug 8, 2017, 3:50:49 AM8/8/17
to Ansible Project
This seems to be working, but is there a more readable way to write this?

size: "{{ 300 if 'string1’ in ansible_fact or 'string_2' in ansible_fact or 'string_3' in ansible_fact or 'string_4' in ansible_fact else 100 if 'string_5' in ansible_fact or 'string_6' in ansible_fact or 'string_7' in ansible_fact else 200 if 'string_8' in ansible_fact }}"




Reply all
Reply to author
Forward
0 new messages