Reputation: 722
- hosts: ALL
gather_facts: true
remote_user:test
vars:
Env: "{{ env }}"
tasks:
- ec2_remote_facts:
region: us-east-1
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
filters:
"tag:Env": "{{ env }}"
register: instance_facts
- name: group_hosts
add_host: hostname={{ item }} groups=dev
with_items: "{{ instance_facts.instances|map(attribute="private_ip_address)|list }}"
- name: "loop over hosts for hostnames"
hostname:
name: {{ item }}
with_items: "{{ instance_facts.instances|map(attribute=' ')|list }}"
My intention in this playbook is to get the tag_Name and set the same as hostname in the instances. I was trying different things, but got stuck while using the attribute for tag in the "loop over hosts for hostames" task. How do I mention the Tag = "Name" to save it as hostname as it would be a nested attribute?
Upvotes: 3
Views: 4889
Reputation: 1
@Konstantin Suvorov thanks that is great example. i will add pause after '- add_host:' in order for second part to complete:
- name: Let's wait for SSH to come up. Usually that takes ~10 seconds
local_action: wait_for
host={{ item.private_ip }}
port=22
state=started
with_items: '{{ instance_facts.instances }}'
Upvotes: 0
Reputation: 430
I think the best way to go about this is set it in the userdata.
In Linux:
pip install awscli
ID=$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-id)
REGION=$(wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone | sed -e "s/.$//")
NAME=$(aws ec2 describe-tags --filters "Name=resource-id,Values=$ID" --region $REGION --output=text | grep Name | awk '{ print $3 }')
#set the hostname according your distro
Upvotes: 1
Reputation: 68289
You should split your playbook into two plays:
Here's an example:
- hosts: localhost
gather_facts: no
tasks:
- ec2_remote_facts:
region: us-east-1
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
filters:
"tag:Env": "{{ env }}"
register: instance_facts
- add_host:
name: "{{ item.tags.Name }}"
ansible_host: "{{ item.private_ip_address }}"
group: dev
with_items: "{{ instance_facts.instances }}"
- hosts: dev
gather_facts: true
tasks:
- hostname:
name: {{ inventory_hostname }}
Upvotes: 5