こんにちは、CX事業本部 Delivery部の若槻です。
AWS CDKでAWS Systems Manager Parameter Storeを構築する際に、パラメータ値(stringValue
プロパティ)の指定が必須となります。
https://github.com/aws/aws-cdk/blob/v1.192.0/packages/@aws-cdk/aws-ssm/lib/parameter.ts#L128
/**
* Properties needed to create a String SSM parameter.
*/
export interface StringParameterProps extends ParameterOptions {
/**
* The value of the parameter. It may not reference another parameter and ``{{}}`` cannot be used in the value.
*/
readonly stringValue: string;
/**
* The type of the string parameter
*
* @default ParameterType.STRING
*/
readonly type?: ParameterType;
/**
* The data type of the parameter, such as `text` or `aws:ec2:image`.
*
* @default ParameterDataType.TEXT
*/
readonly dataType?: ParameterDataType;
}
この仕様はCDK(CloudFormation)以外からパラメータ値を変更しない場合は問題ありませんが、ユーザーや別のシステムに変更可能とさせたいユースケースでは、スタックデプロイ時に意図せぬ値の上書きが発生する可能性があるため、CDKの管理外とする必要があります。
しかし、CDK外で管理している既存のParameterStoreを、CDKスタック内でConstructとして使いたい場合があります。例えばLambda関数にParameterStoreのアクセス権限をgrantRead
やgrantWrite
で付与したい場合などです。
そんな時はStringParameter.fromStringParameterName()
を使います。第3引数に取得したParameterStore名を指定します。
やってみた
実際に試してみます。
既存のParameterStorehoge
がCDK外で別途作成されている場合。
aws ssm put-parameter \
--name "hoge" \
--value "fuga" \
--type String
次のようにStringParameter.fromStringParameterName()
でのParameterStorehoge
のConstructを取得できます。
lib/cdk-sample-app.ts
import { Construct } from 'constructs';
import { Stack, StackProps, aws_lambda_nodejs, aws_ssm } from 'aws-cdk-lib';
export class CdkSampleStack extends Stack {
constructor(scope: Construct, id: string, props: StackProps) {
super(scope, id, props);
const hogeParameter = aws_ssm.StringParameter.fromStringParameterName(
this,
'hogeParameter',
'hoge'
);
const nyaoFunc = new aws_lambda_nodejs.NodejsFunction(this, 'nyaoFunc');
hogeParameter.grantRead(nyaoFunc);
}
}
便利!
SecureStringも取得できる
SecureString ParameterのConstructはfromSecureStringParameterAttributes
を使用すれば取得できます。
const secureStringParameter = ssm.StringParameter.fromSecureStringParameterAttributes(this, 'MySecureValue', {
parameterName: '/My/Secret/Parameter',
version: 5,
});
AWSサービスのリソースはfrom*ArnでConstructを取得できる
実は次のエントリにある通り、ほとんどのAWSサービスのリソースはfrom*Arn
というメソッドでConstructを取得できるようになっています。
ParameterStoreについては例外的にfromStringParameterName()
となっているようです。
参考
以上