-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathec2_extra.py
executable file
·60 lines (47 loc) · 1.6 KB
/
ec2_extra.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env python
import boto3
import botocore.exceptions
ec2 = boto3.resource('ec2')
# allow SSH access
try:
security_group = ec2.create_security_group(GroupName='ssh_access',
Description='pug talk')
security_group.authorize_ingress(IpProtocol='tcp',
CidrIp='0.0.0.0/0',
FromPort=22,
ToPort=22)
except botocore.exceptions.ClientError:
pass
# create SSH key
try:
key = ec2.create_key_pair(KeyName='cpug')
with open('cpug.pem', 'w') as file:
file.write(key.key_material)
except botocore.exceptions.ClientError:
pass
# launch an instance with SSH key + Security Group (port 22)
instances = ec2.create_instances(ImageId='ami-11032472',
InstanceType='t2.micro',
MinCount=1,
MaxCount=1,
SecurityGroupIds=['ssh_access'], # <-- security group
KeyName='cpug') # <-- ssh key
print('launching')
instances[0].wait_until_running()
print('running')
ip_address = ec2.Instance(instances[0].id).public_ip_address
import time
import socket
print('running')
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
try:
s.connect((ip_address, 22))
break
except:
pass
s.close()
time.sleep(1)
print('might need to run: chmod 400 cpug.pem')
print('type: ssh -i cpug.pem ec2-user@' + ip_address)