Create a Ec2 Instance From Python Script

Rahul juneja
1 min readJun 24, 2020

This script also helps to you set your own private ip and ec2 instance hostname and you can set your own custom environment variables on initial start of the machine.

import boto3, botocore

client = boto3.client(‘ec2’, region_name=’ap-south-1')

AMI = ‘ami-999999999999’
az_zone = ‘ap-south-1a’
InstanceType = “t3a.small”
SubnetId = ‘subnet-999999999999’
SecurityGroupId = ‘sg-999999999999’
IAMProfile = ‘arn:aws:iam::999999999999:instance-profile/ROLE_NAME’

SSH_KEY_FILE_NAME = ‘test’

def do(nodeName, environment, ip):
intialCommands = “””#!/bin/bash
sudo hostnamectl set-hostname “””+nodeName+”””
echo export “environment=’”””+environment+”””’” >> /etc/environment
“””

try:
response = client.run_instances(
ImageId=AMI,
InstanceType=InstanceType,
KeyName=SSH_KEY_FILE_NAME,
MaxCount=1,
MinCount=1,
Monitoring={ ‘Enabled’: True },
Placement={ ‘AvailabilityZone’: az_zone, ‘Tenancy’: ‘default’ },
SecurityGroupIds=[ SecurityGroupId ],
SubnetId= SubnetId,
UserData= intialCommands,
IamInstanceProfile={ ‘Arn’: IAMProfile },
InstanceInitiatedShutdownBehavior=’stop’,
PrivateIpAddress=ip,
TagSpecifications=[
{
‘ResourceType’: ‘instance’,
‘Tags’: [
{ ‘Key’: ‘Environment’, ‘Value’: environment },
{ ‘Key’: ‘Name’, ‘Value’: nodeName }
]
}, {
‘ResourceType’: ‘volume’,
‘Tags’: [
{ ‘Key’: ‘Environment’, ‘Value’: environment },
{ ‘Key’: ‘Name’, ‘Value’: nodeName }
]
}
]
)
print(response)
return True
except botocore.exceptions.ClientError as e:
print(e)
return False

do(‘node-n’, ‘staging’, ‘10.0.0.1’)

--

--