如何使用cdk获取账户id

How to get the account id with cdk

我用 AWS CDK 写了一个简单的打字稿并尝试获取帐户 ID

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

const app = new cdk.Stack();

console.log(app.account);

但低于输出

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

那么这里的Token是什么意思呢?如何获取真实账号?

更新

$ 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

我遇到了完全相同的问题,直到我意识到,在您 运行 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
});

如:

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
    });
  }
}

当你 运行 cdk deploy 时,将输出:

MyStack.StackAccount = 987XXXXXX456