How to create an EC2 instance using Python?

0 votes

Guys, HELP!

I need a help to write script on python, what:

  1. Create EC2 instance in existing VPC.

  2. Create security group which allows only 22 and 80 inbound ports and attach it to the instance.

  3. Create new EBS volume with "magnetic" type, 1GB size and attach it to the instance.

  4. Connect to the instance via ssh, format and mount additional volume.

Jun 24 in AWS by JunDevOps

recategorized Jun 24 by Kalgi 259 views

1 answer to this question.

0 votes

Hey JunDevOps, Have a look these scripts:

1. To create an ec2 instance using python, you need to have the programmatic access. Use the following script to create an ec2 instance:

reservations = conn.get_all_instances(instance_ids=[sys.argv[1]])
instances = [i for r in reservations for i in r.instances]
for i in instances:
    #provide the key pair to create the instance
    key_name = i.key_name 
    # Provide security group id the instance should have
    security_group = i.groups[0].id
    # provide the instance type
    instance_type = i.instance_type
    print "Now Spinning New Instance"
    # provide the subnet id
    subnet_name = i.subnet_id
    # Finally create the instance 
    reserve = conn.run_instances(image_id=ami_id,key_name=key_name,instance_type=instance_type,security_group_ids=[security_group],subnet_id=subnet_name)

2. Script to create a security group with your specifications:

import boto3
from botocore.exceptions import ClientError

ec2 = boto3.client('ec2')
# Get all VPC's
response = ec2.describe_vpcs()
vpc_id = response.get('Vpcs', [{}])[0].get('VpcId', '')
# Get VPC Ids
try:
# Create a security group and store it in response
    response = ec2.create_security_group(GroupName='SECURITY_GROUP_NAME',
                                         Description='DESCRIPTION',
                                         VpcId=vpc_id)
# get security id from response
    security_group_id = response['GroupId']
    print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id))
    # configure your security rules
    data = ec2.authorize_security_group_ingress(
        GroupId=security_group_id,
        IpPermissions=[
            {'IpProtocol': 'tcp',
             'FromPort': 80, #allows incoming traffic port 80
             'ToPort': 80,   #Allows port forwarding to port 80
             'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, #Ip ranges to be functional
            {'IpProtocol': 'tcp', #protocol to be used
             'FromPort': 22, # Allow incoming traffic from port 22
             'ToPort': 22,  # Allow traffic to be reached at port 22
             'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}
        ])
    print('Ingress Successfully Set %s' % data) # Print the configuration
except ClientError as e:
    print(e)

3. Create EBS Volume and attach it to the instance

#### Create a volume ####
# create_volume(size, zone, snapshot=None, volume_type=None, iops=None)
# Very straight forward way to create volume. First argument - size, 2nd - region, 3rd - type
vol = conn.create_volume(1, "us-west-1c", "magnetic")
print 'Volume Id: ', vol.id #Prints volume id once its created

# attach volume and print the volume details. You pass volume id, instance id to which you wish to attach #the volume and 
result = conn.attach_volume (vol.id, instance.id, "/dev/sdf")
print 'Attach Volume Result: ', result

4. Connect via ssh

import boto3
import botocore
import paramiko
# Get the key pair, save it in key
key = paramiko.RSAKey.from_private_key_file(path/to/mykey.pem)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect/ssh to an instance
try:
    # Here 'ubuntu' is user name and 'instance_ip' is public IP of EC2
    client.connect(hostname=instance_ip, username="ubuntu", pkey=key)

    # Execute a command(cmd) after connecting/ssh to an instance
    stdin, stdout, stderr = client.exec_command(cmd)
    print stdout.read()

    # close the client connection once the job is done
    client.close()
    break

except Exception, e:
    print e
answered Jun 24 by Aysha

edited Jun 25
Oh!!! Thank you man! Its perfect! Can I ask u more about AWS and about writing script in there?
Glad to help :)

Yes, you can ask anything related to any technology or even any career-related doubt. You can create a new thread by asking a new question if it's not related to the exact same topic.
Thank you! =)
Could you tell us in detail how the whole process of scripting with Amazon web service goes?
That's right from scratch, that was the task to write the above script, where to apply it and how? How does it all begin? Where is this realized in the Amazon itself? Or separately on a virtual machine for example?

I apologize in advance for such primitive questions, probably I know some of the answers, but to convince and understand, I would like to know it from you!)
Thank you very much!

Have a look at this tutorial video, you'll probably get a good understanding: https://www.youtube.com/watch?v=0ftT1y_ckd0

Thank you! Its really good video for start! =)
Can you give some comments in code what you give to me there? I am so sorry, but never work with Python, only C or C++... I can read code what u sent there, but have some trouble with some arguments.

You give me very useful recommendations and guidance on this topic ... This is very important for me ... Can I somehow thank?

Hey, I've added comments. Hopefully, you're able to understand the scripts. You'll probably need to learn python to understand the scripts completely. 

Have a look at this Docs, they might be helpful :

https://boto3.amazonaws.com/v1/documentation/api/latest/guide/ec2-example-managing-instances.html

Hahaha! You don't have to thank, I am glad I could help. If you have any further doubts, put it up on Edureka Community.
This is unbelievable!! Thank you so much!

I apologize, but I am embarrassed for myself from your such quick and high-quality answers ... Thank you again!

I would also like to clarify the function arguments, are they in templates in these scripts, or is it a ready-made solution and if I run it on one of the virtual machines on Amazon, then all the actions that the script provides will be executed?
I am so sorry, but al scripts don t work... I am install all modules, create script in ubuntu, start and they didn t work... =(
What exactly are you trying to do? Can you give background details of what exactly you're trying to do?

Related Questions In AWS

+1 vote
1 answer
0 votes
1 answer

How to Pass the VPC ID while creating the Ec2 instance in AWS using Python Boto3

import boto3 ec2 = boto3.resource('ec2') instance = ec2.create_instances( ...READ MORE

answered Jan 29 in AWS by Priyaj
• 56,160 points
205 views
0 votes
1 answer
0 votes
1 answer