1#!/usr/bin/env python 2 3import boto3 4import json 5 6 7class Certificate(): 8 9 def __init__(self, certId=''): 10 self.id = certId 11 self.arn = '' 12 self.client = boto3.client('iot') 13 if (self.id != ''): 14 result = self.client.describe_certificate(certificateId=self.id) 15 self.arn = result['certificateDescription']['certificateArn'] 16 17 def create(self): 18 assert not self.exists(), "Cert already exists" 19 cert = self.create_keys_and_certificate() 20 self.id = cert["certificateId"] 21 self.arn = cert["certificateArn"] 22 return cert 23 24 def create_keys_and_certificate(self): 25 result = self.client.create_keys_and_certificate(setAsActive=True) 26 return result 27 28 def delete(self): 29 cert_not_found = True 30 # Detach Policies attached to the cert 31 policies_attached = self.list_policies() 32 for policy in policies_attached: 33 self.detach_policy(policy['policyName']) 34 35 # Detach Things attached to the cert 36 things_attached = self.list_things() 37 for thing in things_attached: 38 self.detach_thing(thing) 39 40 # Update the status of the certificate to INACTIVE 41 try: 42 self.client.update_certificate(certificateId=self.id, 43 newStatus='INACTIVE') 44 cert_not_found = False 45 except self.client.exceptions.ResourceNotFoundException: 46 cert_not_found = True 47 return cert_not_found 48 49 # Delete the certificate 50 try: 51 self.client.delete_certificate(certificateId=self.id) 52 cert_not_found = False 53 except self.client.exceptions.ResourceNotFoundException: 54 cert_not_found = True 55 return cert_not_found 56 57 def exists(self): 58 if self.id == '': 59 return False 60 else: 61 return True 62 63 def get_arn(self): 64 return self.arn 65 66 def list_policies(self): 67 policies = self.client.list_principal_policies(principal=self.arn) 68 policies = policies['policies'] 69 return policies 70 71 def attach_policy(self, policy_name): 72 self.client.attach_policy(policyName=policy_name, target=self.arn) 73 74 def detach_policy(self, policy_name): 75 self.client.detach_policy(policyName=policy_name, target=self.arn) 76 77 def list_things(self): 78 things = self.client.list_principal_things(principal=self.arn) 79 things = things['things'] 80 return things 81 82 def attach_thing(self, thing_name): 83 self.client.attach_thing_principal(thingName=thing_name, 84 principal=self.arn) 85 86 def detach_thing(self, thing_name): 87 self.client.detach_thing_principal(thingName=thing_name, 88 principal=self.arn) 89