
Creating EC2 Instance, Volume, and Attachments with CLI and API
š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ā¦