I am creating an instance through the cloud formation script.
The only way I found to attach an OS partition was through \"BlockDeviceMappings\" property. (I\'ve tried t
If your CloudFormation stack is tagged and you want your EC2 attached volumes to copy over the tags from the stack you can use the below UserData value.
Fn::Base64: !Sub |
#!/bin/bash -xe
exec > /tmp/part-001.log 2>&1
# --==Tagging Attached Volumes==--
TAGS=$(aws cloudformation describe-stacks --stack-name ${AWS::StackName} --query 'Stacks[0].Tags' --region ${AWS::Region})
EC2_INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
EBS_IDS=$(aws ec2 describe-volumes --filters Name=attachment.instance-id,Values="$EC2_INSTANCE_ID" --region ${AWS::Region} --query 'Volumes[*].[VolumeId]' --out text | tr "\n" " ")
aws ec2 create-tags --resources $EBS_IDS --tags "$TAGS" --region ${AWS::Region}
TAGS=$(echo $TAGS | tr "Key" "key" | tr "Value" "value")
aws ecs tag-resource --resource-arn arn:aws:ecs:${AWS::Region}:${AWS::AccountId}:cluster/${EcsClusterName} --tags "$TAGS"
Write all stdout and stderr to file for debugging:
`exec > /tmp/part-001.log 2>&1
(requires permission) Get the tags from the stack:
TAGS=$(aws cloudformation describe-stacks --stack-name ${AWS::StackName} --query 'Stacks[0].Tags' --region ${AWS::Region})
Get the EC2 instance id from the metadata endpoint:
EC2_INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
(requires permission) Get the EBS IDS:
EBS_IDS=$(aws ec2 describe-volumes --filters Name=attachment.instance-id,Values="$EC2_INSTANCE_ID" --region ${AWS::Region} --query 'Volumes[*].[VolumeId]' --out text | tr "\n" " ")
(requires permission) Add tags to the EBS volumes:
aws ec2 create-tags --resources $EBS_IDS --tags "$TAGS" --region ${AWS::Region}
Format tags for ECS tagging:
TAGS=$(echo $TAGS | tr "Key" "key" | tr "Value" "value")
(requires permission) Tag the ECS cluster:
aws ecs tag-resource --resource-arn arn:aws:ecs:${AWS::Region}:${AWS::AccountId}:cluster/${EcsClusterName} --tags "$TAGS"
The policy should look like this:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"ec2:DeleteTags",
"ec2:CreateTags",
"ecs:TagResource",
"cloudformation:DescribeStacks"
],
"Resource": "*"
}
]
}