cloudformation-coverage-roadmap icon indicating copy to clipboard operation
cloudformation-coverage-roadmap copied to clipboard

Enable Instance Tags on Instance Metadata Service

Open evanottinger opened this issue 2 years ago • 1 comments

Name of the resource

AWS::EC2::Instance

Description

According to this AWS news article, it is now possible to make Instance Tags available to the EC2 Instance Metadata service. This feature is not enabled by default, but there is an option to enable it when creating a new EC2 Instance in the console.

The AWS::EC2::Instance specification should allow for an attribute to enable Instance Tags from the CloudFormation stack template.

evanottinger avatar Jul 20 '22 14:07 evanottinger

Current workaround, in the EC2's user-data:

Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0

--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"

#cloud-config
cloud_final_modules:
- [scripts-user, always]

--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"

#!/bin/bash

# Redirect logs
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1

apt update

# This is the goal command to use whenever CloudFormation Supports enabling tags
# from instance meta-data out of the box:
# More info: https://github.com/aws-cloudformation/cloudformation-coverage-roadmap/issues/1248
#
# export TARGET_TAG=$(curl http://169.254.169.254/latest/meta-data/tags/instance/target_tag)

# The following is our workaround:
apt install jq -y 
export INSTANCE_ID=$(curl http://169.254.169.254/latest/meta-data/instance-id/)
export TARGET_TAG=$(aws ec2 describe-tags --region us-east-2 --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=target_tag" | jq .Tags[0].Value | cut -d "\"" -f 2)
# end workaround

--//--

evanottinger avatar Jul 23 '22 22:07 evanottinger