DEV Community

Cover image for "Unlocking the Power of Infrastructure as Code: Attaching an Amazon EBS Volume to an EC2 Instance Using Terraform"
Puneet Jena
Puneet Jena

Posted on

"Unlocking the Power of Infrastructure as Code: Attaching an Amazon EBS Volume to an EC2 Instance Using Terraform"

  1. Defining the EBS Volume, EC2 Instance, Creating SSH Keys, and Configuring Security Group:

Create a new Terraform configuration file (e.g., main.tf).
Define the AWS provider block and specify the desired region.

Declare an aws_instance resource, specifying the AMI, instance type, and other settings.

Generate SSH key pair using the ssh-keygen command:



Declare an aws_security_group resource to define the inbound and outbound rules for your EC2 instance:



Declare an aws_ebs_volume resource, setting the availability zone and size.

Automating Volume Attachment:

Add an aws_volume_attachment resource to the Terraform configuration.
1.
 Specify the device name, EC2 instance ID, and volume ID.

Run the following command to initialize the Terraform configuration:
1.terraform init

After successful initialization, run the following command to perform a dry run and see the execution plan:

2.terraform plan

Then excute the program using terraform apply:

3.terraform apply


Now time to connect the instance and see wheather the volume is being attached or not:

  1. from this image we can clearly see that volume xvdf is being attached:

Top comments (0)