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, 2019 in AWS by JunDevOps

recategorized Jun 24, 2019 by Kalgi 9,285 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, 2019 by Aysha

edited Jun 25, 2019
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?
Hi,

Do you also have any python script to create the containers in the instance once it is created. Thanks
For that you can use ECS service. It is available in AWS.

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, 2019 in AWS by Priyaj
• 58,020 points
3,548 views
0 votes
1 answer
0 votes
1 answer

How do I create an alarm for my load balancer using the Amazon EC2 console?

Follow these steps: Open the Amazon EC2 console On ...READ MORE

answered May 17, 2019 in AWS by Rhea
1,645 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP