def build_cw_cb_role(template, config, role_name="s2nEventsInvokeCodeBuildRole"): """ Create a role for CloudWatch events to trigger scheduled CodeBuild jobs. """ role_id = template.add_resource( Role( role_name, Path='/', AssumeRolePolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[ Action("sts", "AssumeRole"), ], Principal=Principal("Service", ["events.amazonaws.com"])) ]), Policies=[ Policy( PolicyName=f"EventsInvokeCBRole", PolicyDocument=PolicyDocument(Statement=[ Statement( Effect=Allow, Action=[Action("codebuild", "StartBuild")], Resource=[ "arn:aws:codebuild:{region}:{account_number}:project/*" .format(region=config.get( 'Global', 'aws_region'), account_number=config.get( 'CFNRole', 'account_number')), ]) ])) ])) return role_id
def build_cw_cb_role(template=None, role_name="s2nEventsInvokeCodeBuildRole"): """ Create a role for CloudWatch events to trigger Codebuild jobs. """ role_id = template.add_resource( Role( role_name, Path='/', AssumeRolePolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[ Action("sts", "AssumeRole"), ], Principal=Principal("Service", ["events.amazonaws.com"])) ]), Policies=[ Policy( PolicyName=f"EventsInvokeCBRole", PolicyDocument=PolicyDocument(Statement=[ Statement( Effect=Allow, Action=[Action("codebuild", "StartBuild")], Resource=[ "arn:aws:codebuild:us-west-2:024603541914:project/*", ]) ])) ])) return role_id
def add_instance_role(self): ''' Add Instance role ''' self.cfn_template.add_resource(Role( title=constants.INST_ROLE, AssumeRolePolicyDocument=PolicyDocument( Statement=[ Statement( Effect=Allow, Action=[AssumeRole], Principal=Principal('Service', ['ec2.amazonaws.com']) ) ] ), Policies=[ Policy( PolicyName='Demo-ECS-Cluster', PolicyDocument=PolicyDocument( Statement=[ Statement( Effect=Allow, Action=[ Action('*') ], Resource=['*'] ) ] ) ) ] )) return self.cfn_template
def add_use_dynamodb_role(template: Template) -> Role: return template.add_resource( Role("usedynamodbrole", AssumeRolePolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal("Service", ["lambda.amazonaws.com"])), Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal("Service", ["apigateway.amazonaws.com"])) ]), Policies=[ Policy(PolicyName="policy_use_dynamodb", PolicyDocument=PolicyDocument( Id="policy_use_dynamodb", Version="2012-10-17", Statement=[ Statement(Effect=Allow, Action=[ DescribeTable, PutItem, GetRecords, GetItem, DeleteItem, Scan ], Resource=["*"]), Statement(Effect=Allow, Action=[ CreateLogGroup, CreateLogStream, PutLogEvents ], Resource=["*"]) ])) ]))
def gen_execution_role(self): # IAM role that allows ECS to pull image from ECR # and write Cloudwatch logs. role_name = "conducto-demo-execution-role" self.execution_role = iam.Role( "ExecutionRole", RoleName=role_name, AssumeRolePolicyDocument=PolicyDocument( Version=self.IAM_POLICY_DOCUMENT_VERSION, Statement=[ Statement( Effect=Allow, Action=[Action("sts", "AssumeRole")], Principal=Principal("Service", "ecs-tasks.amazonaws.com"), ) ], ), Policies=[ iam.Policy( PolicyName=role_name, PolicyDocument=PolicyDocument( Version=self.IAM_POLICY_DOCUMENT_VERSION, Statement=[ Statement( Effect=Allow, Action=[ Action("ecr", "GetAuthorizationToken"), Action("ecr", "BatchCheckLayerAvailability"), Action("ecr", "GetDownloadUrlForLayer"), Action("ecr", "BatchGetImage"), Action("logs", "CreateLogGroup"), Action("logs", "CreateLogStream"), Action("logs", "PutLogEvents"), ], Resource=["*"], ), Statement( Effect=Allow, Action=[Action("iam", "PassRole")], Resource=["arn:aws:iam::*:role/*"], ), ], ), ) ], ) self.template.add_resource(self.execution_role)
def vpc_role_adder(self): self.k8_master_role = self.template.add_resource( Role('k8master', AssumeRolePolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal("Service", ["ec2.amazonaws.com"])) ]), Policies=[ Policy( PolicyName='k8master', PolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[ Action('s3', 'List*'), Action('s3', 'Get*'), Action('ecr', '*'), Action('elasticloadbalancing', '*'), cloudformation.SignalResource, Action('ec2', 'Describe*'), ], Resource=['*']) ])) ])) self.k8_worker_role = self.template.add_resource( Role('k8worker', AssumeRolePolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal("Service", ["ec2.amazonaws.com"])) ]), Policies=[ Policy(PolicyName='worker', PolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[ Action('s3', 'List*'), Action('s3', 'Get*'), Action('ecr', '*'), cloudformation.SignalResource, Action('ec2', 'Describe*'), Action('sns', '*') ], Resource=['*']) ])) ]))
def build_github_role(template=None, role_name="s2nCodeBuildGithubRole"): """ Create a role for GitHub actions to use for launching CodeBuild jobs. This is not attached to any other resource created in this file. """ role_id = template.add_resource( Role( role_name, Path='/', AssumeRolePolicyDocument=PolicyDocument(Statement=[ Statement( Effect=Allow, Action=[ Action("logs", "CreateLogGroup"), Action("logs", "CreateLogStream"), Action("logs", "PutLogEvents") ], Resource=[ "arn:aws:logs:us-west-2:024603541914:log-group:/aws/codebuild/s2nGithubCodebuild", "arn:aws:logs:us-west-2:024603541914:log-group:/aws/codebuild/s2nGithubCodebuild:*" ]) ]))) return Ref(role_id) template.add_output([Output(role_name, Value=Ref(role_id))]) return Ref(role_id)
def build_role(template=Template(), section="CFNRole", project_name: str = None, **kwargs) -> Ref: """ Build a role with a CodeBuild managed policy. """ template.set_version('2010-09-09') assert project_name project_name += 'Role' # NOTE: By default CodeBuild manages the policies for this role. If you delete a CFN stack and try to recreate the project # or make changes to it when the Codebuild managed Policy still exists, you'll see an error in the UI: # `The policy is attached to 0 entities but it must be attached to a single role`. (CFN fails with fail to update) # Orphaned policies created by CodeBuild will have CodeBuildBasePolicy prepended to them; search for policies with this # name and no role and delete to clear the error. # TODO: Get a CloudFormation feature request to turn this off for project creation- let CFN manage the policy. role_id = template.add_resource( Role(project_name, Path='/', AssumeRolePolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal("Service", ["codebuild.amazonaws.com"])) ]))) template.add_output([Output(project_name, Value=Ref(role_id))]) return Ref(role_id)
def user_delegate_role_and_policies(self, user, permissions_list): "Create and add an account delegate Role to template" user_arn = 'arn:aws:iam::{}:user/{}'.format(self.master_account_id, user.username) assume_role_res = troposphere.iam.Role( "UserAccountDelegateRole", RoleName="IAM-User-Account-Delegate-Role-{}".format( self.create_resource_name(user.name, filter_id='IAM.Role.RoleName')), AssumeRolePolicyDocument=PolicyDocument( Version="2012-10-17", Statement=[ Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal("AWS", [user_arn]), Condition=Condition( [AWACSBool({MultiFactorAuthPresent: True})])) ])) # Iterate over permissions and create a delegate role and policices for permission_config in permissions_list: init_method = getattr( self, "init_{}_permission".format(permission_config.type.lower())) init_method(permission_config, assume_role_res) self.template.add_resource(assume_role_res) self.template.add_output( troposphere.Output( title='SigninUrl', Value=troposphere.Sub( 'https://signin.aws.amazon.com/switchrole?account=${AWS::AccountId}&roleName=${UserAccountDelegateRole}' )))
def create_template(self): """Create template (main function called by Stacker).""" template = self.template template.set_version("2010-09-09") template.set_description("Runway Integration Testing - IAM Role") # Resources template.add_resource( iam.Role( "CodeBuildRole", AssumeRolePolicyDocument=PolicyDocument( Statement=[ Statement( Effect=Allow, Action=[awacs.sts.AssumeRole], Principal=Principal("AWS", TESTING_ACCOUNT_ID), ) ] ), Description="Role used for cross account testing in runway", ManagedPolicyArns=["arn:aws:iam::aws:policy/AdministratorAccess"], RoleName=Join( "-", [ "runway-integration-test-role", self.variables["EnvironmentName"].ref, ], ), ) )
def _get_replicated_lambda_state_machine_role( self, remover_function, # type: Dict[str, Union[awslambda.Function, iam.Role, Any]] # noqa pylint: disable=line-too-long self_destruct_function # type: Dict[str, Union[awslambda.Function, iam.Role, Any]] # noqa pylint: disable=line-too-long ): # type (...) -> iam.Role entity = Join('.', ['states', Region, 'amazonaws.com']) return self.template.add_resource( iam.Role( 'StateMachineRole', AssumeRolePolicyDocument=make_simple_assume_policy(entity), Policies=[ iam.Policy( PolicyName="InvokeLambda", PolicyDocument=PolicyDocument( Version="2012-10-17", Statement=[ Statement( Action=[awacs.awslambda.InvokeFunction], Effect=Allow, Resource=[ remover_function.get_att('Arn'), self_destruct_function.get_att('Arn') ]) ])) ]))
def init_custompolicy_permission(self, permission_config, assume_role_res): for managed_policy in permission_config.managed_policies: if 'ManagedPolicyArns' not in assume_role_res.properties.keys(): assume_role_res.properties['ManagedPolicyArns'] = [] assume_role_res.properties['ManagedPolicyArns'].append('arn:aws:iam::aws:policy/' + managed_policy) for policy in permission_config.policies: policy_statements = [] for policy_statement in policy.statement: statement_dict = { 'Effect': policy_statement.effect, 'Action': [ Action(*action.split(':')) for action in policy_statement.action ], } # Resource statement_dict['Resource'] = policy_statement.resource policy_statements.append( Statement(**statement_dict) ) # Make the policy managed_policy_res = troposphere.iam.ManagedPolicy( title=self.create_cfn_logical_id_join( str_list=["CustomPolicy", policy.name], camel_case=True ), PolicyDocument=PolicyDocument( Version="2012-10-17", Statement=policy_statements ), Roles=[ troposphere.Ref(assume_role_res) ] ) self.template.add_resource(managed_policy_res)
def ssm_global(): template = Template() ssm_role = iam.Role( 'SsmRole', RoleName="SsmRole", ManagedPolicyArns=[ "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore", "arn:aws:iam::aws:policy/AmazonS3FullAccess", "arn:aws:iam::aws:policy/AmazonEC2FullAccess" ], AssumeRolePolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[Action("sts", "AssumeRole")], Principal=Principal("Service", "ec2.amazonaws.com")) ])) ssm_profile = iam.InstanceProfile('SsmProfile', Roles=[Ref(ssm_role)], InstanceProfileName="SsmProfile") template.add_resource(ssm_role) template.add_resource(ssm_profile) with open( os.path.dirname(os.path.realpath(__file__)) + '/ssm_global.yml', 'w') as cf_file: cf_file.write(template.to_yaml()) return template.to_yaml()
def create_base_policy(): """Create the base policy.""" deploy_name_list = ["runway-int-test-"] return iam.Policy( PolicyName="base-policy", PolicyDocument=PolicyDocument( Version="2012-10-17", Statement=[ Statement( Action=[ awacs.logs.CreateLogGroup, awacs.logs.CreateLogStream, awacs.logs.PutLogEvents, ], Effect=Allow, Resource=[ Join( "", [ "arn:", Partition, ":logs:", Region, ":", AccountId, ":log-group:/aws/codebuild/", ] + deploy_name_list + ["*"] + x, ) for x in [[":*"], [":*/*"]] ], ) ], ), )
def ECR(self, name): logger.info(f"Criando o ECR: {name}") project_name = f'ECR{name}' resource_name = ''.join(e for e in project_name if e.isalnum()) p_service = Principal("Service", "codebuild.amazonaws.com") p_aws = Principal("AWS", [ Sub("arn:aws:iam::${DevAccount}:root"), Sub("arn:aws:iam::${HomologAccount}:root"), Sub("arn:aws:iam::${ProdAccount}:root") ]) policydocument = PolicyDocument(Version='2008-10-17', Statement=[ Statement( Sid='AllowPushPull', Effect=Allow, Principal=p_service, Action=[Action("ecr", "*")], ), Statement( Sid='AllowPushPull', Effect=Allow, Principal=p_aws, Action=[Action("ecr", "*")], ), ]) resource_ecr = Repository(resource_name, RepositoryName=name.lower(), RepositoryPolicyText=policydocument) return [resource_ecr]
def init_codebuild_permission(self, permission_config, assume_role_res): """CodeBuild Web Console Permissions""" if 'ManagedPolicyArns' not in assume_role_res.properties.keys(): assume_role_res.properties['ManagedPolicyArns'] = [] statement_list = [] #readwrite_codebuild_arns = [] readonly_codebuild_arns = [] for resource in permission_config.resources: codebuild_ref = Reference(resource.codebuild) codebuild_account_ref = 'paco.ref ' + '.'.join( codebuild_ref.parts[:-2]) + '.configuration.account' codebuild_account_ref = self.paco_ctx.get_ref( codebuild_account_ref) codebuild_account_id = self.paco_ctx.get_ref( codebuild_account_ref + '.id') if codebuild_account_id != self.account_id: continue codebuild_arn = self.paco_ctx.get_ref(resource.codebuild + '.project.arn') if resource.permission == 'ReadOnly': if codebuild_arn not in readonly_codebuild_arns: readonly_codebuild_arns.append(codebuild_arn) readonly_codebuild_actions = [ Action('codebuild', 'BatchGet*'), Action('codebuild', 'Get*'), Action('codebuild', 'List*'), Action('cloudwatch', 'GetMetricStatistics*'), Action('events', 'DescribeRule'), Action('events', 'ListTargetsByRule'), Action('events', 'ListRuleNamesByTarget'), Action('logs', 'GetLogEvents') ] if len(readonly_codebuild_arns) > 0: statement_list.append( Statement( Sid='CodeBuildReadOnly', Effect=Allow, Action=readonly_codebuild_actions, Resource=['*'] #readonly_codebuild_arns )) #statement_list.append( # Statement( # Sid='OtherReadOnly', # Effect=Allow, # Action=readonly_other_actions, # Resource=['*'] # ) #) managed_policy_res = troposphere.iam.ManagedPolicy( title=self.create_cfn_logical_id("CodeBuildPolicy"), PolicyDocument=PolicyDocument(Version="2012-10-17", Statement=statement_list), Roles=[troposphere.Ref(assume_role_res)]) self.template.add_resource(managed_policy_res) #
def flow_logs(t, vpc_objects): vpc_flow_log_role = t.add_resource( Role("vpcflowlogrole", AssumeRolePolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[Action("sts", "AssumeRole")], Principal=Principal("Service", "vpc-flow-logs.amazonaws.com")) ]), Policies=[ Policy(PolicyName="vpc_flow_logs_policy", PolicyDocument=PolicyDocument( Id="vpc_flow_logs_policy", Version="2012-10-17", Statement=[ Statement(Effect=Allow, Action=[ Action("logs", "CreateLogGroup"), Action("logs", "CreateLogStream"), Action("logs", "PutLogEvents"), Action("logs", "DescribeLogGroups"), Action("logs", "DescribeLogStreams") ], Resource=["arn:aws:logs:*:*:*"]) ])) ])) t.add_resource( logs.LogGroup( 'VPCLogGroup', LogGroupName='VPCFlowLog', #DependsOn="vpcflowlogrole", RetentionInDays=7)) t.add_resource( ec2.FlowLog( 'VPCFlowLog', DeliverLogsPermissionArn=GetAtt(vpc_flow_log_role, "Arn"), LogGroupName='VPCFlowLog', ResourceId=Ref(vpc_objects['vpc']), ResourceType='VPC', #DependsOn="VPCLogGroup", TrafficType='ALL')) return t, vpc_objects
def codebuild_policy_document(input_kwargs, build_data): user = "******" account = build_data["account_id"] region = build_data["region"] logs_arn = f"arn:aws:logs:{region}:{account}:log-group:/aws/lambda/*" ec2_arn = [ "arn:aws:s3:::product-images-*", "arn:aws:s3:::product-images-*/*" ] pd = PolicyDocument( Version="2012-10-17", Id="Lambda-Common-Permissions", Statement=[ Statement(Effect=Allow, Principal=Principal("AWS", [IAM_ARN(user, '', account)]), Action=[logs.CreateLogStream, logs.PutLogEvents], Resource=[logs_arn]), Statement( Effect=Allow, Principal=Principal("AWS", [IAM_ARN(user, '', account)]), Action=[ ec2.CreateNetworkInterface, ec2.DescribeNetworkInterfaces, ec2.DeleteNetworkInterface, "ec2:Describe*", ec2.CreateSnapshot, ec2.DeleteSnapshot, ec2.CreateImage, ec2.CopyImage, ec2.DeregisterImage, ce.GetCostAndUsage, events.EnableRule, secretsmanager.GetSecretValue, secretsmanager.DescribeSecret, "kms:*", "cloudwatch:*", "s3:*" ], Resource=ec2_arn), Statement(Effect=Allow, Principal=Principal("AWS", [IAM_ARN(user, '', account)]), Action=[ rds.DescribeDBClusterSnapshots, rds.DescribeDBClusters, rds.CopyDBClusterSnapshot, rds.ModifyDBClusterSnapshotAttribute, rds.ListTagsForResource ], Resource=['*']) ]) input_kwargs["policy"] = pd.to_json() return input_kwargs
def add_role(template: Template) -> Role: return template.add_resource( Role("CFNRole", AssumeRolePolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal("Service", ["ec2.amazonaws.com"])) ])))
def init_systemsmanagersession_permission(self, permission_config, assume_role_res): if 'ManagedPolicyArns' not in assume_role_res.properties.keys(): assume_role_res.properties['ManagedPolicyArns'] = [] resource_group_condition_list = [] for resource in permission_config.resources: resource_ref = Reference(resource) # Initialize The network environments that we need access into resource_obj = resource_ref.get_model_obj(self.paco_ctx.project) if schemas.IResourceGroup.providedBy(resource_obj): resource_group_condition_list.append( StringLike({ 'ssm:resourceTag/Paco-Application-Group-Name': resource_obj.name })) if len(resource_group_condition_list) == 0: return statement_list = [] statement_list.append( Statement( Sid='SessionManagerStartSession', Effect=Allow, Action=[ Action('ssm', 'StartSession'), ], Resource=[ 'arn:aws:ec2:*:*:instance/*', 'arn:aws:ssm:*::document/AWS-StartPortForwardingSession' ], Condition=Condition(resource_group_condition_list))) statement_list.append( Statement( Sid='SessionManagerPortForward', Effect=Allow, Action=[ Action('ssm', 'StartSession'), ], Resource=[ 'arn:aws:ssm:*::document/AWS-StartPortForwardingSession' ])) statement_list.append( Statement(Sid='SessionManagerTerminateSession', Effect=Allow, Action=[ Action('ssm', 'TerminateSession'), Action('ssm', 'ResumeSession'), ], Resource=['arn:aws:ssm:*:*:session/${aws:username}-*'])) managed_policy_res = troposphere.iam.ManagedPolicy( title=self.create_cfn_logical_id_join(["SystemsManagerSession"]), PolicyDocument=PolicyDocument(Version="2012-10-17", Statement=statement_list), Roles=[troposphere.Ref(assume_role_res)]) self.template.add_resource(managed_policy_res)
def add_ecs_service_role(self): ''' Add ECS Service Role to template ''' self.cfn_template.add_resource( Role( title=constants.SERVICE_ROLE, AssumeRolePolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal('Service', ['ecs.amazonaws.com'])) ]), Policies=[ Policy( PolicyName='AmazonEC2ContainerServiceRole', PolicyDocument=PolicyDocument(Statement=[ Statement( Effect=Allow, Action=[ Action('ec2', 'AuthorizeSecurityGroupIngress'), Action('ec2', 'Describe*'), Action( 'elasticloadbalancing', 'DeregisterInstancesFromLoadBalancer'), Action('ecelasticloadbalancing2', 'Describe*'), Action( 'elasticloadbalancing', 'RegisterInstancesWithLoadBalancer'), Action('elasticloadbalancing', 'DeregisterTargets'), Action('elasticloadbalancing', 'DescribeTargetGroups'), Action('elasticloadbalancing', 'DescribeTargetHealth'), Action('elasticloadbalancing', 'RegisterTargets') ], Resource=['*']) ])) ])) return self.cfn_template
def init_codecommit_permission(self, permission_config, assume_role_res): statement_list = [] readwrite_repo_arns = [] readonly_repo_arns = [] readonly_codecommit_actions = [ Action('codecommit', 'BatchGet*'), Action('codecommit', 'BatchDescribe*'), Action('codecommit', 'List*'), Action('codecommit', 'GitPull*') ] readwrite_codecommit_actions = [ Action('codecommit', '*'), ] for repo_config in permission_config.repositories: repo_account_id = self.paco_ctx.get_ref(repo_config.codecommit + '.account_id') if repo_account_id != self.account_id: continue codecommit_repo_arn = self.paco_ctx.get_ref( repo_config.codecommit + '.arn') if repo_config.permission == 'ReadWrite': if codecommit_repo_arn not in readwrite_repo_arns: readwrite_repo_arns.append(codecommit_repo_arn) elif repo_config.permission == 'ReadOnly': if codecommit_repo_arn not in readonly_repo_arns: readonly_repo_arns.append(codecommit_repo_arn) if len(readwrite_repo_arns) > 0: statement_list.append( Statement(Sid='CodeCommitReadWrite', Effect=Allow, Action=readwrite_codecommit_actions, Resource=readwrite_repo_arns)) if len(readonly_repo_arns) > 0: statement_list.append( Statement(Sid='CodeCommitReadOnly', Effect=Allow, Action=readonly_codecommit_actions, Resource=readonly_repo_arns)) statement_list.append( Statement(Effect=Allow, Action=[Action('codecommit', 'ListRepositories')], Resource=['*'])) managed_policy_res = troposphere.iam.ManagedPolicy( title=self.create_cfn_logical_id("CodeCommitPolicy"), PolicyDocument=PolicyDocument(Version="2012-10-17", Statement=statement_list), Roles=[troposphere.Ref(assume_role_res)]) self.template.add_resource(managed_policy_res)
def allow_get_secrets(secret_names: Iterable[str]) -> Policy: return Policy('AllowGetAccountSecrets', PolicyName='AllowGetAccountSecrets', PolicyDocument=PolicyDocument(Statement=[ Statement( Action=[awacs.secretsmanager.GetSecretValue], Effect=Allow, Resource=[Ref(f'Secret{n}') for n in secret_names], ) ]))
def test_invalid_property(self): with self.assertRaises(AttributeError) as exc: # statement should be Statement PolicyDocument(Version='2012-10-17', statement=[]) self.assertEqual( exc.exception.args[0], "'awacs.aws.PolicyDocument' object does not support attribute " "'statement'" )
def add_ecs_task_role(self): ''' Add ECS Task Role to template ''' self.cfn_template.add_resource( Role( title=constants.TASK_ROLE, AssumeRolePolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal('Service', ['ecs-tasks.amazonaws.com'])) ]), Policies=[ Policy(PolicyName='ECSTaskDefinitionContainerRole', PolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[ Action('s3', 'GetObject'), Action('kms', 'Encrypt'), Action('kms', 'Decrypt') ], Resource=['*']) ])), Policy( PolicyName='DemoAppContainerRole', PolicyDocument=PolicyDocument(Statement=[ Statement(Effect=Allow, Action=[ Action('dynamodb', 'BatchGetItem'), Action('dynamodb', 'BatchWriteItem'), Action('dynamodb', 'GetItem'), Action('dynamodb', 'ListTables'), Action('dynamodb', 'PutItem'), Action('dynamodb', 'Query'), Action('dynamodb', 'Scan'), Action('dynamodb', 'UpdateItem'), Action('dynamodb', 'DeleteItem') ], Resource=['*']) ])) ])) return self.cfn_template
def test_policy_document_equality(self): one = PolicyDocument( Version="2012-10-17", Statement=[ Statement( Effect="Allow", Action=[ Action("autoscaling", "DescribeLaunchConfigurations"), ], Resource=["*"], ) ], ) one_again = PolicyDocument( Version="2012-10-17", Statement=[ Statement( Effect="Allow", Action=[ Action("autoscaling", "DescribeLaunchConfigurations"), ], Resource=["*"], ) ], ) two = PolicyDocument( Version="2012-10-17", Statement=[ Statement( Effect="Allow", Action=[ Action("ec2", "DescribeInstances"), ], Resource=["*"], ) ], ) self.assertEqualWithHash(one, one_again) self.assertNotEqualWithHash(one, two)
def codepipeline_policy_document(input_kwargs, build_data): user = "******" account = build_data["account_id"] bucket_arn = "arn:aws:s3:::{0}".format(input_kwargs["name"]) pd = PolicyDocument( Version="2012-10-17", Id="CodePipeline-Permissions", Statement=[ Statement(Effect=Allow, Principal=Principal("AWS", [IAM_ARN(user, '', account)]), Action=[ codebuild.StartBuild, codebuild.BatchGetBuilds, codedeploy.CreateDeployment, codedeploy.GetApplicationRevision, codedeploy.GetDeployment, codedeploy.GetDeploymentConfig, codedeploy.RegisterApplicationRevision, iam.PassRole, iam.GetRole, codecommit.GitPull ], Resource=['*']), Statement(Effect=Allow, Principal=Principal("AWS", [IAM_ARN(user, '', account)]), Action=[ s3.CreateBucket, s3.GetObject, s3.ListAccessPoints, s3.ListAllMyBuckets, s3.ListBucket, s3.ListBucketByTags, s3.ListBucketMultipartUploads, s3.ListBucketVersions, s3.ListJobs, s3.ListMultipartUploadParts, s3.ListObjects, s3.PutObject, s3.GetBucketAcl, s3.GetBucketLocation, s3.GetObjectVersion ], Resource=[bucket_arn]) ]) input_kwargs["policy"] = pd.to_json() return input_kwargs
def add_module_bucket(self: Template): self._bucket = self.add_resource( s3.Bucket('TerraformModules', AccessControl='Private', BucketEncryption=s3.BucketEncryption( ServerSideEncryptionConfiguration=[ s3.ServerSideEncryptionRule( ServerSideEncryptionByDefault=s3. ServerSideEncryptionByDefault( SSEAlgorithm='AES256')) ]), PublicAccessBlockConfiguration=s3. PublicAccessBlockConfiguration( BlockPublicAcls=True, BlockPublicPolicy=True, IgnorePublicAcls=True, RestrictPublicBuckets=True))) self.add_resource( s3.BucketPolicy( 'TerraformModulesBucketPolicy', Bucket=Ref(self._bucket), PolicyDocument=PolicyDocument( Version='2012-10-17', Statement=[ Statement( Effect=Deny, Action=[Action('s3', 'GetObject')], Principal=Principal('*'), Resource=[ Join( '', ['arn:aws:s3:::', Ref(self._bucket), '/*']) ], Condition=Condition( Bool({'aws:SecureTransport': False}))), Statement( Effect=Deny, Action=[Action('s3', 'GetObject')], Principal=Principal('*'), Resource=[ Join( '', ['arn:aws:s3:::', Ref(self._bucket), '/*']) ], Condition=Condition( Bool({'aws:SecureTransport': False}))) ]), ))
def add_lambda_execution_role( self, name='LambdaExecutionRole', # type: str function_name='' # type: str ): # noqa: E124 # type: (...) -> iam.Role """Create the Lambda@Edge execution role.""" variables = self.get_variables() lambda_resource = Join('', [ 'arn:', Partition, ':logs:*:', AccountId, ':log-group:/aws/lambda/', StackName, '-%s-*' % function_name ]) edge_resource = Join('', [ 'arn:', Partition, ':logs:*:', AccountId, ':log-group:/aws/lambda/*.', StackName, '-%s-*' % function_name, ]) return self.template.add_resource( iam.Role( name, AssumeRolePolicyDocument=make_simple_assume_policy( 'lambda.amazonaws.com', 'edgelambda.amazonaws.com'), PermissionsBoundary=(variables['RoleBoundaryArn'] if self.role_boundary_specified else NoValue), Policies=[ iam.Policy(PolicyName="LambdaLogCreation", PolicyDocument=PolicyDocument( Version='2012-10-17', Statement=[ Statement(Action=[ awacs.logs.CreateLogGroup, awacs.logs.CreateLogStream, awacs.logs.PutLogEvents ], Effect=Allow, Resource=[ lambda_resource, edge_resource ]) ])), ], ))
def codebuild_policy_document(input_kwargs, build_data): user = "******" account = build_data["account_id"] region = build_data["region"] logs_arn = [ "arn:aws:logs:*:*:log-group:/aws/rds/*:log-stream:*", "arn:aws:logs:*:*:log-group:/aws/docdb/*:log-stream:*", "arn:aws:logs:*:*:log-group:/aws/neptune/*:log-stream:*" ] ec2_arn = ["arn:aws:kinesis:*:*:stream/aws-rds-das-*"] pd = PolicyDocument( Version="2012-10-17", Id="RDS-Monitoring-Permissions", Statement=[ Statement(Effect=Allow, Principal=Principal("AWS", [IAM_ARN(user, '', account)]), Action=[ logs.CreateLogDelivery, logs.GetLogDelivery, logs.UpdateLogDelivery, logs.DeleteLogDelivery, logs.ListLogDeliveries ], Resource=[logs_arn]), Statement(Effect=Allow, Principal=Principal("AWS", [IAM_ARN(user, '', account)]), Action=[ kinesis.CreateStream, kinesis.PutRecord, kinesis.PutRecords, kinesis.DescribeStream, kinesis.SplitShard, kinesis.MergeShards, kinesis.DeleteStream, kinesis.UpdateShardCount ], Resource=["arn:aws:kinesis:*:*:stream/aws-rds-das-*"]) ]) input_kwargs["policy"] = pd.to_json() return input_kwargs