我用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
在这里是什么意思?如何获取真实帐户ID?
$ 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
答案 0 :(得分: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
});
如:
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