Пример #1
0
    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')
                                    ])
                            ]))
                ]))
Пример #2
0
def get_policy_code_build_general_access(policy_name):

    return iam.Policy(
        PolicyName=policy_name,
        PolicyDocument=awacs.aws.PolicyDocument(
            Version="2012-10-17",
            Id="%sId" % policy_name,
            Statement=[
                awacs.aws.Statement(
                    Effect=awacs.aws.Allow,
                    Action=[
                        awacs.aws.Action("cloudformation", "*"),
                        awacs.aws.Action("ec2", "*"),
                        awacs.aws.Action("route53", "*"),
                        awacs.aws.Action("iam", "*"),
                        awacs.aws.Action("elasticloadbalancing", "*"),
                        awacs.aws.Action("s3", "*"),
                        awacs.aws.Action("autoscaling", "*"),
                        awacs.aws.Action("apigateway", "*"),
                        awacs.aws.Action("cloudwatch", "*"),
                        awacs.aws.Action("cloudfront", "*"),
                        awacs.aws.Action("codepipeline", "*"),
                        awacs.aws.Action("rds", "*"),
                        awacs.aws.Action("dynamodb", "*"),
                        awacs.aws.Action("lambda", "*"),
                        awacs.aws.Action("sqs", "*"),
                        awacs.aws.Action("events", "*"),
                        awacs.aws.Action("logs", "*"),
                        awacs.aws.Action("ecr", "*"),
                        awacs.iam.PassRole,
                    ],
                    Resource=["*"]),
                awacs.aws.Statement(
                    Effect=awacs.aws.Allow,
                    Action=[
                        awacs.logs.CreateLogGroup,
                        awacs.logs.CreateLogStream,
                        awacs.logs.PutLogEvents,
                    ],
                    # TODO: restrict more accurately
                    Resource=["*"]),
                awacs.aws.Statement(Effect=awacs.aws.Allow,
                                    Action=[
                                        awacs.s3.HeadBucket,
                                    ],
                                    Resource=['*']),
                awacs.aws.Statement(
                    Effect=awacs.aws.Allow,
                    Action=[
                        awacs.aws.Action('ec2', 'Describe*'),
                    ],
                    # TODO: restrict more accurately.  What does codebuild need?
                    Resource=["*"]),
                cumulus.policies.POLICY_VPC_CONFIG
            ]))
Пример #3
0
    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
                                                 ])
                                   ])),
                ],
            ))
Пример #4
0
def get_policy_cloudformation_general_access(policy_name):
    # TODO: Return policy with permissions:
    # 1. Full Cloudformation access to stacks prefixed with application name
    # 2. IAM access (currently using unlimited access, but this seems like it could be limited a bit)
    return iam.Policy(
        PolicyName=policy_name,
        PolicyDocument=awacs.aws.PolicyDocument(
            Version="2012-10-17",
            Id="%sId" % policy_name,
            Statement=[
                awacs.aws.Statement(
                    Effect=awacs.aws.Allow,
                    Action=[
                        awacs.aws.Action("cloudformation", "*"),
                        awacs.aws.Action("ec2", "*"),
                        awacs.aws.Action("route53", "*"),
                        awacs.aws.Action("iam", "*"),
                        awacs.aws.Action("elasticloadbalancing", "*"),
                        awacs.aws.Action("s3", "*"),
                        awacs.aws.Action("autoscaling", "*"),
                        awacs.aws.Action("apigateway", "*"),
                        awacs.aws.Action("cloudwatch", "*"),
                        awacs.aws.Action("cloudfront", "*"),
                        awacs.aws.Action("rds", "*"),
                        awacs.aws.Action("dynamodb", "*"),
                        awacs.aws.Action("lambda", "*"),
                        awacs.aws.Action("sqs", "*"),
                        awacs.aws.Action("events", "*"),
                        awacs.aws.Action("ecr", "*"),
                        awacs.iam.PassRole,
                    ],
                    Resource=["*"]),
                awacs.aws.Statement(
                    Effect=awacs.aws.Allow,
                    Action=[
                        awacs.logs.CreateLogGroup,
                        awacs.logs.CreateLogStream,
                        awacs.logs.PutLogEvents,
                    ],
                    # TODO: restrict more accurately
                    Resource=["*"])
            ]))
