-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_thing.py
72 lines (59 loc) · 2.3 KB
/
create_thing.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
#This python script runs AWS CLI commands and relies on the permissions on your AWS CLoud9 instance
#Create IoT thing for simulation and define thing policy, create and dowload certs
import json
from collections import namedtuple
import os
import subprocess as sp
#Define path
path = os.path.abspath( os.path.dirname( __file__ ) )
print(path)
#Gets role arn
#defines iot thing creation command
def CreateThing():
create_thing_json = sp.getoutput("aws iot create-thing --thing-name all_pumping_stations")
create_thing = json.loads(create_thing_json)
print(create_thing)
thing_id = create_thing["thingName"]
return(thing_id)
#defines policy creation function and command
def CreatePolicy():
cli_cmd = f'aws iot create-policy --policy-name "pumping_station_simulation" --policy-document file://thing_policy.json'
print(cli_cmd)
create_policy_json = sp.getoutput(cli_cmd)
print(create_policy_json)
create_policy = json.loads(create_policy_json)
print(create_policy)
policy_name = create_policy["policyName"]
return(policy_name)
#defines certificates and keys creation command
def CreateCertKeys():
create_cert_key_json = sp.getoutput('aws iot create-keys-and-certificate \
--certificate-pem-outfile "all_pumping_stations.cert.pem" \
--public-key-outfile "all_pumping_stations.public.key" \
--private-key-outfile "all_pumping_stations.private.key" \
--set-as-active')
print(create_cert_key_json)
create_cert_key = json.loads(create_cert_key_json)
return (create_cert_key["certificateArn"])
#attach policy to certificate
def Attachpolicy(policy_name, target):
cli_cmd = sp.getoutput(f'aws iot attach-policy \
--policy-name "{policy_name}"\
--target "{target}"')
print(cli_cmd)
#attach cert to thing
def AttachCert(principal, thing_name):
cli_cmd = sp.getoutput(f'aws iot attach-thing-principal \
--thing-name "{thing_name}"\
--principal "{principal}"')
print(cli_cmd)
#get root CA
def GetRootCa():
shell_cmd = sp.getoutput("curl -o root-CA.crt https://www.amazontrust.com/repository/AmazonRootCA1.pem")
print(shell_cmd)
GetRootCa()
thing_name = CreateThing()
policy_name = CreatePolicy()
principal = CreateCertKeys()
Attachpolicy(policy_name, principal)
AttachCert(principal, thing_name)