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