首页 > 解决方案 > 带有数字增量的 Ansible 双循环

问题描述

我有以下将 .p12 证书转换为 Java Keystore 的 ansible 任务。目前我正在遍历名为“java”的库存主机,并且还希望在遍历“java”主机时增加每个循环的 cert_alias 值(如 1、2 等)。我没有这个双循环的经验......有人可以建议如何实现这一点。

- name: Import a pkcs12 Keystore with a specified alias, create it if it doesn't exist
  java_cert:
     pkcs12_path: {{item}}_cert.p12
     pkcs12_alias: test
     pkcs12_password: test@123
     cert_alias: 1 >>>>>>> Need this also to be looped
     keystore_path: tlsKeyStore
     keystore_type: "JKS"
     keystore_pass: test@123
     keystore_create: yes
  loop: "{{ query('inventory_hostnames', 'java') }}"

标签: loopsansible

解决方案


问:增加每个循环的 cert_alias 值。

A:使用扩展循环变量。例如,给定库存

shell> cat hosts
[java]
srv1
srv2
srv3

剧本

- hosts: all
  gather_facts: false
  tasks:
    - debug:
        msg: "[{{ item }}] cert_alias: {{ ansible_loop.index }}"
      loop: "{{ query('inventory_hostnames', 'java') }}"
      loop_control:
        extended: true
      run_once: true

  msg: '[srv1] cert_alias: 1'
  msg: '[srv2] cert_alias: 2'
  msg: '[srv3] cert_alias: 3'

推荐阅读