def create_template(self): self.template = Template() self.param_env_name = param_env_name self.param_env_name.Default = self.ENVIRONMENT_NAME.get_value() self.template.add_parameter(param_env_name) self.iam_role_ec2_s3_full_access = iam.Role( "IamRoleEc2S3FullAccess", template=self.template, RoleName=helper_fn_sub("{}-ec2-s3-full-access", self.param_env_name), AssumeRolePolicyDocument=create_assume_role_policy_document( [AWSServiceName.amazon_Elastic_Compute_Cloud_Amazon_EC2]), ManagedPolicyArns=[AWSManagedPolicyArn.amazonS3FullAccess]) self.iam_instance_profile_ec2_s3_full_access = iam.InstanceProfile( "IamInstanceProfileS3FullAccess", template=self.template, InstanceProfileName=helper_fn_sub("{}-ec2-s3-full-access", self.param_env_name), Roles=[ self.iam_role_ec2_s3_full_access.iam_role_name, ]) return self.template
def test_mutable_aws_object(): """ 确定 ``mate.AWSObject`` 变化时, 对应的 ``mate.AWSObject.aws_object`` 也应该 跟着变化. """ from troposphere_mate import iam tpl = Template() my_policy = iam.ManagedPolicy( title="MyPolicy", template=tpl, PolicyDocument={}, ) my_role = iam.Role( title="MyRole", template=tpl, RoleName="my-role", AssumeRolePolicyDocument={}, ) assert tpl.to_dict( )["Resources"]["MyRole"]["Properties"]["RoleName"] == "my-role" assert "ManagedPolicyArns" not in tpl.to_dict( )["Resources"]["MyRole"]["Properties"] my_role.RoleName = "my-role-two" my_role.ManagedPolicyArns = [Ref(my_policy)] assert tpl.to_dict( )["Resources"]["MyRole"]["Properties"]["RoleName"] == "my-role-two" assert tpl.to_dict( )["Resources"]["MyRole"]["Properties"]["ManagedPolicyArns"] == [{ "Ref": "MyPolicy" }] outputs = [ Output( "MyRolePath", Value=GetAtt(my_role, "Path"), DependsOn=my_role, ) ] for output in outputs: tpl.add_output(output) assert tpl.to_dict()["Outputs"]["MyRolePath"]["Value"] == { "Fn::GetAtt": ["MyRole", "Path"] } dct = tpl.to_dict() tpl2 = Template() tpl2.add_resource(my_policy) tpl2.add_resource(my_role) for output in outputs: tpl2.add_output(output) dct2 = tpl2.to_dict() assert dct == dct2
}] })), DeletionPolicy=config.AWS_CFT_DYNAMIC_DELETEION_POLICY.get_value(), ) ecs_cluster = ecs.Cluster( "EcsCluster", ClusterName=helper_fn_sub("{}-webapp", param_env_name), DeletionPolicy=config.AWS_CFT_DYNAMIC_DELETEION_POLICY.get_value(), ) ecs_task_definition_execution_role = iam.Role( "IamRoleEcsTaskDefinitionExecutionRole", RoleName=helper_fn_sub("{}-webapp-ecs-role", param_env_name), AssumeRolePolicyDocument=canned.iam.create_assume_role_policy_document( ["ecs-tasks"]), ManagedPolicyArns=[ canned.iam.AWSManagedPolicyArn.administratorAccess, ], ) ecs_task_definition = ecs.TaskDefinition( "EcsTaskDefinition", ContainerDefinitions=[ ecs.ContainerDefinition( Name="webapp", Image="{}/{}:{}-{}".format( config.ECR_ENDPOINT.get_value(), config.ECR_REPO_NAME_WEBAPP.get_value(), config.APP_VERSION.get_value(), config.STAGE.get_value(),
TemplateURL="", # cross reference parameter Parameters={ tier_1_1_iam_policy.param_env_name.title: Ref(param_env_name), }, ) # bind nested stack with a template link_stack_template(stack=iam_policy_stack, template=tier_1_1_iam_policy.template) iam_ec_instance_role = iam.Role( "IamRoleWebServer", template=template, RoleName=helper_fn_sub("{}-web-server", param_env_name), AssumeRolePolicyDocument=canned.iam.create_assume_role_policy_document([ canned.iam.AWSServiceName.amazon_Elastic_Compute_Cloud_Amazon_EC2, ]), # cross reference output ManagedPolicyArns=[ GetAtt(iam_policy_stack, f"Outputs.{tier_1_1_iam_policy.output_iam_ec2_instance_policy_name.title}"), ], DependsOn=iam_policy_stack, ) # allow cross reference from other stack output_iam_ec2_instance_role_name = Output( "IamInstanceRoleName", Value=iam_ec_instance_role.iam_role_name, Export=Export(helper_fn_sub("{}-iam-ec2-instance-role-name", param_env_name)), DependsOn=iam_ec_instance_role, ) template.add_output(output_iam_ec2_instance_role_name)
) from ..devops.config_init import config template = Template() param_env_name = Parameter( "EnvironmentName", Type="String", Default=config.ECS_EXAMPLE_ENVIRONMENT_NAME.get_value()) template.add_parameter(param_env_name) iam_role_lambda_exec = iam.Role( "IamForLambda", RoleName=helper_fn_sub("{}-lambda-exec-role", param_env_name), AssumeRolePolicyDocument=canned.iam.create_assume_role_policy_document([ canned.iam.AWSServiceName.aws_Lambda, ]), ManagedPolicyArns=[ canned.iam.AWSManagedPolicyArn.awsLambdaBasicExecutionRole, ]) template.create_resource_type_label() # give all aws resource common tags common_tags = { "EnvironmentName": Ref(param_env_name), } template.update_tags(common_tags)
from seedinvest_monitor.devops.config_init import config template = Template() param_env_name = canned.parameter.param_env_name template.add_parameter(param_env_name) # -- declare aws resoure iam_role_for_lbd_func = iam.Role( "IamRoleForLbdFunc", template=template, RoleName=helper_fn_sub("{}-lbd-execution", param_env_name), AssumeRolePolicyDocument=canned.iam.create_assume_role_policy_document([ canned.iam.AWSServiceName.aws_Lambda, ]), ManagedPolicyArns=[ canned.iam.AWSManagedPolicyArn.awsLambdaBasicExecutionRole, canned.iam.AWSManagedPolicyArn.amazonSQSFullAccess, canned.iam.AWSManagedPolicyArn.amazonDynamoDBFullAccess, canned.iam.AWSManagedPolicyArn.amazonS3FullAccess, ]) dynamodb_table_startup = dynamodb.Table("DynamoDBTableStartup", template=template, TableName=helper_fn_sub( "{}-startup", param_env_name), KeySchema=[ dynamodb.KeySchema( AttributeName="id", KeyType="HASH",
# Input Stream kinesis_input_stream = kinesis.Stream( "KinesisInputStream", template=template, Name=helper_fn_sub("{}-web-event", param_env_name), RetentionPeriodHours=24, ShardCount=1, ) # Output Delivery Stream kinesis_delivery_stream_role = iam.Role( "KinesisDeliveryStreamServiceRole", template=template, RoleName=helper_fn_sub("{}-kinesis-delivery-stream-service-role", param_env_name), AssumeRolePolicyDocument=create_assume_role_policy_document([ AWSServiceName.amazon_Kinesis_Data_Firehose, ]), ManagedPolicyArns=[ AWSManagedPolicyArn.administratorAccess, ]) kinesis_delivery_stream = firehose.DeliveryStream( "KinesisDeliveryStream", template=template, DeliveryStreamName=helper_fn_sub("{}-web-event", param_env_name), DeliveryStreamType="DirectPut", ExtendedS3DestinationConfiguration=firehose. ExtendedS3DestinationConfiguration( BucketARN="arn:aws:s3:::eq-sanhe-for-everything", Prefix=Sub(
from .app_config_init import app_config template = tm.Template() param_env_name = tm.Parameter( "EnvironmentName", Type="String", ) template.add_parameter(param_env_name) rest_api = apigateway.RestApi( "RestApi", template=template, Name=tm.helper_fn_sub("{}", param_env_name), EndpointConfiguration=apigateway.EndpointConfiguration(Types=[ "REGIONAL", ])) lambda_code = awslambda.Code( S3Bucket=app_config.LAMBDA_CODE_S3_BUCKET.get_value(), S3Key=app_config.LAMBDA_CODE_S3_KEY.get_value(), ) iam_role = iam.Role( "IamRoleForLbdFunc", template=template, RoleName=tm.helper_fn_sub("{}-lbd-func", param_env_name), AssumeRolePolicyDocument=create_assume_role_policy_document( [AWSServiceName.aws_Lambda]), ManagedPolicyArns=[AWSManagedPolicyArn.awsLambdaBasicExecutionRole])
"Sid": "VisualEditor0", "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::*/*" }] }) ec2_iam_role = iam.Role( "EC2IamRole", template=template, RoleName=helper_fn_sub("{}-ec2-role", param_env_name), AssumeRolePolicyDocument=canned.iam.create_assume_role_policy_document([ canned.iam.AWSServiceName.amazon_Elastic_Compute_Cloud_Amazon_EC2, ]), ManagedPolicyArns=[ ec2_iam_policy.iam_managed_policy_arn, ], ) template.create_resource_type_label() # give all aws resource common tags common_tags = { "EnvironmentName": Ref(param_env_name), } template.update_tags(common_tags)
# -*- coding: utf-8 -*- import pytest from troposphere import Ref, GetAtt from troposphere_mate import awslambda, iam, ec2, sqs, kms from troposphere_mate.associate import LinkerApi, associate iam_role = iam.Role( title="MyIamRole", RoleName="my-iam-role", AssumeRolePolicyDocument={}, ) vpc = ec2.VPC(title="MyVPC", CidrBlock="10.53.0.0/16") public_subnet1 = ec2.Subnet( title="PublicSubnet1", CidrBlock="10.53.0.0/16", VpcId=Ref(vpc), ) public_subnet2 = ec2.Subnet( title="PublicSubnet2", CidrBlock="10.53.2.0/16", VpcId=Ref(vpc), ) sg = ec2.SecurityGroup(title="LambdaSG", GroupDescription="Just a SG") sqs_queue = sqs.Queue(title="SqsQueue", )
code_build_service_role = iam.Role( title="CodeBuildServiceRole", template=template, RoleName=f"{config.ENVIRONMENT_NAME.get_value()}-code-build-service-role", AssumeRolePolicyDocument=create_assume_role_policy_document([AWSServiceName.codeBuild]), Policies=[ iam.Policy( PolicyName="AllowEcrAction", PolicyDocument={ "Version": "2012-10-17", "Statement": [ { "Action": [ "ecr:BatchCheckLayerAvailability", "ecr:CompleteLayerUpload", "ecr:GetAuthorizationToken", "ecr:InitiateLayerUpload", "ecr:PutImage", "ecr:UploadLayerPart" ], "Resource": "*", "Effect": "Allow" }, # only allow all codebuild operation on this code build project { "Action": [ "codebuild:*" ], "Resource": f"arn:aws:codebuild:{config.AWS_REGION.get_value()}:{config.AWS_ACCOUNT_ID.get_value()}:project/{config.CODE_BUILD_PROJECT_NAME.get_value()}", "Effect": "Allow" }, { "Effect": "Allow", "Resource": [ f"arn:aws:logs:{config.AWS_REGION.get_value()}:{config.AWS_ACCOUNT_ID.get_value()}:log-group:/aws/codebuild/{config.CODE_BUILD_PROJECT_NAME.get_value()}", f"arn:aws:logs:{config.AWS_REGION.get_value()}:{config.AWS_ACCOUNT_ID.get_value()}:log-group:/aws/codebuild/{config.CODE_BUILD_PROJECT_NAME.get_value()}:*" ], "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ] }, { "Effect": "Allow", "Resource": [ f"arn:aws:s3:::codepipeline-{config.AWS_REGION.get_value()}-*" ], "Action": [ "s3:PutObject", "s3:GetObject", "s3:GetObjectVersion", "s3:GetBucketAcl", "s3:GetBucketLocation" ] }, { "Effect": "Allow", "Action": [ "codebuild:CreateReportGroup", "codebuild:CreateReport", "codebuild:UpdateReport", "codebuild:BatchPutTestCases" ], "Resource": [ f"arn:aws:codebuild:{config.AWS_REGION.get_value()}:{config.AWS_ACCOUNT_ID.get_value()}:report-group/{config.CODE_BUILD_PROJECT_NAME.get_value()}-*" ] } ] } ), ], )
def create_template(self): self.template = Template() self.iam_role_lbd_basic_exec = iam.Role( "IamRoleLambdaBasicExecution", template=self.template, Metadata={ DEFAULT_LABELS_FIELD: [Metadata.iam_role_lbd_basic_exec, ] }, RoleName="{}-lbd-basic-exec".format( self.ENVIRONMENT_NAME.get_value()), AssumeRolePolicyDocument=create_assume_role_policy_document( [AWSServiceName.aws_Lambda]), ManagedPolicyArns=[AWSManagedPolicyArn.awsLambdaBasicExecutionRole] ) self.iam_role_lbd_s3_read_and_write = iam.Role( "IamRoleLambdaS3Execution", template=self.template, Metadata={ DEFAULT_LABELS_FIELD: [Metadata.iam_role_lbd_s3_read_and_write, ] }, RoleName="{}-lbd-s3-exec".format( self.ENVIRONMENT_NAME.get_value()), AssumeRolePolicyDocument=create_assume_role_policy_document([ AWSServiceName.aws_Lambda, ]), ManagedPolicyArns=[ AWSManagedPolicyArn.awsLambdaExecute ], ) if self.S3_RESTRICTED_BUCKETS.get_value(): bucket_name_list = [ bucket_name.strip() for bucket_name in self.S3_RESTRICTED_BUCKETS.get_value().split(",") ] self.iam_role_lbd_s3_restricted_bucket_read_and_write = iam.Role( "IamRoleLambdaS3RestrictedBucketExecution", template=self.template, Metadata={ DEFAULT_LABELS_FIELD: [Metadata.iam_role_lbd_s3_restricted_bucket_read_and_write, ] }, RoleName="{}-lbd-s3-exec".format( self.ENVIRONMENT_NAME.get_value()), AssumeRolePolicyDocument=create_assume_role_policy_document( [AWSServiceName.aws_Lambda]), Policies=[ iam.Policy( PolicyName="", PolicyDocument={ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:*" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject" ], "Resource": [ "arn:aws:s3:::{}*".format(bucket_name) for bucket_name in bucket_name_list ] } ] } ) ] ) return self.template
"s3:List*", "s3:Describe*", ], "Resource": "*" }] }, ) LABEL_IAM_ROLE_TIER = "iam_role_tier" iam_ec_instance_role = iam.Role( "IamRoleWebServer", template=template, Metadata={DEFAULT_LABELS_FIELD: [ LABEL_IAM_ROLE_TIER, ]}, RoleName=helper_fn_sub("{}-web-server", param_env_name), AssumeRolePolicyDocument=canned.iam.create_assume_role_policy_document([ canned.iam.AWSServiceName.amazon_Elastic_Compute_Cloud_Amazon_EC2, ]), # cross reference output ManagedPolicyArns=[iam_ec2_instance_policy.iam_managed_policy_arn], DependsOn=iam_ec2_instance_policy, ) LABEL_IAM_INSTANCE_PROFILE_TIER = "iam_instance_profile_tier" iam_instance_profile = iam.InstanceProfile( "IamInstanceProfileWebServer", template=template, Metadata={DEFAULT_LABELS_FIELD: [ LABEL_IAM_INSTANCE_PROFILE_TIER, ]}, InstanceProfileName=helper_fn_sub("{}-web-server", param_env_name),