首页 > 解决方案 > Ansible:从多个堆栈中获取 instance_ids

问题描述

我正在尝试从不同的堆栈中获取 instance_ids 列表:

---
- 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 list of instance_ids"
    set_fact:
      instance_ids: "{{ dict(cf_tmp.results | map(attribute=ansible_facts['cloudformation'][stack_name]['stack_resources']['instance'])) }}"

  - debug:
      msg: "{{ instance_ids }}"

但出现以下错误:

TASK [Get list of instance_ids] *************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'stack_name' is undefined

无论如何要解决这个问题?

谢谢!

标签: loopsansible

解决方案


最终使用角色作为解决方法来完成工作。

#role
  - name: "get cloudformation facts from stacks"
    cloudformation_info:
      stack_name: "{{ stack_name }}"
      stack_resources: true
    register: cf_tmp

  - name: get instance id from stack
    set_fact:
      instance_id: "{{ cf_tmp.cloudformation[stack_name].stack_resources.Instance }}"
roles:
    - role: GetInstanceId
      vars:
        stack_name: "stacka"

    - role: GetInstanceId
      vars:
        stack_name: "stackb"

    - role: GetInstanceId
      vars:
        stack_name: "stackc"

推荐阅读