-
Notifications
You must be signed in to change notification settings - Fork 0
/
ec2_util.py
148 lines (136 loc) · 4.81 KB
/
ec2_util.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import os
import datetime
import boto3
import queue_util as queue_util
import global_constants
from botocore.exceptions import ClientError
const = global_constants.GlobalConstants()
script = '''
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
- [scripts-user, always]
--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"
#!/bin/bash
/bin/echo "Hello World" >> /tmp/testfile.txt
python3 /home/ubuntu/pi-eye-py/ec2-instance.py
--//
'''
sqs = boto3.client('sqs')
''', region_name=const.REGION,
aws_access_key_id=const.ACCESS_KEY,
aws_secret_access_key=const.SECRET_KEY)'''
ec2_client = boto3.client('ec2')
''', region_name=const.REGION,
aws_access_key_id=const.ACCESS_KEY,
aws_secret_access_key=const.SECRET_KEY)'''
ec2_resource = boto3.resource('ec2')
''', region_name=const.REGION,
aws_access_key_id=const.ACCESS_KEY,
aws_secret_access_key=const.SECRET_KEY)'''
# pylint: disable=E1101
def get_ec2_ids_state():
instances = {}
for instance in ec2_resource.instances.all():
instances[instance.id] = instance.state['Name']
return instances
# response = ec2_client.describe_instances() instance.network_interfaces_attribute.Description['PrivateIpAddress']
# for reservation in response["Reservations"]:
# for instance in reservation["Instances"]:
# # This sample print will output entire Dictionary object
# # print(instance)
# # This will print will output the value of the Dictionary key 'InstanceId'
# # print(instance["InstanceId"])
# instances.append(instance["InstanceId"])
def create_instance(count):
ec2_resource.create_instances(
# BlockDeviceMappings=[
# {
# 'DeviceName': 'Worker',
# 'VirtualName': 'string',
# 'Ebs': {
# 'DeleteOnTermination': True,
# 'Iops': 123,
# 'SnapshotId': 'string',
# 'VolumeSize': 123,
# 'VolumeType': 'standard'|'io1'|'gp2'|'sc1'|'st1',
# 'KmsKeyId': 'string',
# 'Encrypted': False
# },
# 'NoDevice': 'string'
# },
# ],
ImageId= const.AMI_ID,
MinCount=1,
MaxCount=count,
InstanceType='t2.micro',
# KeyName=const.KEY_FILENAME,
Monitoring={
'Enabled': False
},
Placement={
'AvailabilityZone': const.AVAILABILITY_ZONE,
},
# UserData='string',
DisableApiTermination=False,
DryRun = False,
EbsOptimized = False,
SecurityGroupIds=[
const.SECURITY_GROUP_ID,
],
# IamInstanceProfile={
# 'Arn': 'string',
# 'Name': 'string'
# },
InstanceInitiatedShutdownBehavior='stop'#,
# UserData =script,
)
# instance_id is a list
def start_instances(instance_id):
# Do a dryrun first to verify permissions
# count = len(instance_id)
# try:
# ec2_client.start_instances(InstanceIds=instance_id, DryRun=True)
# # ec2_client.run_instances(ImageId= const.AMI_ID,DryRun=True,MinCount=1,InstanceType='t2.micro',SecurityGroupIds=[
# # const.SECURITY_GROUP_ID],MaxCount=count,UserData=script)
# except ClientError as e:
# if 'DryRunOperation' not in str(e):
# raise
# Dry run succeeded, run start_instances without dryrun
try:
response = ec2_client.start_instances(InstanceIds=instance_id, DryRun=False)
# ec2_client.run_instances(ImageId= const.AMI_ID,DryRun=False,MinCount=1,InstanceType='t2.micro',SecurityGroupIds=[
# const.SECURITY_GROUP_ID],MaxCount=count,UserData=script)
#print(response)
except ClientError as e:
print(e)
# instance_id is a list
def stop_instances(instance_id):
# Do a dryrun first to verify permissions
# try:
# ec2_client.stop_instances(InstanceIds=instance_id, DryRun=True)
# except ClientError as e:
# if 'DryRunOperation' not in str(e):
# raise
# Dry run succeeded, call stop_instances without dryrun
try:
response = ec2_client.stop_instances(InstanceIds=instance_id, DryRun=False)
print(response)
except ClientError as e:
print(e)
if __name__ == "__main__":
#create_instance(1)
#print(script)
# instances = get_ec2_ids_state()
# stop_instances([k for k,v in instances.items() if v == 'running'])
pass