Пример #5
0
    def _get_replicated_lambda_state_machine_role(
        self,
        remover_function,  # type: Dict[str, Union[awslambda.Function, iam.Role, Any]]
        self_destruct_function,  # type: Dict[str, Union[awslambda.Function, iam.Role, Any]]
    ):
        # type (...) -> iam.Role
        variables = self.get_variables()
        entity = Join(".", ["states", Region, "amazonaws.com"])

        return self.template.add_resource(
            iam.Role(
                "StateMachineRole",
                AssumeRolePolicyDocument=make_simple_assume_policy(entity),
                PermissionsBoundary=(
                    variables["RoleBoundaryArn"]
                    if self.role_boundary_specified
                    else NoValue
                ),
                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"),
                                    ],
                                )
                            ],
                        ),
                    )
                ],
            )
        )
Пример #6
0
    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
                                                  # TODO remove after dropping python 2
                                                  ):  # pylint: disable=bad-continuation
        # type (...) -> iam.Role
        variables = self.get_variables()
        entity = Join('.', ['states', Region, 'amazonaws.com'])

        return self.template.add_resource(
            iam.Role(
                'StateMachineRole',
                AssumeRolePolicyDocument=make_simple_assume_policy(entity),
                PermissionsBoundary=(
                    variables['RoleBoundaryArn'] if self.role_boundary_specified
                    else NoValue
                ),
                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')
                                    ]
                                )
                            ]
                        )
                    )
                ]
            )
        )
Пример #7
0
 def add_role(self):
     name, tags = self._name_tags('role')
     self.role = self.t.add_resource(
         iam.Role(
             name,
             AssumeRolePolicyDocument=Policy(
                 Statement=[
                     Statement(
                         Action=[awacs.sts.AssumeRole],
                         Effect=Allow,
                         Principal=Principal('Service', 'ec2.amazonaws.com'),
                         Sid=name,  # redundant?
                     ),
                 ],
             ),
             ManagedPolicyArns=['arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess'],
             Path='/',
             Policies=[iam.Policy(
                 name + 'Policy',
                 PolicyDocument=Policy(
                     Statement=[
                         Statement(
                             Action=[
                                 awacs.s3.GetObject,
                                 awacs.s3.ListBucket,
                             ],
                             Effect=Allow,
                             Resource=[awacs.s3.ARN(self.aws['s3.bucket']),
                                       awacs.s3.ARN(self.aws['s3.bucket'] + '/*')],
                         ),
                     ],
                 ),
                 PolicyName=name + 'Policy',
             )],
             # Doesn't support: Tags=Tags(**tags)
         ))
Пример #8
0
    def _get_replicated_lambda_remover_lambda(self):
        # type: () -> Dict[str, Any]
        res = {}
        res['role'] = self.template.add_resource(
            iam.Role(
                'ReplicatedLambdaRemoverRole',
                AssumeRolePolicyDocument=make_simple_assume_policy(
                    'lambda.amazonaws.com'),
                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=[
                                               Join('', [
                                                   'arn:', Partition,
                                                   ':logs:*:', AccountId,
                                                   ':log-group:/aws/lambda/',
                                                   StackName,
                                                   '-ReplicatedLambdaRemover-*'
                                               ])
                                           ])
                                   ])),
                    iam.Policy(PolicyName="DeleteLambda",
                               PolicyDocument=PolicyDocument(
                                   Version="2012-10-17",
                                   Statement=[
                                       Statement(Action=[
                                           awacs.awslambda.DeleteFunction
                                       ],
                                                 Effect=Allow,
                                                 Resource=self.get_variables()
                                                 ['function_arns'])
                                   ]))
                ],
            ))

        self.template.add_output(
            Output(
                'ReplicatedLambdaRemoverRole',
                Description='The name of the Replicated Lambda Remover Role',
                Value=res['role'].ref()))

        res['function'] = self.template.add_resource(
            awslambda.Function(
                'ReplicatedLambdaRemover',
                Code=awslambda.Code(
                    ZipFile=read_value_from_path('file://' + os.path.join(
                        os.path.dirname(__file__),
                        'templates/replicated_lambda_remover.template.py'))),
                Description=
                "Checks for Replicated Lambdas created during the main stack and "
                "deletes them when they are ready.",
                Handler='index.handler',
                Role=res['role'].get_att('Arn'),
                Runtime='python3.7'))

        self.template.add_output(
            Output('ReplicatedLambdaRemoverArn',
                   Description='The ARN of the Replicated Function',
                   Value=res['function'].get_att('Arn')))

        return res
