I was writing Ansible playbook to display the auto scaling group of AWS based on tags and below is my playbook.
- name: Find the green asg with matching tags
ec2_asg_info:
tags:
service_name: cps_wallet
Environment: "{{ name_env }}"
service_state: green
register: asgs_payment
- name: Show the ASG Payment name
debug:
msg: "{{ asgs_payment.results[0].auto_scaling_group_name}}"
- set_fact:
asg_payment_name: "{{ asgs_payment.results[0].auto_scaling_group_name}}"
I was running it on Jenkins and I was getting error
fatal: [127.0.18.34]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: list object has no element 0nnThe error appears to be in '/opt/software/jenkins/workspace/payment-react-ui/srv/payment-ui-110/payment-ui/roles/inspect/tasks/cps_green_deploy.yml': line 9, column 3, but maynbe elsewhere in the file depending on the exact syntax problem.nnThe offending line appears to be:nnn- name: Show the ASG Payment namen ^ heren"}
I thought the result doesn’t have any asg name so i updated the above code as
- name: Find the green asg with matching tags
ec2_asg_info:
tags:
service_name: cps_wallet
Environment: "{{ name_env }}"
service_state: green
register: asgs_payment
- name: Show the ASG Payment name
debug:
msg: "{{ asgs_payment}}"
- set_fact:
asg_payment_name: "{{ asgs_payment}}"
It didn’t give me any error, but the result was empty.
"msg": { "changed": false, "failed": false, "results": [] }
I do have tags added in my ASG as you can see below. And there is no other asg with same tags
Tags image
The same playbook works like a charm for my other applications
2
Answers
name: Get information about Auto Scaling group
ec2_asg_facts:
region: "{{ region }}"
register: asg_facts
name: Display Auto Scaling group name
debug:
msg: "The Auto Scaling group name is {{ asg_facts.autoscaling_groups[0].name }}"
this works for me
EDIT:
here is a template of playbook
the ec2_instance_info module is used to retrieve information about the instance with the tag Name set to "my-instance" in the us-east-1 region. The ec2_asg_info module is then used to retrieve information about the Auto Scaling group that the instance belongs to, using the asg_name attribute of the instance. Finally, the debug module is used to display the name of the Auto Scaling group.
You can modify this