qa805542
qa805542

Reputation: 63

Detach thing from AWS IoT Certificate

I am trying to delete AWS IoT certificates for a Thing. I am using aws-sdk-go-v2. From documentation I understood that to delete certificates, we must: 1) detach policy 2) detach thing 3) set certificate as inactive and then 4) delete certificates.

I am able to detach policy(DetachPolicy), deactivate certificate(UpdateCertificate), But unable to detach thing. To detach thing I am using DetachThingPrincipal method. In doc its mentioned that its an asynchronous API. Normally to handle Async APIs we use goroutines and channels to fetch data whenever response is ready. But in this case it seems that it is handled internally. So I have simply invoked the method as a normal function.

if op, err := iotClient.DetachThingPrincipal(context.TODO(), &iot.DetachThingPrincipalInput{
        Principal: aws.String(credInfo["certfARN"]),
        ThingName: aws.String(deviceId),
    }); err != nil {
        fmt.Println("ERROR: [deleteCreds] - Unable to detach thing:", err.Error())
        return err
    }

As a response I don't get any error and next I invoke DeleteCertificate method. The method throws "Things must be detached before deletion" error. How can this issue be fixed ?

As it may take time to detach thing should I add a wait timer of few seconds and then try to delete certificate ?

Upvotes: 2

Views: 677

Answers (1)

Jay
Jay

Reputation: 9509

I know you may need a Go code.. But I have a equivalent code in Javascript, you could do similar

The main essence is it works on async/await once the detach completes it then carry on.

/**
 * Detach the given certificate from the given Thing 
 * 
 * @param thingName 
 * @param certificateArn 
 * @returns 
 */
export const detachCertificateFromThing = async (thingName: string, certificateArn: string) => {

  const detachThingPrincipalRequest: DetachThingPrincipalRequest = {
    thingName,
    principal: certificateArn
  }
  const result = await iot.detachThingPrincipal(detachThingPrincipalRequest).promise()
  return result
}

And to use the above helper, you would do like this

 // detach certificate from thing
 const detachCertificateResponse = await detachCertificateFromThing(thingName, certificateArn)
 console.log(`Certificate ARN: ${certificateArn} detach from thing: ${thingName}, response: ${JSON.stringify(detachCertificateResponse)}`);

Upvotes: 0

Related Questions