Last active
October 22, 2021 15:08
-
-
Save mnanchev/041eba475b66580347b4c153abcf5ef1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Construct, Duration, Stack } from '@aws-cdk/core'; | |
import { Bucket, BucketEncryption } from '@aws-cdk/aws-s3'; | |
import { Code, Function, IFunction, Runtime } from '@aws-cdk/aws-lambda'; | |
import * as path from 'path'; | |
import { Effect, PolicyStatement } from '@aws-cdk/aws-iam'; | |
export interface CognitoUserMigrationLambdaProps { | |
readonly userPoolId: string; | |
readonly bucketName: string; | |
} | |
export class CognitoUserMigrationLambdaStack extends Stack { | |
public readonly function: IFunction; | |
constructor(scope: Construct, id: string, props: CognitoUserMigrationLambdaProps) { | |
super(scope, id); | |
// Create a bucket, where to store the user list | |
const bucket = new Bucket(this, props.bucketName, { | |
encryption: BucketEncryption.S3_MANAGED, | |
bucketName: props.bucketName, | |
}); | |
// create aws lambda function | |
this.function = new Function(this, `${id}Function`, { | |
code: Code.fromAsset(path.join(__dirname, './cognito-user-migration')), | |
handler: 'cognitoUserMigration.lambda_handler', | |
runtime: Runtime.PYTHON_3_8, | |
timeout: Duration.seconds(60), | |
environment: { | |
USER_POOL_ID: props.userPoolId, | |
BUCKET_NAME: props.bucketName, | |
}, | |
}); | |
// add to policy allow get and put objects in the bucket | |
this.function.addToRolePolicy( | |
new PolicyStatement({ | |
actions: ['s3:*Object*', 's3:ListBucket'], | |
resources: [bucket.arnForObjects('*'), bucket.bucketArn], | |
effect: Effect.ALLOW, | |
}), | |
); | |
// add to policy the possibility to list userpool users | |
this.function.addToRolePolicy( | |
new PolicyStatement({ | |
actions: ['cognito-idp:ListUsers'], | |
resources: [`arn:aws:cognito-idp:${this.region}:${this.account}:userpool/${props.userPoolId}`], | |
effect: Effect.ALLOW, | |
}), | |
); | |
// add to the bucket policy read and write permissions for the lambda | |
bucket.grantReadWrite(this.function); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment