I am trying to list all the AWS RDS instances which have my cusotm tag defined using ansible playbooks, I am using the rds_instance_info to get the data of all the rds instances.
- 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 }}"
The error i get is,
{"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'
Not all instances have tags defined and the ones having tags defined don't always have the tag "stack".
Q: "List all instances which have my custom tag defined."
A: Use json_query. For example, given the data for testing
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}
Declare the list of "instances which have my custom tag defined"
result: "{{ rds_info.instances|json_query(result_query) }}"
result_query: '[?tags.stack == `custom-tag-name`]'
gives
result:
- name: A
tags:
stack: custom-tag-name
tag: tag_A
Example of a complete playbook for testing
- 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