def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) #get region, use region as bucket postfix name region=self.region #init CfnBucket bucket=s3.CfnBucket(self,id, bucket_name="aws-cdk-handson-"+region, bucket_encryption={ 'serverSideEncryptionConfiguration':[ {'serverSideEncryptionByDefault': {'sseAlgorithm':'AES256'} } ] }, cors_configuration={ 'corsRules':[ { 'allowedHeaders':['*'], 'allowedMethods':['GET'], 'allowedOrigins':['*'] } ] }, versioning_configuration={'status': 'Enabled'} ) core.CfnOutput(self,"BucketArn",export_name="BucketArn",value=bucket.attr_arn)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # get region, use region as bucket postfix name region = self.region # init CfnBucket bucket = s3.CfnBucket( self, id, bucket_name="aws-cdk-handson-" + region + "-test", bucket_encryption={ "serverSideEncryptionConfiguration": [{ "serverSideEncryptionByDefault": { "sseAlgorithm": "AES256" } }] }, versioning_configuration={"status": "Enabled"}, ) core.CfnOutput(self, "BucketArn", export_name="Lab04BucketArn", value=bucket.attr_arn)
def create_transfer_accelerated_bucket(self) -> str: bucket_name = self.get_bucket_name("accel") # As of this writing (2020-05-11), The Bucket object does not expose transfer acceleration bucket = aws_s3.CfnBucket( self, "integ_test_s3_bucket_transfer_acceleration", bucket_name=bucket_name, accelerate_configuration={"accelerationStatus": "Enabled"}, ) self._parameters_to_save[ "bucket_name_transfer_acceleration"] = bucket_name bucket.apply_removal_policy(core.RemovalPolicy.DESTROY) return bucket_name
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) ## Config #- Create bucket #- Create IAM role #- Setup Recorder #- Setup Delivery Channel: https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_config/CfnDeliveryChannel.html cliSts = boto3.client('sts') caller = cliSts.get_caller_identity() roleConfig = _iam.CfnRole(self, "CustomAWSConfigService", role_name="CustomAWSConfigService", assume_role_policy_document={ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "config.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }, managed_policy_arns=[ "arn:aws:iam::aws:policy/service-role/AWSConfigRole", "arn:aws:iam::aws:policy/AmazonS3FullAccess" ]) bname = "aws-config-custom-{}".format(caller['Account']) bucketConfig = _s3.CfnBucket(self, bname, bucket_name=bname) bucketConfig.apply_removal_policy(apply_to_update_replace_policy=False) rec = _config.CfnConfigurationRecorder(self, "ConfigRec", name="ConfigRec", role_arn=roleConfig.attr_arn, recording_group=CfnConfigurationRecorder.RecordingGroupProperty( all_supported=True, include_global_resource_types=True )) rec.add_depends_on(roleConfig) cfgDC = _config.CfnDeliveryChannel(self, 'aws-config', s3_bucket_name=bname, config_snapshot_delivery_properties=CfnDeliveryChannel.ConfigSnapshotDeliveryPropertiesProperty( delivery_frequency="Twelve_Hours"), name='aws-config') cfgDC.add_depends_on(bucketConfig)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) #获取region变量, 使用region 和 datetime 作为bucket的名字 region = self.region now = datetime.now().strftime("%Y%M%d%H%M") #初始化 CfnBucket,设置bucket_name bucket = s3.CfnBucket(self, id, bucket_name="aws-cdk-handson-" + region + "-" + now) #输出Bucket名字和ARN core.CfnOutput(self, "BucketName", value=bucket.bucket_name) core.CfnOutput(self, "BucketArn", value=bucket.attr_arn)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) bucket_name = "cfn-bucket-with-policy-test-abcdefg" bucket_prefix = "alb-log" elb_account_id = "582318560864" # ポリシー作成 policy_statement = iam.PolicyStatement() policy_statement.add_aws_account_principal(elb_account_id) policy_statement.add_actions("s3:PutObject") policy_statement.add_resources("arn:aws:s3:::{0}/{1}/*".format( bucket_name, bucket_prefix)) policy_document = iam.PolicyDocument(statements=[policy_statement]) # S3 バケット(CfnBucket) bucket = s3.CfnBucket(self, "Bucket", bucket_name=bucket_name) # バケットポリシー(CfnBucketPolicy) s3.CfnBucketPolicy(self, "BucketPolicy", bucket=bucket.ref, policy_document=policy_document.to_json())
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # Set Parameters db_password_parameters = core.CfnParameter( self, "DBPassword", no_echo=True, description="New account and RDS password", min_length=1, max_length=41, constraint_description= "the password must be between 1 and 41 characters", default="DBPassword") # LambdaExecutionRole LambdaExecutionRole = iam.CfnRole( self, "LabelsLambdaExecutionRole", assume_role_policy_document={ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "Service": ["lambda.amazonaws.com"] }, "Action": ["sts:AssumeRole"] }] }, managed_policy_arns=[ "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole", "arn:aws:iam::aws:policy/AmazonRekognitionReadOnlyAccess", "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess", "arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess" ], policies=[{ "policyName": "root", "policyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["logs:*"], "Resource": "arn:aws:logs:*:*:*" }, ] } }]) # S3 Bucket source_bucket = "sourcebucketname%s" % (core.Aws.ACCOUNT_ID) # LabelsLambda LabelsLambda = lambda_.CfnFunction( self, "LabelsLambda", handler="lambda_function.lambda_handler", role=LambdaExecutionRole.attr_arn, code={ "s3Bucket": source_bucket, "s3Key": "lambda.zip" }, runtime="python3.6", timeout=120, tracing_config={"mode": "Active"}, vpc_config={ "securityGroupIds": [core.Fn.import_value("LambdaSecurityGroupOutput")], "subnetIds": [ core.Fn.import_value("PrivateSubnet1"), core.Fn.import_value("PrivateSubnet2") ] }, environment={ "variables": { "DATABASE_HOST": core.Fn.import_value("MyDBEndpoint"), "DATABASE_USER": "******", "DATABASE_PASSWORD": db_password_parameters.value_as_string, "DATABASE_DB_NAME": "Photos" } }) # UploadQueue upload_queue = sqs.CfnQueue(self, "UploadQueue", queue_name="uploads-queue", message_retention_period=12800, visibility_timeout=300) # UploadSNSTopic upload_sns_topic = sns.CfnTopic( self, "UploadSNSTopic", display_name="uploads-topic", subscription=[{ "endpoint": upload_queue.attr_arn, "protocol": "sqs" }, { "endpoint": LabelsLambda.attr_arn, "protocol": "lambda" }], ) # QueuePolicy queue_policy = sqs.CfnQueuePolicy( self, "QueuePolicy", queues=[upload_queue.ref], policy_document={ "Version": "2012-10-17", "Id": "QueuePolicy", "Statement": [{ "Sid": "Allow-SendMessage-To-Queues-From-SNS-Topic", "Effect": "Allow", "Principal": "*", "Action": ["SQS:SendMessage"], "Resource": "*", "Condition": { "ArnEquals": { "aws:SourceArn": "%s" % (upload_sns_topic.ref) } } }] }) # UploadTopicPolicy upload_topic_policy = sns.CfnTopicPolicy( self, "UploadTopicPolicy", policy_document={ "Version": "2012-10-17", "Id": "QueuePolicy", "Statement": [{ "Sid": "Allow-S3-Publish", "Effect": "Allow", "Principal": { "Service": "s3.amazonaws.com" }, "Action": ["SNS:Publish"], "Resource": upload_sns_topic.ref, "Condition": { "StringEquals": { "aws:SourceAccount": "!Sub '${AWS::AccountId}'" }, "ArnLike": { "aws:SourceArn": { "Fn::Join": [ "", [ "arn:aws:s3:*:*:", "!Sub 'imagebucketsns${AWS::AccountId}'" ] ] } } }, }] }, topics=[upload_sns_topic.ref]) # ImageS3Bucket image_s3_bucket = s3.CfnBucket(self, "ImageS3Bucket", bucket_name="imagebucketsns%s" % (core.Aws.ACCOUNT_ID), notification_configuration={ "topicConfigurations": [{ "event": 's3:ObjectCreated:*', "topic": upload_sns_topic.ref }] }) image_s3_bucket.add_depends_on(upload_topic_policy) image_s3_bucket.apply_removal_policy(core.RemovalPolicy.DESTROY) # ImageS3BucketPermission ImageS3BucketPermission = lambda_.CfnPermission( self, "ImageS3BucketPermission", action="lambda:InvokeFunction", function_name=LabelsLambda.attr_arn, principal="sns.amazonaws.com", source_arn=upload_sns_topic.ref) # Outputs core.CfnOutput(self, "ImageS3BucketOutput", value=image_s3_bucket.ref, description="Image S3 Bucket", export_name="ImageS3Bucket") core.CfnOutput(self, "LabelsLambdaOutput", value=LabelsLambda.ref, description="Labels Lambda", export_name="LabelsLambda")