Finding Canonical ID of the account using CDK

1k views Asked by At

I'm writing a custom S3 bucket policy using AWS that requires canonical ID of the account as a key parameter. I can get the account ID programmatically using cdk core. You may refer the python sample below.

cid = core.Aws.ACCOUNT_ID

Is there any way that we can get the same for canonical-ID.

Update:

I've found a workaround using S3API call. I've added the following code in my CDK stack. May be helpful to someone.

def find_canonical_id(self):
   s3_client = boto3.client('s3')
   return s3_client.list_buckets()['Owner']['ID']
1

There are 1 answers

0
DilLip_Chowdary On

I found 2 ways to get the canonical ID (boto3):

Method-1 Through List bucket API (also mentioned by author in the update)

This method is recommended by AWS as well.

import boto3

client = boto3.client("s3")

response = client.list_buckets()

canonical_id = response["Owner"]["ID"]

Method-2 Through Get bucket ACL API

import boto3

client = boto3.client("s3")

response = client.get_bucket_acl(
    Bucket='sample-bucket' # should be in your acct
)

canonical_id = response["Owner"]["ID"]