3

How can one get the region name in AWS CDK?

Some SDKs provide Region objects (see also this question)

Inside a CDK construct, self.region is available, and cdk.aws_region has a RegionInfo class, but it doesn't provide the name, eg: ap-southeast-1 -> Singapore

gshpychka
  • 8,523
  • 1
  • 11
  • 31
Efren
  • 4,003
  • 4
  • 33
  • 75
  • If it was available in CDK I think you'd find it in https://github.com/aws/aws-cdk/blob/master/packages/%40aws-cdk/region-info/lib/aws-entities.ts - it's not there right now but it looks to be a fairly simple addition – Elliveny May 17 '22 at 04:51

1 Answers1

4

AWS exposes region long names (like Asia Pacific (Singapore) for ap-southeast-1) as publicly available Parameter Store parameters. Lookup this value at synth-time with ssm.StringParameter.valueFromLookup*. You need the region id for the parameter path, which a stack (or construct) can introspect.

export class MyStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props: cdk.StackProps) {
    super(scope, id, props);

    const regionLongName: string = ssm.StringParameter.valueFromLookup(
      this,
      `/aws/service/global-infrastructure/regions/${this.region}/longName`
    );

    console.dir({ region: this.region, regionLongName });
  }
}

For Python

aws_cdk.aws_ssm.StringParameter.value_from_lookup(
            scope=self,
            parameter_name=f'/aws/service/global-infrastructure/regions/{self.region}/longName')

cdk synth output::

{ region: 'us-east-1', regionLongName: 'US East (N. Virginia)' }

* The CDK's valueFromLookup context method will cache the looked-up parameter store value in cdk.context.json at synth-time. You may initially get a dummy value. Just synth again.

Efren
  • 4,003
  • 4
  • 33
  • 75
fedonev
  • 20,327
  • 2
  • 25
  • 34