aws-cdkでvpc.fromLookupが動作しない
やりたかったこと
構築済みのVPC IDを指定して、その中に各種AWSリソースを作成したかったのだが、うまくいかず。
以下のエラーが出力される。
Cannot retrieve value from context provider vpc-provider since account/region are not specified at the stack level. Either configure "env" with explicit account and region when you define your stack, or use the environment variables "CDK_DEFAULT_ACCOUNT" and "CDK_DEFAULT_REGION" to inherit environment information from the CLI (not recommended for production stacks) Subprocess exited with error 1 Error: Subprocess exited with error 1 at ChildProcess.<anonymous> (/usr/local/lib/node_modules/aws-cdk/lib/api/cxapp/exec.ts:115:23) at ChildProcess.emit (events.js:321:20) at ChildProcess.EventEmitter.emit (domain.js:485:12)
ちなみに --profile XXX
を指定してAWS Profileをして実行している状況。
Stackのコードは以下の通り
interface AuroraStackProps extends StackProps { dbSg: ISecurityGroup } export class DbAuroraStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props: AuroraStackProps) { super(scope, id, props); const stage: string = this.node.tryGetContext("stage"); const vpcId: string = this.node.tryGetContext("vpcId"); // contextからvpcIdを渡す想定 const vpc: IVpc = Vpc.fromLookup(this, "myVpc", {vpcId: vpcId}); const cluster = new DatabaseCluster(this, "aurora-db", { engine: DatabaseClusterEngine.AURORA_POSTGRESQL, removalPolicy: RemovalPolicy.DESTROY, masterUser: { username: "admin" }, instanceProps: { // TODO: ここもパラメータ化した方が良い? instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.SMALL), vpcSubnets: { subnetType: ec2.SubnetType.ISOLATED }, vpc: vpc, securityGroup: props.dbSg } }); cluster.node.applyAspect(new Tag("Name", `aurora-${stage}-db`)) } }
今回問題になっているのは Vpc.fromLookup(this, "myVpc", {vpcId: vpcId});
この部分
Issue
Repository に Issue があった。
This is the expected behavior >= 0.36.0. We wanted to reduce the implicit effect the user's environment has on the synthesis result as this can cause production risks, so we made this explicit.
意図的にこの動作を禁止しているっぽい。エラーメッセージにもあるように、Productionでは推奨しないが開発目的でなら回避方法はあるとのこと。
env
でPropsに打ち込んでやれば良いらしい。
new HogeStack(app, "HogeHogeStack", { env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION, } });
これでひとまずエラーはなくなった(が、Productionはこれではダメなので考えないとダメ)
追記
どうやらエラーメッセージが間違っているらしいというのを社内のCDKマスターから教えてもらった。
やり方としては間違っていなかったらしいので、ひとまず良さそう。