In AWS IoT, delete the certificate that is not attached to the thing. For when you have created a large number of unnecessary certificates.
import boto3
class CertKiller():
def __init__(self):
#Instantiate a class that operates AWS IoT
self.client = boto3.client('iot')
return
def delete_not_attached_cert_all(self):
'''
Delete certificates that are not attached to things
'''
#Get a list of certificate information
list_cert = self.get_list_cert()
#Delete certificates that are not attached to things
for cert in list_cert:
self.__delete_not_attached_cert(cert)
return
def get_list_cert(self):
'''
Get a list of certificate information
'''
list_cert = self.client.list_certificates(pageSize=100)['certificates']
return list_cert
def __delete_not_attached_cert(self, cert):
'''
Delete if the certificate was not attached to any object
'''
#Get certificate information
cert_arn = cert['certificateArn']
cert_id = cert['certificateId']
#Get a list of things with a certificate attached
thing_attached_cert = self.client.list_principal_things(principal=cert_arn)['things']
print(cert_arn, thing_attached_cert)
#Delete if the certificate was not attached to any object
if len(thing_attached_cert) == 0:
self.__delete_cert(cert_arn, cert_id)
else:
pass
return
def __delete_cert(self, cert_arn, cert_id):
'''
Delete certificate
'''
#Must be disabled before deletion
self.client.update_certificate(certificateId=cert_id, newStatus='INACTIVE')
#Policy must be detached before deletion
self.__detach_all_policy(cert_arn, cert_id)
#Delete
self.client.delete_certificate(certificateId=cert_id, forceDelete=False)
print('{} has been deleted.'.format(cert_arn))
return
def __detach_all_policy(self, cert_arn, cert_id):
'''
Detach all policies attached to the certificate
'''
#Get a list of policies attached to the certificate
list_policy = self.client.list_attached_policies(target=cert_arn)['policies']
#Detach
for policy in list_policy:
policy_name = policy['policyName']
self.client.detach_policy(policyName=policy_name, target=cert_arn)
return
cert_killer = CertKiller()
cert_killer.delete_not_attached_cert_all()
I am a very beginner, so I would appreciate it if you could point out and comment on even the smallest things.