Skip an item in an Ansible task loop

5.4k views Asked by At

Let's say I have a group var named show_canada which is a boolean. I have the following task:

    - name: install conf file
      template: src="example.conf.j2" dest="/etc/{{ item }}/example.conf"
      sudo: yes
      with_items:
        - usa
        - brazil
        - canada
        - japan
        - turkey

How can I have the task skip the canada item depending on the value of the show_canada boolean? I guess I can have a when field that checks if the item == 'canada' and show_canada is true? There has to be a better/nicer way to accomplish this, any suggestions? And if I have multiple tasks that require this same filtering, is there some global way I can skip certain items?

1

There are 1 answers

1
ant31 On

In those cases what I'm doing is including status with the value in a dict:

- name: install conf file
  template: src="example.conf.j2" dest="/etc/{{ item }}/example.conf"
  sudo: yes
  when: item.display is true
  with_item:
    - {name: usa, display: true}
    - {name: brazil, display: true}
    - {name: canada, display: false}
    - {name: japan, display: true}
    - {name: turkey, display: true}

You even probably can set the display value from a var

   - {name: canada, display: {{show_canada}} }