How to get the account id with cdk

Bil*_*ill 3 typescript aws-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);
Run Code Online (Sandbox Code Playgroud)

But get below output

$ tsc index.ts 
$ node index.js 
${Token[AWS::AccountId.0]}
Run Code Online (Sandbox Code Playgroud)

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

Run Code Online (Sandbox Code Playgroud)

Rob*_*sch 6

直到我意识到,直到您运行cdk deploy,才存在完全相同的问题,只有这样的值,只有占位符(如${Token[AWS::AccountId.0]})会在部署期间填写。

这样想,您的CDK堆栈是创建大量资源的计划,但是直到您运行cdk deploy,这些资源才不存在,因此无法查询其值。

获得所需值的一种方法是将其添加到堆栈构造函数中:

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

如:

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
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

运行时cdk deploy,将输出:

MyStack.StackAccount = 987XXXXXX456
Run Code Online (Sandbox Code Playgroud)