You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible:如何在with_items任务中调用另一with_items任务的注册输出

解决Ansible中客户端与SSL ARN关联提取的问题

核心问题分析

原Playbook里,sslearn.results是一个列表,每个元素包含对应客户端的执行结果(带item字段标记客户端名),但后续任务没建立客户端名与ARN的映射关系,导致没法精准提取对应客户端的ARN。

解决方案步骤

1. 将注册结果转换为客户端-ARN映射字典

在获取ARN的任务后,新增set_fact任务,把循环结果整理成以客户端名为键、ARN为值的字典:

- name: Find ARN
  shell: aws acm list-certificates --output text --certificate-statuses ISSUED | grep {{ apache[item].domain }} | awk '{print $2}'
  args:
    executable: /bin/bash
  with_items:
    - "clientA"
    - "clientB"
    - "clientC"
  register: sslarn

# 新增:构建客户端与ARN的映射字典
- name: Build client-ARN mapping dictionary
  set_fact:
    client_arn_map: "{{ client_arn_map | default({}) | combine({ item.item: item.stdout.strip() }) }}"
  with_items: "{{ sslarn.results }}"

2. 验证映射字典(可选)

修改debug任务,直接查看映射后的字典,确认每个客户端对应的ARN:

- debug:
    var: client_arn_map

3. 在模板任务中传递对应客户端的ARN

修改模板任务,通过映射字典获取当前客户端的ARN,并传递给模板:

- name: Remake the dictionary assemble files
  template:
    src: /file/path/to/templates/update-dictionary-template.j2
    dest: /file/path/to/dictionary/files/{{ item }}.yml
    mode: 0644
  with_items:
    - "clientA"
    - "clientB"
    - "clientC"
  vars:
    # 通过客户端名从映射字典中获取对应ARN
    client_ssl_arn: "{{ client_arn_map[item] }}"

4. 模板文件中使用ARN

在update-dictionary-template.j2里,直接用传递的变量{{ client_ssl_arn }}即可:

# 示例模板内容,根据实际字典结构调整
{{ item }}:
  ssl_arn: {{ client_ssl_arn }}
  # 其他自定义字段...

优化建议:用Ansible官方ACM模块替代Shell命令

避免依赖grep/awk和AWS CLI输出格式,改用aws_acm_info模块更稳定可靠:

- name: Get ACM certificate ARN via official module
  aws_acm_info:
    certificate_statuses: issued
    domain_name: "{{ apache[item].domain }}"
  with_items:
    - "clientA"
    - "clientB"
    - "clientC"
  register: sslarn

- name: Build client-ARN mapping dictionary
  set_fact:
    client_arn_map: "{{ client_arn_map | default({}) | combine({ item.item: item.certificates[0].certificate_arn }) }}"
  with_items: "{{ sslarn.results }}"

内容的提问来源于stack exchange,提问作者Daynesuke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 05:32:50