{"id":15899062,"url":"https://github.com/neilkuan/cdk-sample-save","last_synced_at":"2025-03-20T17:30:41.871Z","repository":{"id":42437386,"uuid":"284852185","full_name":"neilkuan/cdk-sample-save","owner":"neilkuan","description":"Save some AWS CDK example ","archived":false,"fork":false,"pushed_at":"2025-03-17T00:17:26.000Z","size":5655,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-20T05:13:53.833Z","etag":null,"topics":["aws","aws-cdk","python","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/neilkuan.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"ko_fi":"neilkuan"}},"created_at":"2020-08-04T02:01:35.000Z","updated_at":"2025-03-17T00:16:53.000Z","dependencies_parsed_at":"2023-09-25T04:50:48.209Z","dependency_job_id":"4507f820-3761-4888-92fa-6f2f181efe75","html_url":"https://github.com/neilkuan/cdk-sample-save","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neilkuan%2Fcdk-sample-save","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neilkuan%2Fcdk-sample-save/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neilkuan%2Fcdk-sample-save/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neilkuan%2Fcdk-sample-save/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/neilkuan","download_url":"https://codeload.github.com/neilkuan/cdk-sample-save/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244660130,"owners_count":20489295,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws","aws-cdk","python","typescript"],"created_at":"2024-10-06T10:10:46.556Z","updated_at":"2025-03-20T17:30:41.400Z","avatar_url":"https://github.com/neilkuan.png","language":"TypeScript","funding_links":["https://ko-fi.com/neilkuan"],"categories":[],"sub_categories":[],"readme":"# cdk-sample-save\n\n\n\n- tips: create custom cidrblock subnet .\n```typescript\nimport * as cdk from '@aws-cdk/core';\nimport * as ec2 from '@aws-cdk/aws-ec2';\n\nexport class FargetMultipleStackStack extends cdk.Stack {\n  readonly vpc: ec2.IVpc;\n  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {\n    super(scope, id, props);\n    // create custom cidrblock subnet .\n    const iGWId = 'igw-xxxxxx'\n    const defaultVpc = ec2.Vpc.fromLookup(this , 'testDf',{\n      isDefault: true\n    });\n\n    const defaultpubS = new ec2.PublicSubnet(this,'testPub',{\n      vpcId: defaultVpc.vpcId,\n      availabilityZone: `${this.region}a`,\n      cidrBlock: '172.31.48.0/20',\n      mapPublicIpOnLaunch: true,\n\n    });\n    const att = new ec2.CfnVPCGatewayAttachment(this, 'VPCGW', {\n      internetGatewayId: `${iGWId}`,\n      vpcId: defaultVpc.vpcId,\n    });\n    defaultpubS.addDefaultInternetRoute(\n      `${iGWId}`, att\n    )\n    att.node.addDependency(defaultpubS)\n  }\n}\n\n```\n\n### Find Centos 7 ami\n```typescript\nec2.MachineImage.lookup({\n      name: '*CentOS-7*',\n      owners: ['679593333241'],\n    });.getImage(this).imageId;\n```\n### Find Centos 8 ami\n```typescript\nec2.MachineImage.lookup({\n      name: '*CentOS-8*',\n      owners: ['679593333241'],\n    });.getImage(this).imageId;\n```\n\n\n### Find Ubuntu ami\n```typescript\nec2.MachineImage.lookup({\n       //name: '*ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server*',\n        name: '*ubuntu-bionic-18.04-amd64-*',\n        owners: ['099720109477'],\n        filters: {\n          ['root-device-type']: ['ebs'],\n        },\n      }).getImage(this).imageId\n```\n\n\n### How to use `CfnKeyPair` and download.\n```ts\nconst key = new CfnKeyPair(this, 'Mykey', {\n      keyName: 'labcdk',\n    });\n    \nnew CfnOutput(this, 'key', {\n      value: `aws ssm get-parameter --name /ec2/keypair/${key.getAtt('KeyPairId')} --region ${this.region} --with-decryption --query 'Parameter.\"Value\"' --output text \u003e ${key.keyName}.pem`,\n    });\n```\n\n### In Case lookup `dummy-value` back.\nissue link:\n[21520](https://github.com/aws/aws-cdk/pull/21520)\n[8699](https://github.com/aws/aws-cdk/issues/8699#issuecomment-976159825)\n[aws-docs](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ssm-readme.html#lookup-existing-parameters)\n```ts\nlet roleArnValue\nlet roleArn = ssm.StringParameter.valueFromLookup(this, \"/param/testRoleArn\");\nif (roleArn.includes('dummy-value')) {\n  roleArnValue = 'arn:aws:service:eu-central-1:123456789012:entity/dummy-value';\n} else {\n  roleArnValue = roleArn\n}\nconst role = iam.Role.fromRoleArn(this, \"role\", roleArnValue);\n\n\n//or\n\nconst roleArn = ssm.StringParameter.valueFromLookup(this, \"/param/testRoleArn\");\n// use Lazy function let cdk app lookup back later.\nconst role = iam.Role.fromRoleArn(this, \"role\", cdk.Lazy.string({ produce: () =\u003e roleArn }));\n\n```\n\n\n### Select vpcSubnet when new `aws_eks.Cluster` error\n- Case:\n```ts\nexport class MyStack extends Stack {\n  vpc: aws_ec2.IVpc;\n  constructor(scope: Construct, id: string, props: MyStackProps) {\n    super(scope, id, props);\n\n    this.vpc = aws_ec2.Vpc.fromLookup(this, 'lookup', {\n      vpcId: props.vpcId,\n    });\n\n    new aws_eks.Cluster(this, 'Cluster', {\n      vpc: this.vpc,\n      version: aws_eks.KubernetesVersion.V1_21,\n      vpcSubnets: [{ subnetGroupName: 'PrivateA' }, { subnetGroupName: 'Public' }],\n      endpointAccess: aws_eks.EndpointAccess.PUBLIC_AND_PRIVATE.onlyFrom('1.2.3.4/32'),\n    });\n  }\n}\n```\nerror message:\n```ts\nVpc must contain private subnets when public endpoint access is restricted\n```\n- vpc.lookup() looks for vpc and stores it in cdk.context.json, before select subnet, new eks.Cluster() is assigned dummy vpc in advance...\n\n\n- Solution: [iussue](https://github.com/aws/aws-cdk/issues/19425)\n```ts\nexport class MyStack extends Stack {\n  vpc: aws_ec2.IVpc;\n  constructor(scope: Construct, id: string, props: MyStackProps) {\n    super(scope, id, props);\n\n    this.vpc = aws_ec2.Vpc.fromLookup(this, 'lookup', {\n      vpcId: props.vpcId,\n    });\n\n    if (this.vpc.vpcId === 'vpc-12345') {\n    // if get Dummy Vpc, find again...\n      this.vpc = aws_ec2.Vpc.fromLookup(this, 'lookup2', {\n        vpcId: props.vpcId,\n      });\n    }\n    // if get Dummy Vpc, will not new Cluster class...\n    if (this.vpc.vpcId !== 'vpc-12345') {\n      new aws_eks.Cluster(this, 'Cluster', {\n        vpc: this.vpc,\n        version: aws_eks.KubernetesVersion.V1_21,\n        vpcSubnets: [{ subnetGroupName: 'PrivateA' }, { subnetGroupName: 'Public' }],\n        endpointAccess: aws_eks.EndpointAccess.PUBLIC_AND_PRIVATE.onlyFrom('1.2.3.4/32'),\n      });\n    }\n  }\n}\n```\n\n#### Find new VPC NatGateway eip address \n```ts\nconst vpc = new ec2.Vpc(this, 'Vpc', {\n      vpcName: 'HttpApiVpc',\n      natGateways: 1,\n      subnetConfiguration: [\n        {\n          name: 'PublicSubnet',\n          subnetType: ec2.SubnetType.PUBLIC,\n        },\n        {\n          name: 'PrivateNatSubnet',\n          subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,\n        },\n      ],\n      maxAzs: 3,\n      enableDnsHostnames: true,\n      enableDnsSupport: true,\n    });\nvpc.publicSubnets.forEach((publicSubnet, index) =\u003e {\n    const eip = publicSubnet.node.children.find(c =\u003e (c as CfnResource).cfnResourceType === 'AWS::EC2::EIP') as ec2.CfnEIP;\n    if (eip) {\n      new CfnOutput(this, `eip${index}`, {\n          value: `${eip.ref}`,\n     });\n    }\n});\n```\n\n\n\n### ECS RUN Task IN Tail do not thing.\n```ts\n const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef');\n    \nfargateTaskDefinition.addContainer(\n      'Container',\n      {\n        containerName: 'nginx',\n        image: ecs.ContainerImage.fromRegistry('nginx'),\n        entryPoint: [''],\n        command: ['tail', '-f', '/dev/null'],\n      },\n    );\n```\n\n### ECS Service dependency Capacity Provider Aspect\n```ts\nimport {\n  aws_ecs,\n  IAspect,\n  Aspects,\n} from 'aws-cdk-lib';\nimport { IConstruct } from 'constructs';\n\n/**\n * Add a dependency from capacity provider association to the cluster\n * and from each service to the capacity provider association.\n */\nclass CapacityProviderDependencyAspect implements IAspect {\n  public visit(node: IConstruct): void {\n    if (node instanceof aws_ecs.FargateService) {\n      const children = node.cluster.node.findAll();\n      for (const child of children) {\n        if (child instanceof aws_ecs.CfnClusterCapacityProviderAssociations) {\n          child.node.addDependency(node.cluster);\n          node.node.addDependency(child);\n        }\n      }\n    }\n  }\n}\n\n\nAspects.of(this).add(new CapacityProviderDependencyAspect());\n```\n\n### Slack Approval Bot Action on Codepipeline\n```ts\nimport { ActionCategory, CommonActionProps, IStage, ActionBindOptions, ActionConfig } from '@aws-cdk/aws-codepipeline';\nimport { Action } from '@aws-cdk/aws-codepipeline-actions';\nimport { ITopic } from '@aws-cdk/aws-sns';\nimport { Construct } from '@aws-cdk/core';\n\nexport interface SlackApprovalActionProps extends CommonActionProps {\n  readonly additionalInformation?: string;\n  readonly externalEntityLink?: string;\n  /**\n   * for codepipeline send approval event\n   */\n  readonly topic: ITopic;\n}\n\n/**\n * idea from\n * see: https://github.com/cloudcomponents/cdk-constructs/blob/master/packages/cdk-codepipeline-slack\n */\nexport class SlackApprovalAction extends Action {\n  public constructor(private props: SlackApprovalActionProps) {\n    super({\n      ...props,\n      category: ActionCategory.APPROVAL,\n      provider: 'Manual',\n      artifactBounds: {\n        minInputs: 0,\n        maxInputs: 0,\n        minOutputs: 0,\n        maxOutputs: 0,\n      },\n    });\n\n    this.props = props;\n  }\n\n  protected bound(scope: Construct, stage: IStage, options: ActionBindOptions): ActionConfig {\n    const topic = this.props.topic;\n    topic.grantPublish(options.role);\n\n    return {\n      configuration: {\n        NotificationArn: topic.topicArn,\n        CustomData: this.props.additionalInformation,\n        ExternalEntityLink: this.props.externalEntityLink,\n      },\n    };\n  }\n}\n\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fneilkuan%2Fcdk-sample-save","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fneilkuan%2Fcdk-sample-save","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fneilkuan%2Fcdk-sample-save/lists"}