我正在尝试从 EC2 实例分离 EBS 卷并将其附加到我正在使用 CloudFormation 模板 (YAML) 启动的新 EC2 实例。下面是用户数据部分。我使用超时命令为 EBS 卷提供时间以正确分离。 但是这个脚本在启动时没有正确地将卷附加到实例。
UserData: !Base64
<script>
aws ec2 detach-volume --instance-id i-05e13cbyrr78f75f7 --volume-id vol-0e5a92637c3dec929x --region us-east-1
timeout /t 100
for /F %%L in ('powershell Invoke-RestMethod -Uri 'http://169.254.169.254/latest/meta-data/instance-id'') do (set "ID=%%L")
aws ec2 attach-volume --volume-id vol-0e5a92637c3dec929x --instance-id %ID% --device xvdf --region us-east-1
</script>
但是当我在实例启动并运行后运行与批处理文件相同的脚本时,它工作正常。 我在这里错过了什么? UserdataExecution.log 表明,
2023/04/28 07:05:43Z: <script> tag was provided.. running script content
2023/04/28 07:06:14Z: Message: The errors from user data script: usage:
Note: AWS CLI version 2, the latest major version of the AWS CLI, is now stable and recommended for general use. For more information, see the AWS CLI version 2 installation instructions at: https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html
usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:
aws help
aws <command> help
aws <command> <subcommand> help
aws: error: argument --instance-id: expected one argument
2023/04/28 07:06:14Z: Message: The output from user data script:
C:\Windows\system32>aws ec2 detach-volume --instance-id i-05e13cbyrr78f75f7 --volume-id vol-0e5a92637c3dec929x --region us-east-1 timeout /t 100 for /F %L in ('powershell Invoke-RestMethod -Uri 'http://169.254.169.254/latest/meta-data/instance-id'') do (set "ID=%L") aws ec2 attach-volume --volume-id vol-0e5a92637c3dec929x --instance-id --device xvdf --region us-east-1
2023/04/28 07:06:14Z: User data script completed.
这里有一些通过 YAML 传递用户数据的例子。请注意,他们使用
!Sub |
可能会为您解决问题:
来自AWS CloudFormation UserData Example · GitHub:
UserData:
Fn::Base64:
!Sub |
#!/bin/bash -xe
yum update -y aws-cfn-bootstrap
/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource LaunchConfig --configsets wordpress_install --region ${AWS::Region}
/opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource WebServerGroup --region ${AWS::Region}
来自amazon web服务-试图理解UserData脚本的Cloudformation语法-服务器故障:
UserData:
Fn::Base64: !Sub |
#!/bin/bash -xe
# Pre-Bootstrap Configuration
yum update -y
yum install -y aws-cfn-bootstrap git docker
usermod -a -G docker ec2-user
systemctl enable docker
systemctl start docker
curl -L https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m) -o /usr/bin/docker-compose
chmod +x /usr/bin/docker-compose