Пример #9
0
    def _get_self_destruct(self, replicated_lambda_remover):
        # type: (Dict[str, Union[awslambda.Function, Any]]) -> Dict[str, Any]
        res = {}
        variables = self.get_variables()

        res['role'] = self.template.add_resource(
            iam.Role(
                'SelfDestructRole',
                AssumeRolePolicyDocument=make_simple_assume_policy(
                    'lambda.amazonaws.com'),
                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=[
                                               Join('', [
                                                   'arn:', Partition,
                                                   ':logs:*:', AccountId,
                                                   ':log-group:/aws/lambda/',
                                                   StackName, '-SelfDestruct-*'
                                               ])
                                           ])
                                   ])),
                    iam.Policy(
                        PolicyName="DeleteStateMachine",
                        PolicyDocument=PolicyDocument(
                            Version="2012-10-17",
                            Statement=[
                                Statement(
                                    Action=[awacs.states.DeleteStateMachine],
                                    Effect=Allow,
                                    Resource=[
                                        # StateMachine
                                        Join('', [
                                            'arn:', Partition, ':states:',
                                            Region, ':', AccountId,
                                            ':stateMachine:StaticSiteCleanup-',
                                            variables['stack_name']
                                        ])
                                    ])
                            ])),
                    iam.Policy(PolicyName="DeleteRolesAndPolicies",
                               PolicyDocument=PolicyDocument(
                                   Version="2012-10-17",
                                   Statement=[
                                       Statement(
                                           Action=[
                                               awacs.iam.DeleteRolePolicy,
                                               awacs.iam.DeleteRole
                                           ],
                                           Effect=Allow,
                                           Resource=[
                                               Join('', [
                                                   'arn:', Partition, ':iam::',
                                                   AccountId, ':role/',
                                                   StackName, '-*'
                                               ]),
                                           ])
                                   ])),
                    iam.Policy(
                        PolicyName="DeleteLambdas",
                        PolicyDocument=PolicyDocument(
                            Version="2012-10-17",
                            Statement=[
                                Statement(
                                    Action=[awacs.awslambda.DeleteFunction],
                                    Effect=Allow,
                                    Resource=[
                                        Join('', [
                                            'arn:', Partition, ':lambda:',
                                            Region, ':', AccountId,
                                            ':function:%s-SelfDestruct-*' %
                                            (variables['stack_name'])
                                        ]),
                                        replicated_lambda_remover['function'].
                                        get_att('Arn')
                                    ])
                            ])),
                    iam.Policy(
                        PolicyName="DeleteStack",
                        PolicyDocument=PolicyDocument(
                            Version="2012-10-17",
                            Statement=[
                                Statement(
                                    Action=[awacs.cloudformation.DeleteStack],
                                    Effect=Allow,
                                    Resource=[
                                        Join('', [
                                            'arn:', Partition,
                                            ':cloudformation:', Region, ':',
                                            AccountId,
                                            ':stack/%s/*' %
                                            (variables['stack_name'])
                                        ])
                                    ])
                            ]))
                ],
            ))

        self.template.add_output(
            Output('SelfDestructLambdaRole',
                   Description='The name of the Self Destruct Role',
                   Value=res['role'].ref()))

        res['function'] = self.template.add_resource(
            awslambda.Function(
                'SelfDestruct',
                Code=awslambda.Code(ZipFile=read_value_from_path(
                    'file://' +
                    os.path.join(os.path.dirname(__file__),
                                 'templates/self_destruct.template.py'))),
                Description=
                "Issues a Delete Stack command to the Cleanup stack",
                Handler='index.handler',
                Role=res['role'].get_att('Arn'),
                Runtime='python3.7'))

        self.template.add_output(
            Output('SelfDestructLambdaArn',
                   Description='The ARN of the Replicated Function',
                   Value=res['function'].get_att('Arn')))

        return res
