Ansible如何从多个CloudFormation栈中获取instance_ids列表
问题原因
- 你在
Get list of instance_ids任务中直接使用了未定义的stack_name变量,该变量仅在第一个任务的循环上下文里临时存在,第二个任务执行时已经失效 - 你对
cf_tmp.results的结构处理逻辑有误,map(attribute=)的参数需要是固定的属性路径,无法直接代入动态变量遍历所有栈的资源
解决方法
两种常用实现方案,按需选择:
方案1:循环遍历栈名生成结果(最易理解维护)
如果你需要所有实例ID组成的扁平列表
修改第二个任务为如下写法:
- name: "Get list of instance_ids" set_fact: instance_ids: "{{ instance_ids | default([]) + [ansible_facts.cloudformation[item].stack_resources.instance] }}" loop: "{{ stack_names }}"
如果你需要栈名和对应实例ID的映射字典
修改第二个任务为如下写法:
- name: "Get stack to instance_id mapping" set_fact: instance_ids: "{{ instance_ids | default({}) | combine({item: ansible_facts.cloudformation[item].stack_resources.instance}) }}" loop: "{{ stack_names }}"
方案2:直接处理第一次循环的注册结果(无需二次遍历栈名)
利用第一次任务注册的cf_tmp.results直接提取数据,写法如下:
- name: "Get list of instance_ids" set_fact: instance_ids: "{{ cf_tmp.results | json_query('[*].ansible_facts.cloudformation.*.stack_resources.instance') | flatten }}"
完整可运行参考playbook
--- - hosts: localhost vars: stack_names: - 'stacka' - 'stackb' - 'stackc' tasks: - name: "get cloudformation facts from stacks" cloudformation_facts: stack_name: "{{ item }}" stack_resources: true with_items: "{{ stack_names }}" register: cf_tmp - name: "Get flat list of instance_ids" set_fact: instance_ids: "{{ instance_ids | default([]) + [ansible_facts.cloudformation[item].stack_resources.instance] }}" loop: "{{ stack_names }}" - debug: msg: "{{ instance_ids }}"
内容的提问来源于stack exchange,提问作者Mary W
相关产品推荐
相关产品推荐

