Tips

Describe instances (source)

1
2
3
4
5
  export BASTION_INSTANCE_ID=$(aws ec2 describe-instances \
                          --region=$AWS_REGION \
                          --filter "Name=tag:Name,Values=my-bastion" \
                          --query "Reservations[].Instances[?State.Name == 'running'].InstanceId[]" \
                          --output text)

tail-stack-events

Watch AWS/CloudFormation events on the CLI using tail-stack-events.

1
tail-stack-events -f -s <stack name>

Snippets

Load environment based configuration file

In app.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Load configuration file
env = app.node.try_get_context("env")
with open(f"config.{env}.yaml", "r") as cfg:
    try:
        config = yaml.safe_load(cfg)
    except yaml.YAMLError as exc:
        print(exc)

# Create stack
Stack(
    app,
    "stack-name",
    cdk.Environment(account=config["aws"]["account"], region=config["aws"]["region"]),
    config=config
)

Then on the CLI you can use:

1
$ cdk deploy -c env=prod

And this will load config from config.prod.yaml.

The stack itself can be defined as:

1
2
3
4
5
6
7
8
class CDKStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, env, **kwargs) -> None:
        # Save config
        self.config = kwargs.pop("config")

        super().__init__(scope, construct_id, **kwargs)

        ...

Override logical IDs

1
2
cfn_assignment = sso.CfnAssignment(...)
cfn_assignment.override_logical_id(unique_id)

Add conditions

In this example add conditions to S3 bucket policies:

1
2
3
4
5
6
7
8
listBucketPolicy = aws_iam.PolicyStatement(
    actions=[
        "s3:ListBucket",
    ],
    resources=["arn:aws:s3:::my-bucket"],
)
listBucketPolicy.add_condition("StringEquals", {"s3:prefix": ["prod"], "s3:delimiter": ["/"]})
bucket.policy.document.add_statements(listBucketPolicy)

Also check:

Resources

Articles

Testing

Docs