使用 CloudFormation 创建 EC2 实例,但根卷的名称(标签)为空。如何使用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”属性,但找不到。
最佳答案
CloudFormation 目前似乎不支持此功能。但是使用实例user data script ,您可以执行以下操作来标记根卷:
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=Root Volume my-instance
标记/dev/sda1 EBS 卷
请注意,对于我的 Ubuntu AMI,我必须首先安装 AWS 工具。 Amazon Linux AMI 已安装这些工具。
对于 CloudFormation,您可以使用:
# 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}
关于amazon-web-services - 如何通过CloudFormation设置EC2实例根卷的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47499722/