Пример #10
0
    def handle(self, chain_context):
        """
        This step adds in the shell of a pipeline.
         * s3 bucket
         * policies for the bucket and pipeline
         * your next step in the chain MUST be a source stage
        :param chain_context:
        :return:
        """

        if self.create_bucket:
            pipeline_bucket = Bucket(
                "PipelineBucket%s" % chain_context.instance_name,
                BucketName=self.bucket_name,
                VersioningConfiguration=VersioningConfiguration(
                    Status="Enabled"))
            chain_context.template.add_resource(pipeline_bucket)

        default_bucket_policies = self.get_default_bucket_policy_statements(
            self.bucket_name)

        if self.bucket_policy_statements:
            bucket_access_policy = self.get_bucket_policy(
                pipeline_bucket=self.bucket_name,
                bucket_policy_statements=self.bucket_policy_statements,
            )
            chain_context.template.add_resource(bucket_access_policy)

        pipeline_bucket_access_policy = iam.ManagedPolicy(
            "PipelineBucketAccessPolicy",
            Path='/managed/',
            PolicyDocument=awacs.aws.PolicyDocument(
                Version="2012-10-17",
                Id="bucket-access-policy%s" % chain_context.instance_name,
                Statement=default_bucket_policies))

        chain_context.metadata[cumulus.steps.dev_tools.
                               META_PIPELINE_BUCKET_NAME] = self.bucket_name
        chain_context.metadata[
            cumulus.steps.dev_tools.META_PIPELINE_BUCKET_POLICY_REF] = Ref(
                pipeline_bucket_access_policy)

        # TODO: this can be cleaned up by using a policytype and passing in the pipeline role it should add itself to.
        pipeline_policy = iam.Policy(
            PolicyName="%sPolicy" % self.name,
            PolicyDocument=awacs.aws.PolicyDocument(
                Version="2012-10-17",
                Id="PipelinePolicy",
                Statement=[
                    awacs.aws.Statement(
                        Effect=awacs.aws.Allow,
                        # TODO: actions here could be limited more
                        Action=[awacs.aws.Action("s3", "*")],
                        Resource=[
                            troposphere.Join(
                                '', [awacs.s3.ARN(), self.bucket_name, "/*"]),
                            troposphere.Join('', [
                                awacs.s3.ARN(),
                                self.bucket_name,
                            ]),
                        ],
                    ),
                    awacs.aws.Statement(
                        Effect=awacs.aws.Allow,
                        Action=[awacs.aws.Action("kms", "*")],
                        Resource=['*'],
                    ),
                    awacs.aws.Statement(
                        Effect=awacs.aws.Allow,
                        Action=[
                            awacs.aws.Action("cloudformation", "*"),
                            awacs.aws.Action("codebuild", "*"),
                        ],
                        # TODO: restrict more accurately
                        Resource=["*"]),
                    awacs.aws.Statement(
                        Effect=awacs.aws.Allow,
                        Action=[
                            awacs.codecommit.GetBranch,
                            awacs.codecommit.GetCommit,
                            awacs.codecommit.UploadArchive,
                            awacs.codecommit.GetUploadArchiveStatus,
                            awacs.codecommit.CancelUploadArchive
                        ],
                        Resource=["*"]),
                    awacs.aws.Statement(Effect=awacs.aws.Allow,
                                        Action=[awacs.iam.PassRole],
                                        Resource=["*"]),
                    awacs.aws.Statement(
                        Effect=awacs.aws.Allow,
                        Action=[awacs.aws.Action("lambda", "*")],
                        Resource=["*"])
                ],
            ))

        pipeline_service_role = iam.Role(
            "PipelineServiceRole",
            Path="/",
            AssumeRolePolicyDocument=awacs.aws.Policy(Statement=[
                awacs.aws.Statement(Effect=awacs.aws.Allow,
                                    Action=[awacs.sts.AssumeRole],
                                    Principal=awacs.aws.Principal(
                                        'Service',
                                        "codepipeline.amazonaws.com"))
            ]),
            Policies=[pipeline_policy] + self.pipeline_policies)

        generic_pipeline = codepipeline.Pipeline(
            "Pipeline",
            RoleArn=troposphere.GetAtt(pipeline_service_role, "Arn"),
            Stages=[],
            ArtifactStore=codepipeline.ArtifactStore(
                Type="S3",
                Location=self.bucket_name,
            )
            # TODO: optionally add kms key here
        )

        if self.bucket_kms_key_arn:
            encryption_config = codepipeline.EncryptionKey(
                "ArtifactBucketKmsKey",
                Id=self.bucket_kms_key_arn,
                Type='KMS',
            )
            generic_pipeline.ArtifactStore.EncryptionKey = encryption_config

        pipeline_output = troposphere.Output(
            "PipelineName",
            Description="Code Pipeline",
            Value=Ref(generic_pipeline),
        )
        pipeline_bucket_output = troposphere.Output(
            "PipelineBucket",
            Description="Name of the input artifact bucket for the pipeline",
            Value=self.bucket_name,
        )

        chain_context.template.add_resource(pipeline_bucket_access_policy)
        chain_context.template.add_resource(pipeline_service_role)
        chain_context.template.add_resource(generic_pipeline)
        chain_context.template.add_output(pipeline_output)
        chain_context.template.add_output(pipeline_bucket_output)
