Get AWS pseudo parameter using AWS CDK
Sometimes, we need to get the following properties. AWS Account ID Stack Notification ARNs Cloudfromation Stac […]
広告ここから
広告ここまで
目次
Sometimes, we need to get the following properties.
- AWS Account ID
- Stack Notification ARNs
- Cloudfromation Stack Name
- etc…
These properties are named Pseudo Parameters
in AWS CloudFormation.
How to get Pseudo parameters in AWS CDK
In AWS CDK, we can get these parameters using ScopedAws
class.
Accessor for scoped pseudo parameters.
These pseudo parameters are anchored to a stack somewhere in the construct tree, and their values will be exported automatically.
https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.ScopedAws.html
Usage
import { Stack, Construct, ScopedAws, StackProps } from '@aws-cdk/core';
export class DeployToS3Stack extends Stack {
constructor(scope: Construct, id: string, props: StackProps) {
super(scope, id, props);
const {
accountId,
notificationArns,
stackId,
stackName,
urlSuffix,
} = new ScopedAws(this)
...
Usage: IAM Policy statement
Using these parameter, we can easy to define our IAM policy statement more secure.
import { Stack, Construct, ScopedAws, StackProps } from '@aws-cdk/core';
import { ManagedPolicy, PolicyStatement, ServicePrincipal, Role } from "@aws-cdk/aws-iam"
export class DeployToS3Stack extends Stack {
constructor(scope: Construct, id: string, props: StackProps) {
super(scope, id, props);
const {
accountId,
stackName,
region,
} = new ScopedAws(this)
const LambdaRole = new Role(this.stack, 'LambdaRole', {
roleName: `${stackName}LambdaRole`,
managedPolicies: [
ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaBasicExecutionRole'),
new ManagedPolicy(this, `LambdaManagedPolicy`, {
managedPolicyName: `${stackName}LambdaManagedPolicy`,
statements: [
new PolicyStatement({
actions: [
'codebuild:StartBuild',
'codebuild:BatchGetBuilds'
],
resources: [
`arn:aws:codebuild:${region}:${accountId}:project/*`
]
})
]
})
],
assumedBy: new ServicePrincipal("lambda.amazonaws.com"),
path: '/'
})
The code will be create the following CloudFormation template.
LambdaManagedPolicy526313B2:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Statement:
- Action:
- codebuild:StartBuild
- codebuild:BatchGetBuilds
Effect: Allow
Resource:
Fn::Join:
- ""
- - "arn:aws:codebuild:"
- Ref: AWS::Region
- ":"
- Ref: AWS::AccountId
- :project/*
Version: "2012-10-17"
ManagedPolicyName:
Fn::Join:
- ""
- - Ref: AWS::StackName
- LambdaManagedPolicy
Path: /
Metadata:
aws:cdk:path: ExampleProject/LambdaManagedPolicy/Resource