Cannot retrieve value from context provider ssm since account/region are not specified at the stack level. Configure “env” with an account and region when you define your stack.

状況

CDKでSSMパラメータストアを参照したとき

vpc-stack.ts

...
export class VpcStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
    ...
    console.log(ssm.StringParameter.valueFromLookup(this, '/cdk/vpcid'));
    ...

エラー全文

/opt/github/cdk/node_modules/aws-cdk-lib/core/lib/context-provider.js:2
This usually happens when one or more of the provider props have unresolved tokens`);const propStrings=propsToArray(props);return{key:`${options.provider}:${propStrings.join(":")}`,props}}static getValue(scope,options){try{jsiiDeprecationWarnings.aws_cdk_lib_GetContextValueOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.getValue),error}const stack=stack_1.Stack.of(scope);if(token_1.Token.isUnresolved(stack.account)||token_1.Token.isUnresolved(stack.region))throw new Error(`Cannot retrieve value from context provider ${options.provider} since account/region are not specified at the stack level. Configure "env" with an account and region when you define your stack.See https:/docs.aws.amazon.com/cdk/latest/guide/environments.html for more details.`);const{key,props}=this.getKey(scope,options),value=constructs_1.Node.of(scope).tryGetContext(key),providerError=extractProviderError(value);return value===void 0||providerError!==void 0?(stack.reportMissingContextKey({key,provider:options.provider,props}),providerError!==void 0&&annotations_1.Annotations.of(scope).addError(providerError),{value:options.dummyValue}):{value}}constructor(){}}exports.ContextProvider=ContextProvider,_a=JSII_RTTI_SYMBOL_1,ContextProvider[_a]={fqn:"aws-cdk-lib.ContextProvider",version:"2.95.1"};function extractProviderError(value){if(typeof value=="object"&&value!==null)return value[cxapi.PROVIDER_ERROR_KEY]}function colonQuote(xs){return xs.replace("$","$$").replace(":","$:")}function propsToArray(props,keyPrefix=""){const ret=[];for(const key of Object.keys(props))if(props[key]!==void 0)switch(typeof props[key]){case"object":{ret.push(...propsToArray(props[key],`${keyPrefix}${key}.`));break}case"string":{ret.push(`${keyPrefix}${key}=${colonQuote(props[key])}`);break}default:{ret.push(`${keyPrefix}${key}=${JSON.stringify(props[key])}`);break}}return ret.sort(),ret}



                                                                ^
Error: Cannot retrieve value from context provider ssm since account/region are not specified at the stack level. Configure "env" with an account and region when you define your stack.See https:/docs.aws.amazon.com/cdk/latest/guide/environments.html for more details.
    at Function.getValue (/opt/github/cdk/node_modules/aws-cdk-lib/core/lib/context-provider.js:2:554)
    at Function.valueFromLookup (/opt/github/cdk/node_modules/aws-cdk-lib/aws-ssm/lib/parameter.js:1:5510)
    at new VpcStack (/opt/github/cdk/lib/resource/vpc-stack.ts:67:37)
    at new CdkStack (/opt/github/cdk/lib/cdk-stack.ts:9:22)
    at Object.<anonymous> (/opt/github/cdk/bin/cdk.ts:5:1)
    at Module._compile (node:internal/modules/cjs/loader:1233:14)
    at Module.m._compile (/opt/github/cdk/node_modules/ts-node/src/index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1287:10)
    at Object.require.extensions.<computed> [as .ts] (/opt/github/cdk/node_modules/ts-node/src/index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:1091:32)

原因

ssm.StringParameter.valueFromLookup()を利用するスタックにenvを渡す必要がある

対処

valueFromLookup()を利用するVpcStackの呼び出し元、CdkStackでVpcStackにenvを渡す

cdk-stack.ts

...
    const vpcStack = new VpcStack(this, 'VpcStack', {
      env: {
          account: '644384150803',
          region: 'ap-northeast-1',
        }});
...

補足

上記以外の箇所でenvを渡しても無効だった

  • (最上位の)App(cdk.ts)からCdkStackを呼び出すときに渡す
  • valueFromLookup()を実際に実行するVpcStack自身でenvを設定する(valueFromLookup()の手前にenvを設定する)