Пример #11
0
    def add_lambda_execution_role(self,
                                  name: str = "LambdaExecutionRole",
                                  function_name: str = "") -> iam.Role:
        """Create the Lambda@Edge execution role.

        Args:
            name: Name for the Lambda Execution Role.
            function_name: Name of the Lambda Function the Role will be
                attached to.

        """
        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=(self.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],
                                )
                            ],
                        ),
                    ),
                ],
            ))
Пример #12
0
    def create_template(self):
        """Create template (main function called by Stacker)."""
        template = self.template
        variables = self.get_variables()
        template.add_version("2010-09-09")
        template.add_description("Kubernetes Master via EKS - V1.0.0")

        # Resources
        ccpsecuritygroup = template.add_resource(
            ec2.SecurityGroup(
                "ClusterControlPlaneSecurityGroup",
                GroupDescription="Cluster communication with worker nodes",
                Tags=[
                    {
                        "Key": Sub("kubernetes.io/cluster/${EksClusterName}"),
                        "Value": "owned",
                    },
                    {
                        "Key": "Product",
                        "Value": "Kubernetes"
                    },
                    {
                        "Key": "Project",
                        "Value": "eks"
                    },
                    {
                        "Key": "Name",
                        "Value": Sub("${EksClusterName}-sg-worker-nodes")
                    },
                ],
                VpcId=variables["VPC"].ref,
            ))
        template.add_output(
            Output(
                ccpsecuritygroup.title,
                Description="Cluster communication with worker nodes",
                Export=Export(
                    Sub("${AWS::StackName}-ControlPlaneSecurityGroup")),
                Value=ccpsecuritygroup.ref(),
            ))

        eksservicerole = template.add_resource(
            iam.Role(
                "EksServiceRole",
                AssumeRolePolicyDocument=make_simple_assume_policy(
                    "eks.amazonaws.com"),
                ManagedPolicyArns=[
                    IAM_POLICY_ARN_PREFIX + "AmazonEKSClusterPolicy"
                ],
                Policies=[
                    iam.Policy(
                        PolicyName="EksServiceRolePolicy",
                        PolicyDocument=PolicyDocument(Statement=[
                            Statement(
                                Action=[
                                    awacs.iam.CreateServiceLinkedRole,
                                    awacs.iam.PutRolePolicy,
                                ],
                                Condition=Condition(
                                    StringLike(
                                        "iam:AWSServiceName",
                                        "elasticloadbalancing.amazonaws.com",
                                    )),
                                Effect=Allow,
                                Resource=[
                                    Sub("arn:aws:iam::${AWS::AccountId}:role/"
                                        "aws-service-role/"
                                        "elasticloadbalancing.amazonaws.com/"
                                        "AWSServiceRoleForElasticLoadBalancing*"
                                        )
                                ],
                            )
                        ]),
                    )
                ],
            ))

        ekscluster = template.add_resource(
            eks.Cluster(
                "EksCluster",
                Name=variables["EksClusterName"].ref,
                Version=variables["EksVersion"].ref,
                RoleArn=eksservicerole.get_att("Arn"),
                ResourcesVpcConfig=eks.ResourcesVpcConfig(
                    SecurityGroupIds=[ccpsecuritygroup.ref()],
                    SubnetIds=variables["EksSubnets"].ref,
                ),
            ))
        template.add_output(
            Output(
                "%sName" % ekscluster.title,
                Description="EKS Cluster Name",
                Export=Export(
                    Sub("${AWS::StackName}-%sName" % ekscluster.title)),
                Value=ekscluster.ref(),
            ))
        template.add_output(
            Output(
                "%sEndpoint" % ekscluster.title,
                Description="EKS Cluster Endpoint",
                Export=Export(
                    Sub("${AWS::StackName}-%sEndpoint" % ekscluster.title)),
                Value=ekscluster.get_att("Endpoint"),
            ))

        # Additional Outputs
        template.add_output(
            Output(
                "VpcId",
                Description="EKS Cluster VPC Id",
                Export=Export(Sub("${AWS::StackName}-VpcId")),
                Value=variables["VPC"].ref,
            ))
        template.add_output(
            Output(
                "Subnets",
                Description="EKS Cluster Subnets",
                Export=Export(Sub("${AWS::StackName}-Subnets")),
                Value=Join(",", variables["EksSubnets"].ref),
            ))
