Skip to content

Instantly share code, notes, and snippets.

@zdotfive
Forked from bgdnlp/boto3_create_ec2_example.py
Created January 29, 2022 07:41
Show Gist options
  • Save zdotfive/aac8ab646af6af6b25e92ebf0d3471c5 to your computer and use it in GitHub Desktop.
Save zdotfive/aac8ab646af6af6b25e92ebf0d3471c5 to your computer and use it in GitHub Desktop.
# needs Python3, though easily adapted
from __future__ import unicode_literals
import boto3
def main():
session = boto3.session.Session(profile_name='aws_credentials_profile')
ec2 = session.resource('ec2')
# define instance parameters
# type
image_id = get_amazon_linux_ami()
instance_type = 't2.nano'
# network
security_group_ids = ['sg-abcde123']
subnet_id = 'subnet-abcde123' # bogdan_private 1a
network_interfaces = [
{
'DeviceIndex': 0,
'SubnetId': subnet_id,
'Groups': security_group_ids,
'AssociatePublicIpAddress': False
}
]
# storage
block_device_mappings = [
{
'DeviceName': get_root_device_name(image_id),
'Ebs': {
'VolumeSize': 8,
'DeleteOnTermination': True,
'VolumeType': 'gp2',
},
},
]
ebs_optimized = False # TODO: maybe it can be determined from instance type?
# access
ssh_key_name = 'add-one-or-lose-access'
iam_instance_profile='' # role
#user_data = get_user_data('script_to_run_on_first_boot.sh')
disable_api_termination = False
# create instance(s)
print('Creating instance...')
instances = ec2.create_instances(
ImageId=image_id,
MinCount=1,
MaxCount=1,
KeyName=ssh_key_name,
UserData=user_data,
InstanceType=instance_type,
BlockDeviceMappings=block_device_mappings,
DisableApiTermination=disable_api_termination,
NetworkInterfaces=network_interfaces,
EbsOptimized=ebs_optimized
)
# add tags
print('Tagging...')
for instance in instances:
instance.create_tags(
Tags=[
{
'Key': 'Name',
'Value': 'Bogdan_boto_test'
}
]
)
# wait for instance(s) to start
instance_ids = []
for instance in instances:
instance_ids.append(instance.id)
print('Waiting for running state')
waiter = ec2.meta.client.get_waiter('instance_running')
waiter.wait(InstanceIds=instance_ids)
for instance in instances:
print(instance.private_ip_address, instance.public_ip_address)
print('Waiting for status ok')
waiter = ec2.meta.client.get_waiter('instance_status_ok')
waiter.wait(InstanceIds=instance_ids)
print('Waiting for console output')
waiter = ec2.meta.client.get_waiter('console_output_available')
waiter.wait(InstanceId=instance_ids[0])
def get_amazon_linux_ami():
# A dummy function for now, when developped it should return one and only
# one id of an Amazon Linux AMI to be used. Arguments can be passed on to
# to identify the exact image. 'latest' should return the newest version
# of Amazon Linux, HVM, EBS-Backed, 64-bit (the most used image),
# depending on region
return 'ami-bff32ccc'
def get_root_device_name(image_id):
# will return the device name for a particular image (ex. '/dev/sda1')
return '/dev/xvda'
def get_user_data(file_name=False):
# Returns user data to be passed to cloud-init on instance launch.
# i.e. add ansible user, add proper ssh key. The commands to run could be
# defined here, or loaded from a text file. Maybe use a parameter for that
user_data = ''
if file_name:
with open(file_name, 'r') as f:
user_data = f.read()
return user_data
if __name__ == "__main__":
# execute only if run as a script
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment