Rag
Rag

Reputation: 13

Ansible - when condition

I am very much new to ansible. I would need help in when condition.

Please help to correct below playbook. where as it takes input and displaying output in url.

    - hosts: all
      gather_facts: False
      vars_prompt:
      - name: "region"
        prompt: "Which region"
      tasks:
      - name: url_name
        set_fact:
          - url: "google.com"
            when: {{ region }} == "IN"
          - url: "facebook.com"
            when: {{ region }} == "UK"
          - url: "stackoverflow"
            when: {{ region }} == "US"
          - url: "LinkedIn"
            when: {{ region }} == "AZ"
      - debug:
          msg: url

Upvotes: 1

Views: 391

Answers (1)

Frenchy
Frenchy

Reputation: 17037

instead of typing all if else, i suggest you to create a dictionnary and use the region as index:

- hosts: localhost
  gather_facts: False
  vars:
    regions:
      IN: google.com
      US: stackoverflow        
      AZ: LinkedIn        
      UK: facebook.com 
                  
  vars_prompt:
  - name: "region"
        prompt: "Which region in {{ regions.keys() }}"
        private: no  #to hide the answer typed set yes   
  tasks:
    - debug:
        msg: "{{regions}}" 

    - name: url_name
      set_fact:
        url: "{{ regions[region] }}"

    - debug:
        var: url

some interesting fixes: if you add filter upper, you could accept lower or upper answer:

  set_fact:
    url: "{{ regions[region|upper] }}"

Upvotes: 2

Related Questions