Пример #13
0
    def create_template(self) -> None:
        """Create template."""
        template = self.template

        bucket_arn = Sub("arn:aws:s3:::${CFNginBucket}*")
        objects_arn = Sub("arn:aws:s3:::${CFNginBucket}*/*")
        cloudformation_scope = Sub(
            "arn:aws:cloudformation:*:${AWS::AccountId}:stack/${Namespace}-*")
        changeset_scope = "*"

        # This represents the precise IAM permissions that cfngin itself
        # needs.
        cfngin_policy = iam.Policy(
            PolicyName="CFNgin",
            PolicyDocument=Policy(Statement=[
                Statement(
                    Effect="Allow",
                    Resource=["*"],
                    Action=[awacs.s3.ListAllMyBuckets],
                ),
                Statement(
                    Effect="Allow",
                    Resource=[bucket_arn],
                    Action=[
                        awacs.s3.ListBucket,
                        awacs.s3.GetBucketLocation,
                        awacs.s3.CreateBucket,
                        awacs.s3.DeleteBucket,
                    ],
                ),
                Statement(
                    Effect="Allow",
                    Resource=[bucket_arn],
                    Action=[
                        awacs.s3.GetObject,
                        awacs.s3.GetObjectAcl,
                        awacs.s3.PutObject,
                        awacs.s3.PutObjectAcl,
                    ],
                ),
                Statement(
                    Effect="Allow",
                    Resource=[objects_arn],
                    Action=[awacs.s3.DeleteObject],
                ),
                Statement(
                    Effect="Allow",
                    Resource=[changeset_scope],
                    Action=[
                        awacs.cloudformation.DescribeChangeSet,
                        awacs.cloudformation.ExecuteChangeSet,
                        awacs.cloudformation.DeleteChangeSet,
                    ],
                ),
                Statement(
                    Effect="Deny",
                    Resource=[Ref("AWS::StackId")],
                    Action=[awacs.cloudformation.Action("*")],
                ),
                Statement(
                    Effect="Allow",
                    Resource=[cloudformation_scope],
                    Action=[
                        awacs.cloudformation.GetTemplate,
                        awacs.cloudformation.CreateChangeSet,
                        awacs.cloudformation.DeleteChangeSet,
                        awacs.cloudformation.DeleteStack,
                        awacs.cloudformation.CreateStack,
                        awacs.cloudformation.UpdateStack,
                        awacs.cloudformation.SetStackPolicy,
                        awacs.cloudformation.DescribeStacks,
                        awacs.cloudformation.DescribeStackEvents,
                    ],
                ),
            ]),
        )

        principal = AWSPrincipal(Ref("AWS::AccountId"))
        role = template.add_resource(
            iam.Role(
                "FunctionalTestRole",
                AssumeRolePolicyDocument=Policy(Statement=[
                    Statement(
                        Effect="Allow",
                        Action=[awacs.sts.AssumeRole],
                        Principal=principal,
                    )
                ]),
                Policies=[cfngin_policy],
            ))

        assumerole_policy = iam.Policy(
            PolicyName="AssumeRole",
            PolicyDocument=Policy(Statement=[
                Statement(
                    Effect="Allow",
                    Resource=[GetAtt(role, "Arn")],
                    Action=[awacs.sts.AssumeRole],
                )
            ]),
        )

        user = template.add_resource(
            iam.User("FunctionalTestUser",
                     Policies=[cfngin_policy, assumerole_policy]))

        key = template.add_resource(
            iam.AccessKey("FunctionalTestKey", Serial=1, UserName=Ref(user)))

        template.add_output(Output("User", Value=Ref(user)))
        template.add_output(Output("AccessKeyId", Value=Ref(key)))
        template.add_output(
            Output("SecretAccessKey",
                   Value=GetAtt("FunctionalTestKey", "SecretAccessKey")))
        template.add_output(
            Output("FunctionalTestRole", Value=GetAtt(role, "Arn")))
