Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the account id with cdk

I wrote a simple typescript with AWS CDK and try to get the account id

import cdk = require("@aws-cdk/core");

const app = new cdk.Stack();

console.log(app.account);

But get below output

$ tsc index.ts 
$ node index.js 
${Token[AWS::AccountId.0]}

So what's the meaning of Token here? How to get the real account id?

Updates

$ cdk init app --language=typescript

# replace lib/<name>-stack.ts with @Rob Raisch 's code

$ cdk synth
${Token[AWS::AccountId.0]}
Outputs:
  MyStackAccount:
    Description: Account of this stack
    Value:
      Ref: AWS::AccountId
Resources:
  CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
      Modules: aws-cdk=1.2.0,@aws-cdk/core=1.8.0,@aws-cdk/cx-api=1.8.0,jsii-runtime=node.js/v10.15.3

$ cdk deploy
${Token[AWS::AccountId.0]}
MyStack: deploying...
MyStack: creating CloudFormation changeset...
 0/2 | 11:58:59 AM | CREATE_IN_PROGRESS   | AWS::CDK::Metadata | CDKMetadata Resource creation Initiated
 1/2 | 11:58:59 AM | CREATE_COMPLETE      | AWS::CDK::Metadata | CDKMetadata 
 2/2 | 11:59:00 AM | CREATE_COMPLETE      | AWS::CloudFormation::Stack | MyStack 

 ✅  MyStack

Outputs:
MyStack.MyStackAccount = 123456789012

like image 500
Bill Avatar asked Sep 13 '19 01:09

Bill


1 Answers

I had exactly the same issue until I realized that, until you run cdk deploy, there are no such values, only placeholders (like ${Token[AWS::AccountId.0]}) that will be filled in during deployment.

Think of it this way, your CDK stack is a plan to create a number of resources, but until you run cdk deploy, those resources do not exist and so, cannot be queried for their values.

One way to get the value you need would be to add this to your stack constructor:

// Publish the custom resource output
new cdk.CfnOutput(this, "MyStackAccount", {
  description: "Account of this stack",
  value: this.account
});

As in:

class MyStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, "MyStack", props);

    new cdk.CfnOutput(this, "MyStackAccount", {
      description: "Account of this stack",
      value: this.account
    });
  }
}

which, when you run cdk deploy, will output:

MyStack.StackAccount = 987XXXXXX456
like image 179
Rob Raisch Avatar answered Oct 02 '22 19:10

Rob Raisch