Using ansible inside EC2 instance to gather tags

21 views
Skip to first unread message

Pshem Kowalczyk

unread,
Nov 15, 2017, 1:29:43 PM11/15/17
to Ansible Project
Hi,

We're starting to move our setup to AWS. In order to get an EC2 instance provisioned we use ansible in 'pull' mode.  That works fine. The one thing that seems to be a problem is getting the tags assigned to the instance. 

If the playbook is ran from the 'outside' the inventory script supplies all the 'ec2_tag_' variables. But from the 'inside' of the instance, if I wanted to do that I'd have to supply the key/secret pair into the instance. 

aws cli is able to get details like that if the correct IAMProfile is attached to an instance without supplying any additional credentials. Is there a way to make ansible do the same?

kind regards
Pshem

Pshem Kowalczyk

unread,
Nov 15, 2017, 2:45:13 PM11/15/17
to Ansible Project
So far I came up with the following, but it does feel a bit kludgy: 


- name: check if running inside AWS
  uri:
    timeout: 2
  register: aws_uri_check
  failed_when: False

- name: store result
  set_fact:
    inside_aws: "{{ aws_uri_check.status == 200 }}"

- name: install aws cli
  command: pip install awscli
  when: inside_aws

- name: get the list of tags
  shell: REGION=$(curl -q http://169.254.169.254/latest/meta-data/placement/availability-zone) INSTANCE=$(curl -q http://169.254.169.254/latest/meta-data/instance-id); aws ec2 describe-tags --region ${REGION%?} --filters "Name=resource-id,Values=$INSTANCE"
  register: tag_list
  when: inside_aws

- name: create facts out of the tags
  set_fact:
    "{{'ec2_tag_' + tag.Key.replace(':','_').replace('-','_') }}": "{{ tag.Value }}"
  with_items: "{{ (tag_list.stdout | from_json)['Tags'] }}"
  when: inside_aws
  loop_control:
    loop_var: tag
    label: "{{ tag.Key }}"

- name: remove awscli tools
  command: pip uninstall -y awscli
  when: inside_aws
 
kind regards
Pshem
Reply all
Reply to author
Forward
0 new messages