Skip to content

Instantly share code, notes, and snippets.

@amcginlay
Last active February 2, 2022 14:27
Show Gist options
  • Save amcginlay/85fe85a7a14288f86fac530ca31e7075 to your computer and use it in GitHub Desktop.
Save amcginlay/85fe85a7a14288f86fac530ca31e7075 to your computer and use it in GitHub Desktop.
CDK Java MVP
#!/bin/bash
# --------------------------------
# from standard Cloud9 environment
# --------------------------------
which aws cdk
pip install botocore boto3 # required to run python script for emptying versioned buckets (see later)
npm install --force -g aws-cdk # upgrade
cdk doctor # status check
# install maven
sudo wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo
sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo
sudo yum install -y apache-maven
mkdir ~/environment/cdk-app && cd $_
cdk init --language java
cdk bootstrap # apply baseline CDK stack
# replace the sample stack class with a simple one to create an SNS topic named "BuiltWithCDK" (standard CFN MVP)
cat > ~/environment/cdk-app/src/main/java/com/myorg/CdkAppStack.java << EOF
package com.myorg;
import software.constructs.Construct;
import software.amazon.awscdk.Stack;
import software.amazon.awscdk.StackProps;
import software.amazon.awscdk.services.sns.Topic;
public class CdkAppStack extends Stack {
public CdkAppStack(final Construct scope, final String id) {
this(scope, id, null);
}
public CdkAppStack(final Construct scope, final String id, final StackProps props) {
super(scope, id, props);
final Topic topic = Topic.Builder.create(this, "BuiltWithCDK")
//.displayName("BuiltWithCDK")
.build();
}
}
EOF
mvn package # compile and run tests (not technically required to deploy)
cdk synth # emits the synthesized CloudFormation template
cdk deploy # deploy this stack (CdkAppStack) to your default AWS account/region
cdk ls
# ----------------------
# uncomment the ".displayName()" command (line 13) in CdkAppStack.java and save the file
cdk diff # compare deployed stack with current state
cdk deploy # create and apply a CloudFormation ChangeSet
# ----------------------
cdk destroy CdkAppStack # delete your stack
# done with CDK?
aws cloudformation delete-stack --stack-name CDKToolkit
export BUCKET=$(aws s3 ls | awk '{print $3}' | grep "^cdk-")
# python script for emptying versioned buckets
python - << EOF
import os, boto3
boto3.resource('s3').Bucket(os.getenv('BUCKET')).object_versions.delete()
EOF
# dispose of empty bucket
aws s3 rb s3://${BUCKET}
# NOTE: "cdk bootstrap" creates a versioned bucket which can be a be a little "sticky" during deletion/recreation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment