1. Attach an EBS to EC2:
There are many ways to attach an EBS to EC2. You can manually attach an EBS (Block device) to EC2 through AWS Console UI. You can also do it through AWS CLI from the terminal.
Here, I am taking AWS Cloud Formation example to create and attach an EBS to EC2.
We have attached an EBS(Block device) on EC2 using cloud formation. Please refer to the cloud formation code below. We have a mapping section. In the Resource section, we simply Create a BlockDeviceMappings in the LaunchConfig resource. type.
"Mappings":{
"InstanceVolumeSize" : {
"Production" : {
"VolumeSize" : "100" #This is the size of EBS in GB
}
}
"Resources": {
"testLaunchConfig": {
"Type": "AWS::AutoScaling::LaunchConfiguration",
"Properties": {
"BlockDeviceMappings" : [
{
"DeviceName" : "/dev/sda1",
"Ebs" : {
"VolumeSize" : {
"Fn::FindInMap" : [ "InstanceVolumeSize", "Production", "VolumeSize" ]
},
"VolumeType" : "gp2",
"DeleteOnTermination": "true"
}
}
]
}
}
2. Resize the volume size so that it can extend to the new allocated size.
On the launch/At the start of the machine, you can pass the following scripts as user-data or you may run this script on boot. Please note that you keep the device name same “/dev/sda1” in the below script as you mention it in the cloud formation script above. Let’s say that the below script is “resize.sh”.
#!/bin/bash
sudo apt install cloud-guest-utils
sudo growpart /dev/xvda 1
sudo resize2fs /dev/xvda1