Is there a way to tag a root volume when initializing from the cloudformation template?

前端 未结 4 1585
傲寒
傲寒 2021-02-13 01:15

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

4条回答
  •  清歌不尽
    2021-02-13 01:59

    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"
    
    
    1. Write all stdout and stderr to file for debugging:

      `exec > /tmp/part-001.log 2>&1

    2. (requires permission) Get the tags from the stack:

      TAGS=$(aws cloudformation describe-stacks --stack-name ${AWS::StackName} --query 'Stacks[0].Tags' --region ${AWS::Region})

    3. Get the EC2 instance id from the metadata endpoint:

      EC2_INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)

    4. (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" " ")

    5. (requires permission) Add tags to the EBS volumes: aws ec2 create-tags --resources $EBS_IDS --tags "$TAGS" --region ${AWS::Region}

    6. Format tags for ECS tagging:

      TAGS=$(echo $TAGS | tr "Key" "key" | tr "Value" "value")

    7. (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": "*"
            }
        ]
    }
    

提交回复
热议问题