louie anderson
louie anderson

Reputation: 43

Accessing CDK Stack Resources

When creating a basic s3 resource with the following code

export class Test1Stack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
    new s3.Bucket(this, 'sampleBucket', {
      versioned: true,
      removalPolicy: cdk.RemovalPolicy.DESTROY,
      autoDeleteObjects: true
    });
  }
}

Cdk creates the following resources:

I can access AWS::S3::Bucket AWS::S3::BucketPolicy properties by using

const s3 = new s3.Bucket(.......)

What object would give me access to the rest of the resources, for example if I'd like to overwrite the logical id for AWS::IAM::Role.

I imagine that I could create my own AWS::IAM::Role, AWS::Lambda::Function, AWS::CDK::Metadata and in this way I could use the same mechanism I am using for s3 to manipulate & override properties, but it is not what I am looking for.

I just want to be able to access the other resources at run time.

I have tried the properties from the constructor with no success.

I also understand that CDK does not recommend overriding resources.

Upvotes: 2

Views: 2145

Answers (1)

miensol
miensol

Reputation: 41608

You can access the bucket policy, assuming it got auto-created, and change its logical id like so:

const policy = bucket.policy!;
(policy.node.defaultChild as CfnBucketPolicy).overrideLogicalId("MyBucketPolicy")

As for the IAM Role related to autoDeleteObjects it is also possible but a little bit more brittle. There's a custom resource provider mini-framework used. This means that the labmda is shared between all Buckets in a given stack that use autoDeleteObjects.

Still, it is possible to get a hold of the lambda itself like so:

const provider = this.node.findChild('Custom::S3AutoDeleteObjectsCustomResourceProvider') as CustomResourceProvider
const lambda = provider.node.findChild('Handler') as CfnResource

Upvotes: 2

Related Questions