Unable to attach my existing EBS volume (data drive) to a newly launched EC2 instance (RHEL 8) through user data commands. I am able to attach the EBS volume manually by connecting the server through putty and using the same set of commands, but not through user data input.
1) Launched a free tier RHEL instance and attached an EBS volume - X (data drive) to it through AWS Web console. The volume X is expected to store few application data.
2) Connected EC2 instance through putty and checked Volume X was visible to the OS. >
#fdisk -l
Disk /dev/xvdf: 11 GiB, 11811160064 bytes, 23068672 sectors
3) Formatted/partitioned the drive as below >
#/sbin/mkfs -t ext3 /dev/xvdf
4) Created a directory to mount the volume.
#mkdir /mnt/data
5) Updated /etc/fstab to make sure that the mount is available even after server reboot. Below is the fstab entry I did.
#vi /etc/fstab
/dev/xvdf /mnt/data ext4 defaults,nofail 0 0
6) Reboot.
7) #df -h >
Filesystem Size Used Avail Use% Mounted on devtmpfs 391M 0 391M 0% /dev tmpfs 410M 0 410M 0% /dev/shm tmpfs 410M 11M 400M 3% /run tmpfs 410M 0 410M 0% /sys/fs/cgroup /dev/xvda2 10G 1.1G 9.0G 11% / /dev/xvdf 11G 28M 11G 1% /IIG --> New mount point listed. tmpfs 82M 0 82M 0% /run/user/1000
8) Installed aws cli and configured it as below
$ sudo yum install -y python3
install aws cli
$ pip3 install awscli --upgrade --user
$ aws configure
AWS Access Key ID : abc123
AWS Secret Access Key [None]: def456
Default region name [None]: us-west-2
Default output format [None]:
9) I created an AMI using this EC2 with only the root device.
10) Terminated the EC2.
11) Launched a new EC2 from the AMI without additional volume and provided below inputs in user data section
#!/bin/bash
instanceid=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
aws ec2 attach-volume --volume-id vol-abcd1234 --instance-id
echo instanceid
--device /dev/sdfsleep 20 mount -a
12) EC2 launches fine but Volume X is not getting attached to it.
User data input:
#!/bin/bash
instanceid=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
aws ec2 attach-volume --volume-id vol-abcd1234 --instance-id `echo
$instanceid` --device /dev/sdf
sleep 20
mount -a
When I run the user inputs commands manually by connecting the EC2 through Putty, it is working perfectly and volume X is getting attached to the instance without any error. The volume X gets listed under df -h as well.
The expected result was, Volume X to get attached to the new EC2 instance automatically when launched through AMI. This is not happening.