AWS Cloud Development Kit (CDK)
Recent questions
see all1/18
- In my CDK project, I use a lot of Docker images for various services. These images are for different platforms, since Fargate doesn't support Spot ARM64. Building all of these images on my own machine (an Apple M1 Pro) can be quite cumbersome. Out of curiosity, I was wondering if there is a convenient way to build these Docker images on AWS. Ideally, when I run 'cdk deploy --all', it would upload my assets to AWS, build the Docker images, and publish the results on ECR. Do you have any ideas on how I could achieve this?
- Is there a way to query Timestream from an Appsync API using an HTTP resolver? Is there any examples of setting that up using the cdk?
- I am trying to invoke googleapis through AWS lambda. I am using a google service account to generate server-server authentication. we have stored the service account details in a JSON file name 'config.json'. Inorder to invoke API for google, we need to create auth object using the 'GoogleAuth' class and pass the config file path as a value to the 'keyfile' property. Though we have provided the correct path location of the file, lambda could not recognize the path and throw error. For path, I have tried absolute, and relative paths, using Path package with '__dirname", process.env.cwd(), used environment variable etc. I even tried with assets too. I am using AWS cdk to form cloud formation using nodejs. My intention is to invoke google apis using service account credentials with AWS lambda. ``` import {GoogleAuth} from 'google-auth-library' const auth = new GoogleAuth({ keyFile: 'path/to/file', scope: SCOPES }) ``` ``` undefined ERROR Uncaught Exception {"errorType":"Error","errorMessage":"ENOENT: no such file or directory, open '/keys/config.json'","code":"ENOENT","errno":-2,"syscall":"open","path":"/keys/config.json","stack":["Error: ENOENT: no such file or directory, open '/keys/config.json'"," at Object.openSync (node:fs:601:3)"," at Object.readFileSync (node:fs:469:35)"," at Object.<anonymous> (/var/task/index.js:533512:28)"," at Module._compile (node:internal/modules/cjs/loader:1254:14)"," at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)"," at Module.load (node:internal/modules/cjs/loader:1117:32)"," at Module._load (node:internal/modules/cjs/loader:958:12)"," at Module.require (node:internal/modules/cjs/loader:1141:19)"," at require (node:internal/modules/cjs/helpers:110:18)"," at _tryRequireFile (file:///var/runtime/index.mjs:912:37)"]} ```
- ``` new UserPoolClient(this, 'Client', { idTokenValidity: Duration.hours(2), accessTokenValidity: Duration.hours(2), // CDK BUG! sets to 1 minute which is error refreshTokenValidity: Duration.hours(12), ``` is synthesized as: ``` TokenValidityUnits: AccessToken: minutes IdToken: minutes RefreshToken: minutes RefreshTokenValidity: 1 // <- WRONG! IdTokenValidity: 120 AccessTokenValidity: 120 ```
- I have added two very similar OIDC id provider to cognito user pool with cdk. Why is the <domain>.<region>.amazoncognito.com/oauth2/idpresponse giving error_description=username+attribute+mapping+required&error=invalid_request ? I have successfully added two OIDC and one SAML id provider. username is not one of the attributes you can add - it's provided by default.
- I'm working on my first CDK stack, and it's frustratingly not working at all. It dies when I go to run deploy with the following error: ``` Building assets failed: Error: Building Assets Failed: Error: FuseArchiver: Socket timed out without establishing a connection ``` If I run it with `cdk deploy -vv` I get these last few lines after it run synthesis: ``` [15:21:15] Retrieved account ID xxxxxxxxx from disk cache [15:21:15] Assuming role 'arn:aws:iam::xxxxxxxxxxx:role/cdk-hnb-xxxxxx-deploy-role-xxxxxxxxxxxx-us-east-1'. [15:21:16] Waiting for stack CDKToolkit to finish creating or updating... [15:21:16] [AWS cloudformation 200 0.081s 0 retries] describeStacks({ StackName: 'CDKToolkit' }) [15:22:35] [AWS ssm undefined 79.686s 6 retries] getParameter({ Name: '/cdk-bootstrap/hnxxxxxds/version' }) [15:22:35] Call failed: getParameter({"Name":"/cdk-bootstrap/hnxxxxxxfds/version"}) => Socket timed out without establishing a connection (code=TimeoutError) ❌ Building assets failed: Error: Building Assets Failed: Error: FuseArchiver: Socket timed out without establishing a connection at buildAllStackAssets (D:\Users\xxxxx\apps\nvm\v18.15.0\node_modules\aws-cdk\lib\index.js:374:115279) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async CdkToolkit.deploy (D:\Users\xxxxx\apps\nvm\v18.15.0\node_modules\aws-cdk\lib\index.js:374:143496) at async exec4 (D:\Users\xxxxx\apps\nvm\v18.15.0\node_modules\aws-cdk\lib\index.js:429:51795) [15:22:52] Reading cached notices from D:\Users\xxxxx\.cdk\cache\notices.json Building Assets Failed: Error: FuseArchiver: Socket timed out without establishing a connection [15:22:52] Error: Building Assets Failed: Error: FuseArchiver: Socket timed out without establishing a connection at buildAllStackAssets (D:\Users\xxxxx\apps\nvm\v18.15.0\node_modules\aws-cdk\lib\index.js:374:115279) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async CdkToolkit.deploy (D:\Users\xxxxx\apps\nvm\v18.15.0\node_modules\aws-cdk\lib\index.js:374:143496) at async exec4 (D:\Users\xxxxx\apps\nvm\v18.15.0\node_modules\aws-cdk\lib\index.js:429:51795) ``` So it looks like it dies when it goes to talk to AWS SSM with getParameter call. I'm running this from an AWS workspace inside a VPC which should be able to talk to SSM, but can't. I've had some issues with SSM reaching my boxes in the past with permissions, but I think those are resolved. I'm using node: v18.15.0, CDK 2.69.0, and Windows 10
- I created a Kinesis stream and CfnDestination in my account through CDK in <region-1>. And created CloudWatch logs subscription filters in cross-accounts to stream data to my kinesis. Now for subscription filters in <region-2> accounts I will need to create CfnDestinations in <region-2>. I followed [this AWS Article](https://aws.amazon.com/premiumsupport/knowledge-center/streaming-cloudwatch-logs/) to achieve it through CLI. Now I want to integrate this step in my CDK code. I checked through various AWS resources/articles & went through the CfnDestination code base, but couldn't find any place in code where I can specify the region where the CfnDestination should be created.
- Hello, I'm using Java CDK to create a new ECR instance. Here is a code fragment: Repository.Builder.create(scope, id).imageScanOnPush(true) .repositoryName("my-registry").removalPolicy(RemovalPolicy.DESTROY).build(); Looking in the AWS Console, the name of the new created repository is "null/my-registry" instead of "my-registry". If I create the new ECR instance in AWS Console then its name is created as expected, i.e. "my-registry" and not "null/my-registry". What am I doing wrong here ? Many thanks in advance. Nicolas
- When I use @aws-solutions-constructs/aws-sns-sqs, the construct creates its own topic and queue, and makes the subscription between them, regardless of whether I specify existingTopicObj and/or existingQueueObj. E.g., ``` // subscribe the queue to the ihsTopic (from the global stack) const snsToSqsStack = new SnsToSqs(this, env.buildId(baseStackName, 'SnsToSqsPattern'), { existingTopicObj: ihsTopic }); ``` results in the creation of ``` dev2-MPNManagementIHSStack-dev2MPNManagementIHSSnsToSqsPatternSnsTopic3CE13A35-dK7u7eSgJnJ6 subscription: 72965362-92af-4ee3-8fb4-398e90ed93dd arn:aws:sqs:us-west-1:225996342467:dev2-MPN... ``` rather than using the specified ``` dev2-MPNManagementGlobalIHSTopic ``` I understand that this is still in 'experimental' status, so should I not expect this feature to work? Please advise, thank, Mitchell
- Any active projects on the CDK roadmap for a FSx Windows file system L2 construct? I just searched through the roadmap repo in GitHub and could not find any. I currently use the cfnFileSystem L1 construct to deploy a FSx file system plus an ec2.instance L2 construct to deploy a FSx file gateway appliance. However, I could use support for activating the gateway and attaching a file system to the former. Thanks.
- My CDK app has two stacks defined, one for a prod environment and one for a dev environment. I have a CloudFront function defined in the stack with a different file path for dev and prod builds (the behavior of the function necessarily needs to be different for dev and prod, i.e. the dev function implements basic authentication so that the dev site will not be publicly accessible and I don't want that code on the prod side). So for example, the CloudFront function is defined as follows: ``` const cfViewerRequest = new cloudfront.Function(this, "MySite-CFViewerRequest", { code: cloudfront.FunctionCode.fromFile({filePath: `backend/functions/cf-viewer-request/build-${props.stage}/index.js`}), functionName: `MySite-CFViewerRequest-${props.stage}`, comment: `MySite-CFViewerRequest-${props.stage}` }); ``` The idea here is that when the "stage" prop is passed to the stack constructor (it is set to either "dev" or "prod"), the resulting file path for the function will either be "build-dev" or "build-prod". However, if I only build the dev version, I get an error `ENOENT: no such file or directory, open 'backend/functions/cf-viewer-request/build-prod/index.js'` when running cdk synth with the dev stack name, since only the dev resource was built. The same goes for other resources, such as the CloudFront deployment, which also has specific dev and prod build directories. How can I run CDK commands for the dev stack without having to build the prod resources beforehand? Or is there a better way I should be going about this? Here is the entry point code: ``` #!/usr/bin/env node import "source-map-support/register"; import * as cdk from "aws-cdk-lib"; import { MySiteStack } from "../lib/my-site-stack"; const app = new cdk.App(); new MySiteStack(app, "MySiteDev", { env: { account: "012345678901", region: "us-east-1" }, stage: "dev", }); new MySiteStack(app, "MySiteProd", { env: { account: "109876543210", region: "us-east-1" }, stage: "prod", }); ```
- I received an email to inform me to update some CDK stacks to version 2 or all of my stacks firstly created with CDK 1 were migrated on v2 from January 2022. Despite several searches via the console or using [awscdk-v1-stack-finder](https://github.com/cdklabs/awscdk-v1-stack-finder) No stacks were found. CDK v1 entered on end-of-support period on June 1, 2023. So I would like to make sure that I don't have andy stacks or nested stacks in CDK v1. Do you have any idea how to do this ?
- Hi, I just did as I always used to do: * Create a Cloud9 using Amazon Linux 2 * upgrade AWS CLI to v2 * initialize a CDK app and add some sample code * I am logged on using a role that has 'AdministratorAccess' policy attached and it is assumed by Cloud9. * CDK is bootstrapped. Running 'cdk deploy' now gives the following error: ``` current credentials could not be used to assume 'arn:aws:iam::ACCOUNTNUMBER:role/cdk-hnb659fds-deploy-role-ACCOUNTNUMBER-eu-central-1', but are for the right account. Proceeding anyway. ❌ Building assets failed: Error: Building Assets Failed: Error: TestStack: The security token included in the request is invalid at buildAllStackAssets (/home/ec2-user/.nvm/versions/node/v16.19.1/lib/node_modules/cdk/node_modules/aws-cdk/lib/index.js:362:115279) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async CdkToolkit.deploy (/home/ec2-user/.nvm/versions/node/v16.19.1/lib/node_modules/cdk/node_modules/aws-cdk/lib/index.js:362:142800) at async exec4 (/home/ec2-user/.nvm/versions/node/v16.19.1/lib/node_modules/cdk/node_modules/aws-cdk/lib/index.js:417:51795) Building Assets Failed: Error: TestStack: The security token included in the request is invalid ``` * I deleted the CDKToolkit stack and did run 'cdk bootstrap' again, it created the stack again. So apparently this works. * Running ' aws sts get-caller-identity' also shows the right role. * I also tried on an old instance that was stopped, getting same result. Ideas?
- Hi, This CLI command to create a job from an AWS managed template works: ``` $ aws iot create-job --targets 'arn:aws:iot:region:account:thing/thingname' --job-id 'test-aws-job' --job-template-arn 'arn:aws:iot:region::jobtemplate/AWS-Run-Command:1.0' --document-parameters '{"command": "ls","runAsUser": "root"}' ``` but this seemingly equivalent CDK custom resource doesn't. CDK deploy returns `Message returned: Document parameters are only supported for managed job templates.`: ``` const testAwsJobUuid = 'test-aws-job' + uuidv4(); const testDocumentParameters = new Map<string, string>([ ["command", "ls"], ["runAsUser", "root"] ]); const testAwsJob = new cr.AwsCustomResource(this, 'test-aws-job', { onCreate: { service: 'Iot', action: 'createJob', parameters: { targets: [`arn:aws:iot:${process.env.CDK_DEFAULT_REGION}:${process.env.CDK_DEFAULT_ACCOUNT}:thing/thingname`], jobTemplateArn: `arn:aws:iot:${process.env.CDK_DEFAULT_REGION}:${process.env.CDK_DEFAULT_ACCOUNT}:jobtemplate/AWS-Run-Command:1.0`, documentParameters: testDocumentParameters, jobId: `${testAwsJobUuid}` }, physicalResourceId: cr.PhysicalResourceId.of(Date.now().toString()), }, policy: cr.AwsCustomResourcePolicy.fromSdkCalls({ resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE, }), }); ``` Many thanks, Gary
- Hello, I am aware of AWS Systems Manager templates ServiceNow has. But our team has a review and application process(terraform), hence we do not want to use this. The usecase I have here: Automate ServiceNow requests (Push from ServiceNow?) to insert request details into an AWS Datastore(Dynamo). We have a post process from here that takes care of rest. The request , could be for resources such as Accounts, config, VPC. I believe AWS Lambda makes sense for this effort, but I am also looking for a trigger from Service Now. Please also let me know if there are better alternatives Thank You.
- I am Deploying EKS cluster using CDK pipeline in Typescript This is May Cluster Stack, import { PhysicalName, Stack, StackProps } from "aws-cdk-lib"; import * as ec2 from 'aws-cdk-lib/aws-ec2'; import { Vpc } from "aws-cdk-lib/aws-ec2"; import * as eks from 'aws-cdk-lib/aws-eks'; import { Cluster } from "aws-cdk-lib/aws-eks/lib/cluster"; import { AccountRootPrincipal,Role } from "aws-cdk-lib/aws-iam"; import { Construct } from "constructs"; export interface DevOpsClusterStackProps extends StackProps { cluster:Cluster, vpc:Vpc, } export class DevOpsClusterStack extends Stack { public readonly cluster: eks.Cluster; accountId = this.account; clusterName = "DevOpsCluster" Role: Role; /* Cluster Role Defined */ constructor(scope: Construct, id: string, props: DevOpsClusterStackProps) { super(scope, id, props); this.accountId = this.account; this.clusterName = "DevOpsCluster"; const clusterAdmin = new Role(this, 'clusterAdmin', { assumedBy: new AccountRootPrincipal(), roleName: "clusterAdmin", }); /* Cluster Configuration */ const cluster = new eks.Cluster(this, 'DevOpsCluster', { clusterName: "DevOpsCluster", version: eks.KubernetesVersion.V1_23, defaultCapacity: 3, mastersRole: clusterAdmin, defaultCapacityInstance: ec2.InstanceType.of(ec2.InstanceClass.M5, ec2.InstanceSize.LARGE), vpc:props.vpc, vpcSubnets: [{ subnetType: ec2.SubnetType.PUBLIC }], }); cluster.addAutoScalingGroupCapacity('spot-group', { instanceType: new ec2.InstanceType('m5.xlarge'), }); if (Stack.of(this).region==this.region) this.Role = createDeployRole(this, `for-1st-region`, cluster); this.cluster = cluster; } } function createDeployRole(scope: Construct, id: string, cluster: eks.Cluster): Role { const role = new Role(scope, id, { roleName: PhysicalName.GENERATE_IF_NEEDED, assumedBy: new AccountRootPrincipal() }); cluster.awsAuth.addMastersRole(role); return role; } export interface PipelineStack extends StackProps { Cluster: eks.Cluster, Role: Role, } and This is My Pipeline Stack to Deploy this cluster using Pipeline import { Stack, StackProps, Stage } from 'aws-cdk-lib'; import * as codecommit from 'aws-cdk-lib/aws-codecommit'; import { CodePipeline, CodePipelineSource } from 'aws-cdk-lib/pipelines'; import * as pipelines from 'aws-cdk-lib/pipelines'; import { Construct } from 'constructs'; import { VpcStack } from './vpc-stack'; import { Cluster } from 'aws-cdk-lib/aws-eks/lib/cluster'; import { DevOpsClusterStack } from '../lib/devops-cluster-stack'; class DevelopmentStage extends Stage { cluster: Cluster; constructor(scope: Construct, id: string, props: StackProps) { super(scope, id, props); const vpcStack = new VpcStack(this, "VpcStack", {}); const ClusterStack = new DevOpsClusterStack (this, 'DevOpsCluster',{vpc:vpcStack.vpc , cluster:this.cluster}); } } /** * Create a CI/CD pipelines for cluster deployment */ export class PipelineStack extends Stack { cluster: Cluster; static cluster: Cluster; constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); /** * Here we provide pipeline start point as a Codecommit Soursecode to Create a CI/CD pipelines for cluster deployment */ const repository = codecommit.Repository.fromRepositoryName(this, 'Repository', 'CDK-Typescript-Project'); const source = CodePipelineSource.codeCommit(repository, "feature/create-eks-cluster") const pipeline = new CodePipeline(this, 'Pipeline', { pipelineName: 'EKS-CICD-Pipeline', synth: new pipelines.ShellStep('Synth', { input: source, installCommands: ['npm i -g npm@latest',"npm install -g typescript"], commands: [ 'npm ci', 'npm run build', 'npx cdk synth', ] }) }); // Developemnt stage This could include things like EC2 instances and more, depending on the needs of the application being developed. const devStage = new DevelopmentStage(this, "Development", { }); pipeline.addStage(devStage); } } Also I have Created Separate VPC Stack import { App, Stack, StackProps } from "aws-cdk-lib"; import * as ec2 from 'aws-cdk-lib/aws-ec2'; import { IpAddresses } from "aws-cdk-lib/aws-ec2"; import { Construct } from "constructs"; /** * Create a VPC with one Public and one Private Subnet */ export class VpcStack extends Stack { public readonly vpc: ec2.Vpc; constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); const vpc = new ec2.Vpc(this, 'vpc', { natGateways: 1, ipAddresses: IpAddresses.cidr("10.1.0.0/16"), subnetConfiguration: [ { name: 'Public', subnetType: ec2.SubnetType.PUBLIC, }, { name: 'Private', subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS, } ], maxAzs: 2 }); this.vpc = vpc; } } /*I am receiving following error while deploying the Cluster Stack*/ ERROR is like: instance Fails to Join Kubernetes Cluster DevOpsClusterNodegroupDefaultCapacity90B6204B CREATE_FAILED Resource handler returned message: "[Issue(Code=NodeCreationFailure, Message=Instances failed to join the kubernetes cluster, ResourceIds=[i-02c060ccb6d6e8c6f, i-048feaa20bfdca377, i-0a7a4184599e60cd2])] (Service: null, Status Code: 0, Request ID: null)" (RequestToken: e94890a6-5074-b4a3-a4e3-916cf510ef8a, HandlerErrorCode: GeneralServiceException)
- I have some CDK constructs as Python packages built and published to CodeArtifact repository. Now I want to reuse these packages on my CDK app with CDK Pipeline. My code is this ```python pipeline = CodePipeline( self, "Pipeline", pipeline_name="MyApp", synth=ShellStep( "Synth", input=CodePipelineSource.connection(...), commands=[ "pip3 install awscli --upgrade --user", "aws codeartifact login --tool pip --repository my-repo --domain my-domain --domain-owner 123456789012 --region us-east-1", "pip install -r requirements.txt", "npm install -g aws-cdk", "cdk synth", ], ), ) ``` But I am getting de following error: ``` An error occurred (AccessDeniedException) when calling the GetAuthorizationToken operation: User: arn:aws:sts::123456789012:assumed-role/MyAppPipelineStack-PipelineBuildSynthCdkBuildPr-OC8QO3ENNGDV/AWSCodeBuild-8cb5d5ee-c307-4742-bed6-51b0a0c36c48 is not authorized to perform: codeartifact:GetAuthorizationToken on resource: arn:aws:codeartifact:us-east-1:123456789012:domain/my-domain because no identity-based policy allows the codeartifact:GetAuthorizationToken action ``` I understand that this Roles don't have permissions to get this CodeArtifact repository, however I don't know how to setup CodePipeline. Does anyone know how to do it? Is there any tutorial that explains how to use private CDK packages in the CDK Pipeline build process?
- I split my stack into two pieces so I can have other developers work on the implementation of the apigatewayv2 routes, integrations, and lambdas. I am trying to figure out how to reference the API Gateway. I thought I had it figured out: ``` HttpApi.fromHttpApiAttributes(stack, "my-api-gateway-id", { httpApiId: "something" } ); ``` but that returns an IHttpApi which doesn't have .addRoutes(). I tried casting it to HttpApi but that didn't work - it really doesn't have .addRoutes(). Not sure what to do. How do I get an HttpApi rather than an IHttpApi? Casting didn't work.
Popular users
see all1/18
skinsman
EXPERTGreg_B
EXPERTalatech
EXPERTMichaelDombrowski-AWS
EXPERTRanjith
MODERATOR