How to register the X.509 Certificate using CDK

Did you know that you can register the X.509 Certificate in the AWS IoT Core using AWS Cloud Development Kit (CDK)?

Simplified registration process:

  • generate the Private Key locally
  • based on that Private Key generate the Certificate Signing Request (CSR)
  • use the below code to register your X.509 Certificate based on generated CSR
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from aws_cdk import (
    Stack,
    aws_iot as iot,
    CfnOutput
)
from constructs import Construct

class IotCdkStack(Stack):

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)
        
        # read locally generated CSR (Certificate Signing Request)
        with open("creds/SomeThing.csr","r") as csr_file:
            csr = csr_file.read()
        
        # register and activate the X.509 Certificate in AWS IoT Core
        cfn_certificate = iot.CfnCertificate(self, "CfnCertificate",
            status = "ACTIVE",
            certificate_signing_request = csr
        )

        # output the ID of registered X.509 Certificate 
        CfnOutput(self, "CertificateId", value = cfn_certificate.attr_id)

Question: How can we obtain the X.509 itself? We need the PEM file to connect our device to the AWS IoT Core.

Answer: To download the X.509 Certificate body we need the certificateId. Luckily, we can obtain this identifier from the output of our CDK deployment:

1
2
Outputs:
IotCdkStack.CertificateId = fd2b5440961d88d42f54b606b117c64523b4ebbb25fbb50d97c932f65b3991d0

We can use AWS SDK to describe the X.509 Certificate in IoT Core and obtain its content.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import boto3

session = boto3.Session(profile_name = "MySecretProfile")
iot_c = session.client('iot')

# describe the X.509 Certificate
cert = iot_c.describe_certificate(
    certificateId = "fd2b5440961d88d42f54b606b117c64523b4ebbb25fbb50d97c932f65b3991d0"
)['certificateDescription']['certificatePem']

# store the X.509 Certificate as a PEM file
with open("creds/SomeThing.pem","w") as pem_file:
    pem_file.write(cert)

That is all for today, I hope it was interesting for you!

Support quality content❤️ Donate💰

Sign up for news: (by subscribing you accept the privacy policy)