如何使用 ansible 过滤掉具有特定标签的特定 AWS rds 实例

问题描述 投票:0回答:1

我正在尝试列出所有使用 ansible 剧本定义了我的 cusotm 标签的 AWS RDS 实例,我正在使用 rds_instance_info 来获取所有 rds 实例的数据。

    - name: List RDS instances
      hosts: localhost
      tasks:
        - name: Get RDS instance info
          amazon.aws.rds_instance_info:
            region: xx-xxxx-x
            aws_access_key: xxxxxxxxxxxxxxxx
            aws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
          register: rds_info
    
        - set_fact:
            var: "{{ rds_info.instances | selectattr('tags', 'defined') | selectattr('tags.stack', 'equalto', 'custom-tag-value') | default([]) | list }}"
          loop: "{{ rds_info.instances }}"

        - debug:
            msg: "{{ item.db_instance_identifier }}"
          loop: "{{ var }}"

我得到的错误是,

{"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'stack'. 'dict object' has no attribute 'stack'

并非所有实例都定义了标签,并且定义了标签的实例并不总是具有标签“堆栈”。

amazon-web-services automation ansible amazon-rds
1个回答
0
投票

Q:“列出所有定义了我的自定义标签的实例。”

A:使用 json_query。例如,给定测试数据

    rds_info:
      instances:
        - name: A
          tags: {stack: custom-tag-name, tag: tag_A}
        - name: B
          tags: {tag: tag_B}
        - name: C
        - name: D
          tags: {stack: X, tag: tag_D}

声明“定义了我的自定义标签的实例”列表

    result: "{{ rds_info.instances|json_query(result_query) }}"
    result_query: '[?tags.stack == `custom-tag-name`]'

给予

  result:
  - name: A
    tags:
      stack: custom-tag-name
      tag: tag_A

完整的测试剧本示例

- hosts: localhost

  vars:

    # Not all instances have tags defined and the ones having tags defined
    # don't always have the tag 'stack'

    rds_info:
      instances:
        - name: A
          tags: {stack: custom-tag-name, tag: tag_A}
        - name: B
          tags: {tag: tag_B}
        - name: C
        - name: D
          tags: {stack: X, tag: tag_D}


    result: "{{ rds_info.instances|json_query(result_query) }}"
    result_query: '[?tags.stack == `custom-tag-name`]'

#    result: "{{ rds_info.instances|
#                selectattr('tags', 'defined')|
#                selectattr('tags.stack', 'equalto', 'custom-tag-name') }}"
#
#    result: 'VARIABLE IS NOT DEFINED!: ''dict object'' has no attribute ''stack''

  tasks:

    - debug:
        var: result
© www.soinside.com 2019 - 2024. All rights reserved.