Home > front end >  Ansible jinja if statement in list and check correct value
Ansible jinja if statement in list and check correct value

Time:12-04

I wanto to check if site variable exist on inventory, if there is not exist, I print error message. I find to print value, so I want to check if newyork or paris value are written correclty.

variable file

server:
  server1:
    name: server1
    site: newyork
    serie: "[100,200,300]"
    
  server2:
    name: server2
    site: paris
    serie: "[0,1,2]"

server3:
        name: server2
        site: madrid
        serie: "[0,1,2]"

task.yml

- name: template file
  template:
    src: "toto/toto.j2"
    dest: "/tmp/toto_{{ item.value.name }}"
  with_dict: "{{ server }}"

toto/toto.j2

    the {{ item.value.name }}
    {% if ("{{ item.value.site }}" == "newyork") or ("{{ item.value.site }}" == "paris") %}
    {{ item.value.site }} = {{ item.value.serie }}
  {% endif %}

I think to try with if statement, if paris and newyork is written correctly. but the if statement is always false. how to solve it ?

but how to print a error message and check value on inventory, if someone write madrid for instance. I just want to accept paris and nework value.

CodePudding user response:

Q: "If someone write London, I have got an error"

A: Test the site is in the dictionary, e.g. given my_site=London

    - fail:
      when: my_site not in server|json_query('*[].site')

you'll get the error

fatal: [localhost]: FAILED! => changed=false 
  msg: Failed as requested from task

CodePudding user response:

From the description in your question, and your comments - it appears that you don't want the template to be created for the server if the item.value.site does not match newyork or paris.

For this, we can do a comparison such as: item.value.site in ["newyork", "paris"].

You can have this condition on your template task, and templates will be skipped for any servers whose site is NOT "newyork" or "paris".

    - name: template file
      template:
        src: toto/toto.j2
        dest: "/tmp/toto_{{ item.value.name }}"
      when: item.value.site in ["newyork", "paris"]
      with_dict: "{{ server }}"
  • Related