import boto3
import time
c = boto3.client('ec2')
ec2 = boto3.resource('ec2')
userdata = """#!/bin/bash -x
exec > /tmp/log 2>&1
yum -y install htop
"""
instanceName = 'test'
#instanceName = 'ftp-test'
args = {
'ImageId': 'ami-0c02fb55956c7d316', # amazon linux 2,
#'InstanceType': 't2.micro', # vcpu 1 mem 1
'InstanceType': 't3.medium', # vcpu 2 mem 4
#'InstanceType': 't3a.large', # vcpu 2 mem 8
'BlockDeviceMappings': [
{
'DeviceName': '/dev/xvda',
'Ebs': {
'DeleteOnTermination': True,
'VolumeSize': 50,
'VolumeType': 'gp2',
}
}
],
'SecurityGroupIds': ['sg-0161b674be972b4e4'], # all
'SubnetId': 'subnet-51a93b35', # sa-east-1a
'KeyName': 'automation',
'InstanceInitiatedShutdownBehavior': 'stop', # stop|terminate
'UserData': userdata,
'MaxCount': 1,
'MinCount': 1,
'TagSpecifications': [
{
'ResourceType': 'instance',
'Tags': [
{'Key': 'Name', 'Value': instanceName},
]
}
]
}
rs = c.run_instances(**args)
instanceid = rs['Instances'][0]['InstanceId']
time.sleep(3)
instance = ec2.Instance(instanceid)
for i in range(10):
instance = ec2.Instance(instanceid)
#print(instance.state) #{'Code': 16, 'Name': 'running'} pending
if instance.state['Name'] == 'running':
break
time.sleep(5)
ipaddress = print(instance.public_ip_address)
print(ipaddress)