Ansible 中出现双重循环,如何处理?

Ansible 中出现双重循环,如何处理?

我有这样的结构:

- name: Run validation query on db localy
  shell: >
    docker exec postgres.1.$(docker service ps -f "name=postgres.1" postgres -q) bash -c 'psql -v --username "{{ pg_connection_speruser }}" --dbname "{{ pg_db }}" -c "select 1"'
  register: validation_query
  delegate_to: "{{ item }}"
  with_items: "{{ groups.postgres_server }}"
  until: validation_query.stderr == ''
  retries: 6
  delay: 10
  ignore_errors: false
  changed_when: false

我需要做的是:

- name: Run validation query on db localy
  shell: >
    docker exec postgres.{{ item }}.$(docker service ps -f "name=postgres.{{ item }}" postgres -q) bash -c 'psql -v --username "{{ pg_connection_speruser }}" --dbname "{{ pg_db }}" -c "select 1"'
  register: validation_query
  with_sequence: start=1 end="{{ pg_docker_service_replicas }}"
  delegate_to: "{{ item }}"
  with_items: "{{ groups.postgres_server }}"
  until: validation_query.stderr == ''
  retries: 6
  delay: 10
  ignore_errors: false
  changed_when: false

但是当然,双循环 with_sequence 和 with_items 存在问题。

可以用其他方法吗?谢谢

答案1

您可以使用 和 来做到这with_nested一点lookup

---
- hosts: localhost
  gather_facts: no
  vars:
    max_num: 3
    delegates:
      - host1
      - host2
  tasks:
    - debug:
        msg: "delegate={{ item[0] }} seq={{ item [1] }}"
      with_nested:
        - "{{ delegates }}"
        - "{{ lookup('sequence','start=1 end='+max_num|string,wantlist=True) }}"

这将生成嵌套循环:外层循环 - 遍历delegates列表中的每个项目(可通过 访问item[0]),内层循环 - 遍历序列1-max_num

相关内容