Changing the variable value through looping in ansible playbook

Viewed 32

I have the following Ansible playbook: remove.yaml that have two variable and it loops through a set of items.

- name: calling helm commands tasks
  include_tasks: helm_commands.yaml
  vars:
    name_spce: "sdn"
    extra_parameter: "--no-hooks"

  loop: ['dre','hju','cny','wer','guy']

The included tasks file helm_commands.yaml is:

---

- name: check if {{item}} exist
  shell:
    cmd: /usr/local/bin/helm3 get manifest {{item}} --namespace {{name_spce}}
  register: get_release
  failed_when: get_release.rc ==2

- name: helm delete {{item}}
  shell:
    cmd: /usr/local/bin/helm3 delete {{item}} {{extra_parameter}} --namespace {{name_spce}}
  when: get_release.rc ==0

The problem is I want the variable extra_parameter take the value --no-hooks only when it loop through the first item 'dre' otherwise take empty value ''

extra_parameter: "--no-hooks" when loop with 'dre'

                 ""           when loop with other items
1 Answers

You could use the extended loop functionalities for that:

- name: calling helm commands tasks
  include_tasks: helm_commands.yaml
  vars:
    name_spce: "sdn"
    extra_parameter: "{{ '--no-hooks' if ansible_loop.first }}"
  loop: ['dre','hju','cny','wer','guy']
  loop_control:
    extended: yes

If you want to add the flag --no-hooks regardless of the position of dre in the list, then it is as simple as:

- name: calling helm commands tasks
  include_tasks: helm_commands.yaml
  vars:
    name_spce: "sdn"
    extra_parameter: "{{ '--no-hooks' if item == 'dre' }}"
  loop: ['dre','hju','cny','wer','guy']
Related