def clean()

in deploy/deploy_agent.py [0:0]


def clean(iotClient, iotConfig, all=True, number=0):
    resp = iotClient.list_things_in_thing_group(thingGroupName=iotConfig['thingGroup'])
    things = resp['things']
    while 'nextToken' in resp:
        resp = iotClient.list_things_in_thing_group(
            thingGroupName=iotConfig['thingGroup'],
            nextToken=resp['nextToken']
        )
        things.extend(resp['things'])

    sample_dir = os.path.dirname(iotConfig['iotConfigPath'])
    for thing_name in things:
        resp = iotClient.list_thing_principals(
            thingName=thing_name
        )
        certificateIds = []
        for principal in resp['principals']:
            certificateId = principal.split('/')[-1]
            certificateIds.append(certificateId)
            iotClient.detach_policy(
                policyName=iotConfig['devicePolicy'], target=principal
            )
            iotClient.update_certificate(
                certificateId=certificateId, newStatus='INACTIVE'
            )
            iotClient.detach_thing_principal(
                thingName=thing_name,
                principal=principal
            )
        # wait for detach finish
        while True:
            resp = iotClient.list_thing_principals(
                thingName=thing_name
            )
            if not resp['principals']:
                break
            time.sleep(1)
        for certificateId in certificateIds:
            iotClient.delete_certificate(certificateId=certificateId, forceDelete=True)
        iotClient.delete_thing(thingName=thing_name)

        client_id = thing_name.split('_', 1)[-1]
        try:
            os.remove('%s/%s.pem.crt' % (iotConfig['thingCertDir'], client_id))
            os.remove('%s/%s.pem.key' % (iotConfig['thingCertDir'], client_id))
            os.remove('%s/%s' % (sample_dir, client_id))
        except OSError as e:
            logging.warn('Failed to remove device credentials %s', str(e))
        for proc in psutil.process_iter():
            if proc.name() == client_id:
                proc.kill()
        pidfile = '/tmp/%s.pid' % client_id
        if os.path.exists(pidfile):
            os.remove(pidfile)