aws-cdk-examples
aws-cdk-examples copied to clipboard
Need samples for AWS IoT
Describe the feature
Samples for AWS IoT
Use Case
I want to use CDK to build a AWS IoT Core example.
- Create IoT things
- Create a x509 certificate
- Create a policy
- Attach the policy to the certificate
- Attach the certificate to the thing
- Further integrate with other services such as Kinesis
Proposed Solution
I am stuck at how to create the IoT x509 certificate using CDK. So I have to create a certificate from AWS CLI then pass the certificate ARN into CDK
aws iot create-keys-and-certificate \
--set-as-active \
--certificate-pem-outfile esp-certificate.crt \
--public-key-outfile esp-public.key \
--private-key-outfile esp-private.key \
--region ap-southeast-1
CDK stack
import { aws_iam, aws_iot, Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
interface AwsIotDemoStackProps extends StackProps {
certificateArn: string
}
export class AwsIotDemoStack extends Stack {
constructor(scope: Construct, id: string, props: AwsIotDemoStackProps) {
super(scope, id, props);
// create a thing
const thing = new aws_iot.CfnThing(
this,
'DemoDeviceThing', {
thingName: 'DemoDevice'
}
)
// create a policy
const policy = new aws_iot.CfnPolicy(
this,
'PolicyForDemoDevice',
{
policyName: 'PolicyForDemoDevice',
policyDocument: new aws_iam.PolicyDocument(
{
statements: [
new aws_iam.PolicyStatement(
{
actions: ['iot:*'],
resources: ['*'],
effect: aws_iam.Effect.ALLOW
}
)
]
}
)
}
)
// attach the policy to certificate
const attachPolicy = new aws_iot.CfnPolicyPrincipalAttachment(
this,
'AttachPolicyForDemoDevice',
{
policyName: policy.policyName!.toString(),
principal: props.certificateArn
}
)
attachPolicy.addDependsOn(
policy
)
// attach the certificate to the IoT thing
const attachCert = new aws_iot.CfnThingPrincipalAttachment(
this,
'AttachCertificiateToThing',
{
thingName: thing.thingName!.toString(),
principal: props.certificateArn
}
)
attachCert.addDependsOn(
thing
)
}
}
Other Information
No response
Acknowledgements
- [x] I may be able to implement this feature request
- [ ] This feature might incur a breaking change
Language
Typescript
Would you be able to help us out with this @yamatatsu?
@peterwoodworth I'll try to create the example.
@entest-hai
CDK (and CloudFormation) does not have the feature of create-keys-and-certificate.
If you wanna create certs with cdk, you can create the cert with using a csr created on your local machine. See, https://github.com/aws/aws-cdk/issues/19303#issuecomment-1063722656 .
Or you can create thing and cert in only cdk with the 3rd party constructs. https://constructs.dev/packages/cdk-iot-core-certificates/v/0.0.3?lang=typescript
If you use this 3rd party constructs, you can get cert from AWS SSM parameter store.
I am working on this FR