How Do You Use Boto3 to Create EC-2 Instances?

Problem scenario
You want to create EC-2 instances using an SDK (a program that automatically generates AWS resources). How do you do this?

Solution
Prerequisites

You have Boto3 installed. If you need assistance, see this posting if you have CentOS/RHEL/Fedora or this posting for Debian/Ubuntu.

Procedures
Run this program to create a RHEL server (but you can replace the "ami-0a54aef4ef3b5f881" with the image ID of your choice):

# Replace AKIAabcdefghijk with your AWS access key ID
# Replace 1a2b3c4d5e6f7g8h9/i0j0k9l8m7n6o5p4q3r2s1tuvwxyz with your AWS Secret Access key
# Replace us-west-1 with the region of your choice
# Replace ami-0a54aef4ef3b5f881 with the image ID of your choice.
# Replace subnet-abcd1234 with the subnet ID of your choice
# Replace foobarkeyname with the AWS key pair name of your choice
# You can set the MaxCount to the number of EC-2 instances you want to create.  This example will create 2.

import boto3
ec2 = boto3.resource('ec2', region_name='us-west-1', aws_access_key_id='AKIAabcdefghijk', aws_secret_access_key='1a2b3c4d5e6f7g8h9/i0j0k9l8m7n6o5p4q3r2s1tuvwxyz')

# create a new EC2 instance
instances = ec2.create_instances(
     ImageId='ami-0a54aef4ef3b5f881',
     MinCount=1,
     MaxCount=2,
     SubnetId='subnet-abcd1234',
     InstanceType='t2.micro',
     KeyName='foobarkeyname'
 )

Leave a comment

Your email address will not be published. Required fields are marked *