通过在ansible playbook中循环更改变量值

Changing the variable value through looping in ansible playbook

我有以下 Ansible 剧本:remove.yaml 有两个变量,它循环遍历一组项目。

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

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

包含的任务文件 helm_commands.yaml 是:

---

- 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

问题是我希望变量 extra_parameter 只有在循环第一项 'dre' 时才取值 --no-hooks 否则取空值 ''

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

                 ""           when loop with other items

您可以为此使用 extended loop functionalities

- 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

如果你想添加标志--no-hooks而不考虑dre在列表中的位置,那么很简单:

- 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']