本文介绍了如何通过CloudFormation设置EC2实例的根卷的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用CloudFormation创建EC2实例,但是根卷的名称(标记)为空。如何使用CloudFormation设置它?

Create EC2 instance using CloudFormation, but the name (tags) of root volume is empty. How to set it using CloudFormation?

# ec2-instance.yml (CloudFormation template)
MyInstance:
  Type: "AWS::EC2::Instance"
  Properties:
    ImageId: "ami-da9e2cbc"
    InstanceType: "t2.nano"
    KeyName: !Ref "KeyPair"
    Tags: # This is for EC2 instance (not root volume)
      - Key: "Name"
        Value: "my-instance"

我找到了 Volumes和 BlockDeviceMappings属性,但找不到。

I find "Volumes" and "BlockDeviceMappings" properties but it could not.

推荐答案

CloudFormation当前似乎不支持此功能。但是,使用实例,您可以执行以下操作以标记根卷:

CloudFormation does not appear to support this currently. However using an instance user data script, you can do this to tag the root volume:

apt-get -y install unzip
unzip awscli-bundle.zip
./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws    
rm -rf  awscli-bundle awscli-bundle.zip
EC2_INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
EC2_REGION=${EC2_AVAIL_ZONE:0:${#EC2_AVAIL_ZONE} - 1}
ROOT_DISK_ID=$(aws ec2 describe-volumes --filters Name=attachment.instance-id,Values={EC2_INSTANCE_ID} Name=attachment.device,Values=/dev/sda1 --query 'Volumes[*].[VolumeId]' --region=${EC2_REGION} --out \"text\" | cut -f 1)
aws ec2 create-tags --resources $ROOT_DISK_ID --tags Key=Name,Value=\"Root Volume my-instance\" --region ${EC2_REGION}

此脚本会使用 Name =根卷我的实例

请注意,对于我的Ubuntu AMI,我必须首先安装AWS工具。 Amazon Linux AMI已安装了那些工具。

Note that for my Ubuntu AMI I have to install the AWS tools first. The Amazon Linux AMI has those tools installed.

对于CloudFormation,您将使用:

For CloudFormation, you would use:

# ec2-instance.yml (CloudFormation template)
MyInstance:
  Type: "AWS::EC2::Instance"
  Properties:
    ImageId: "ami-da9e2cbc"
    InstanceType: "t2.nano"
    KeyName: !Ref "KeyPair"
    UserData:
      "Fn::Base64": !Sub |
       #!/bin/bash -x
       apt-get -y install unzip
       unzip awscli-bundle.zip
       ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws    
       rm -rf  awscli-bundle awscli-bundle.zip
       EC2_INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
       EC2_REGION=${EC2_AVAIL_ZONE:0:${#EC2_AVAIL_ZONE} - 1}
       ROOT_DISK_ID=$(aws ec2 describe-volumes --filters Name=attachment.instance-id,Values={EC2_INSTANCE_ID} Name=attachment.device,Values=/dev/sda1 --query 'Volumes[*].[VolumeId]' --region=${EC2_REGION} --out \"text\" | cut -f 1)
       aws ec2 create-tags --resources $ROOT_DISK_ID --tags Key=Name,Value=\"Root Volume my-instance\" --region ${EC2_REGION}

这篇关于如何通过CloudFormation设置EC2实例的根卷的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 07:25