Пример #14
0
    def _get_replicated_lambda_remover_lambda(self):
        # type: () -> Dict[str, Any]
        res = {}
        variables = self.get_variables()
        res["role"] = self.template.add_resource(
            iam.Role(
                "ReplicatedLambdaRemoverRole",
                AssumeRolePolicyDocument=make_simple_assume_policy(
                    "lambda.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=[
                                        Join(
                                            "",
                                            [
                                                "arn:",
                                                Partition,
                                                ":logs:*:",
                                                AccountId,
                                                ":log-group:/aws/lambda/",
                                                StackName,
                                                "-ReplicatedLambdaRemover-*",
                                            ],
                                        )
                                    ],
                                )
                            ],
                        ),
                    ),
                    iam.Policy(
                        PolicyName="DeleteLambda",
                        PolicyDocument=PolicyDocument(
                            Version="2012-10-17",
                            Statement=[
                                Statement(
                                    Action=[awacs.awslambda.DeleteFunction],
                                    Effect=Allow,
                                    Resource=self.get_variables()["function_arns"],
                                )
                            ],
                        ),
                    ),
                ],
            )
        )

        self.template.add_output(
            Output(
                "ReplicatedLambdaRemoverRole",
                Description="The name of the Replicated Lambda Remover Role",
                Value=res["role"].ref(),
            )
        )

        res["function"] = self.template.add_resource(
            awslambda.Function(
                "ReplicatedLambdaRemover",
                Code=awslambda.Code(
                    ZipFile=read_value_from_path(
                        "file://"
                        + os.path.join(
                            os.path.dirname(__file__),
                            "templates/replicated_lambda_remover.template.py",
                        )
                    )
                ),
                Description="Checks for Replicated Lambdas created during the main stack and "
                "deletes them when they are ready.",
                Handler="index.handler",
                Role=res["role"].get_att("Arn"),
                Runtime="python3.7",
            )
        )

        self.template.add_output(
            Output(
                "ReplicatedLambdaRemoverArn",
                Description="The ARN of the Replicated Function",
                Value=res["function"].get_att("Arn"),
            )
        )

        return res
Пример #15
0
    def _get_self_destruct(self, replicated_lambda_remover):
        # type: (Dict[str, Union[awslambda.Function, Any]]) -> Dict[str, Any]
        res = {}
        variables = self.get_variables()

        res["role"] = self.template.add_resource(
            iam.Role(
                "SelfDestructRole",
                AssumeRolePolicyDocument=make_simple_assume_policy(
                    "lambda.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=[
                                        Join(
                                            "",
                                            [
                                                "arn:",
                                                Partition,
                                                ":logs:*:",
                                                AccountId,
                                                ":log-group:/aws/lambda/",
                                                StackName,
                                                "-SelfDestruct-*",
                                            ],
                                        )
                                    ],
                                )
                            ],
                        ),
                    ),
                    iam.Policy(
                        PolicyName="DeleteStateMachine",
                        PolicyDocument=PolicyDocument(
                            Version="2012-10-17",
                            Statement=[
                                Statement(
                                    Action=[awacs.states.DeleteStateMachine],
                                    Effect=Allow,
                                    Resource=[
                                        # StateMachine
                                        Join(
                                            "",
                                            [
                                                "arn:",
                                                Partition,
                                                ":states:",
                                                Region,
                                                ":",
                                                AccountId,
                                                ":stateMachine:StaticSiteCleanup-",
                                                variables["stack_name"],
                                            ],
                                        )
                                    ],
                                )
                            ],
                        ),
                    ),
                    iam.Policy(
                        PolicyName="DeleteRolesAndPolicies",
                        PolicyDocument=PolicyDocument(
                            Version="2012-10-17",
                            Statement=[
                                Statement(
                                    Action=[
                                        awacs.iam.DeleteRolePolicy,
                                        awacs.iam.DeleteRole,
                                    ],
                                    Effect=Allow,
                                    Resource=[
                                        Join(
                                            "",
                                            [
                                                "arn:",
                                                Partition,
                                                ":iam::",
                                                AccountId,
                                                ":role/",
                                                StackName,
                                                "-*",
                                            ],
                                        ),
                                    ],
                                )
                            ],
                        ),
                    ),
                    iam.Policy(
                        PolicyName="DeleteLambdas",
                        PolicyDocument=PolicyDocument(
                            Version="2012-10-17",
                            Statement=[
                                Statement(
                                    Action=[awacs.awslambda.DeleteFunction],
                                    Effect=Allow,
                                    Resource=[
                                        Join(
                                            "",
                                            [
                                                "arn:",
                                                Partition,
                                                ":lambda:",
                                                Region,
                                                ":",
                                                AccountId,
                                                ":function:%s-SelfDestruct-*"
                                                % (variables["stack_name"]),
                                            ],
                                        ),
                                        replicated_lambda_remover["function"].get_att(
                                            "Arn"
                                        ),
                                    ],
                                )
                            ],
                        ),
                    ),
                    iam.Policy(
                        PolicyName="DeleteStack",
                        PolicyDocument=PolicyDocument(
                            Version="2012-10-17",
                            Statement=[
                                Statement(
                                    Action=[awacs.cloudformation.DeleteStack],
                                    Effect=Allow,
                                    Resource=[
                                        Join(
                                            "",
                                            [
                                                "arn:",
                                                Partition,
                                                ":cloudformation:",
                                                Region,
                                                ":",
                                                AccountId,
                                                ":stack/%s/*"
                                                % (variables["stack_name"]),
                                            ],
                                        )
                                    ],
                                )
                            ],
                        ),
                    ),
                ],
            )
        )

        self.template.add_output(
            Output(
                "SelfDestructLambdaRole",
                Description="The name of the Self Destruct Role",
                Value=res["role"].ref(),
            )
        )

        res["function"] = self.template.add_resource(
            awslambda.Function(
                "SelfDestruct",
                Code=awslambda.Code(
                    ZipFile=read_value_from_path(
                        "file://"
                        + os.path.join(
                            os.path.dirname(__file__),
                            "templates/self_destruct.template.py",
                        )
                    )
                ),
                Description="Issues a Delete Stack command to the Cleanup stack",
                Handler="index.handler",
                Role=res["role"].get_att("Arn"),
                Runtime="python3.7",
            )
        )

        self.template.add_output(
            Output(
                "SelfDestructLambdaArn",
                Description="The ARN of the Replicated Function",
                Value=res["function"].get_att("Arn"),
            )
        )

        return res
