I'm trying to detach an EBS volume from an EC2 instance and attach it to a new EC2 instance which I'm starting up using a CloudFormation template(YAML). Below is the UserData section. I use a timeout command to give time for the EBS volume to properly detach. yet this script does not attach the volume to the instance properly at start up.
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>
But when I run the same script as a batch file after the instance is up and running, it works fine. What am I missing here? The UserdataExecution.log indicates,
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.