Creating EC2 Instance, Volume, and Attachments with CLI and API

Nithish Kumar
2 min readJul 1, 2023

šŸ“„In this blog, Iā€™m going to explain how we can launch EC2 Instance without going to AWS portal, and attach a newly created volume to that instance. And another service which is SNS, will create a topic and subscribe to my mail for demonstration purpose.

šŸ‘Øā€šŸ’»prerequisites:
1. AWS Configure
2. Boto3 Library

šŸ”¶Launching EC2 Instance and creating volume and attaching it to ec2 instance.

aws ec2 run-instances --image-id <image Id> --count 1 --instance-type <instance_type>

The above command will create a new instance in configured region. Now create a volume.

aws ec2 create-volume --size 5 --availability-zone ap-south-1b

Note: You have to give same availability zone to volume where your ec2 instance is launched.

Final thing is to attaching volume to ec2 instance.

aws ec2 attach-volume --volume-id <Volume Id > --instance-id <instance Id> --device /dev/sdf

Done with CLI commands. Now Letā€™s jump to Boto3 library in python.

Python code:

import boto3
ec2_res = boto3.resource(ā€œec2ā€)
ec2_client = boto3.client(ā€˜ec2ā€™)
response = ec2_res.create_instances(
ImageId = ā€œ<image_id>ā€,
InstanceType=ā€™<instance-type>ā€™,
MaxCount = 1,
MinCount = 1
)

vol = ec2_res.create_volume(
AvailabilityZone=ā€™<zone>ā€™,
Size = 5,
)

vol_client = boto3.client(ā€˜ebsā€™)
vol_client.attach_to_instance(
Device=ā€™/dev/sdkā€™,
InstanceId=ā€™<instance_id>',
)

For creating, we have to use resource module. while accessing the services we can use both resource module and client module. But we donā€™t have some required attributes in resource module. So itā€™s a good practice to use client module.

šŸ”¶Creating a SNS topic and subscribe to email for event notifications:

aws sns create-topic --name <topic-name>

Topic is a logical access point that acts as a communication channel.

aws sns subscribe --topic-arn <topic-arn>:<topic-name> --protocol <protocol> --notification-endpoint <email>

Now you will get a mail for subscription confirmation from AWS. Once your subscription confirmed, then you can publish your message.

aws sns publish --topic-arn <topic-arn>:<name> --message "<message>"

Thatā€™s all. See you in the next blog.

ā€¦Signing Offā€¦

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Nithish Kumar
Nithish Kumar

Written by Nithish Kumar

Aspiring DevOps/Cloud Engineer. #Believe in you.

No responses yet

Write a response