Пример #16
0
    def get_default_pipeline_role(self):
        # TODO: this can be cleaned up by using a policytype and passing in the pipeline role it should add itself to.
        pipeline_policy = iam.Policy(
            PolicyName="%sPolicy" % self.name,
            PolicyDocument=awacs.aws.PolicyDocument(
                Version="2012-10-17",
                Id="PipelinePolicy",
                Statement=[
                    awacs.aws.Statement(
                        Effect=awacs.aws.Allow,
                        # TODO: actions here could be limited more
                        Action=[awacs.aws.Action("s3", "*")],
                        Resource=[
                            troposphere.Join('', [
                                awacs.s3.ARN(),
                                self.bucket_name,
                                "/*"
                            ]),
                            troposphere.Join('', [
                                awacs.s3.ARN(),
                                self.bucket_name,
                            ]),
                        ],
                    ),
                    awacs.aws.Statement(
                        Effect=awacs.aws.Allow,
                        Action=[awacs.aws.Action("kms", "*")],
                        Resource=['*'],
                    ),
                    awacs.aws.Statement(
                        Effect=awacs.aws.Allow,
                        Action=[
                            awacs.aws.Action("cloudformation", "*"),
                            awacs.aws.Action("codebuild", "*"),
                        ],
                        # TODO: restrict more accurately
                        Resource=["*"]
                    ),
                    awacs.aws.Statement(
                        Effect=awacs.aws.Allow,
                        Action=[
                            awacs.codecommit.GetBranch,
                            awacs.codecommit.GetCommit,
                            awacs.codecommit.UploadArchive,
                            awacs.codecommit.GetUploadArchiveStatus,
                            awacs.codecommit.CancelUploadArchive
                        ],
                        Resource=["*"]
                    ),
                    awacs.aws.Statement(
                        Effect=awacs.aws.Allow,
                        Action=[
                            awacs.iam.PassRole
                        ],
                        Resource=["*"]
                    ),
                    awacs.aws.Statement(
                        Effect=awacs.aws.Allow,
                        Action=[
                            awacs.aws.Action("lambda", "*")
                        ],
                        Resource=["*"]
                    ),
                ],
            )
        )

        pipeline_service_role = iam.Role(
            "PipelineServiceRole",
            Path="/",
            AssumeRolePolicyDocument=awacs.aws.Policy(
                Statement=[
                    awacs.aws.Statement(
                        Effect=awacs.aws.Allow,
                        Action=[awacs.sts.AssumeRole],
                        Principal=awacs.aws.Principal(
                            'Service',
                            "codepipeline.amazonaws.com"
                        )
                    )]
            ),
            Policies=[pipeline_policy] + self.pipeline_policies
        )
        return pipeline_service_role