예제 #1
0
파일: iam.py 프로젝트: harai/toddlr
def csvimport_lambda_role(words_table):
    def role_policy():
        return {
            'Version':
            '2012-10-17',
            'Statement': [
                {
                    'Effect': 'Allow',
                    'Action': [
                        'dynamodb:BatchWriteItem',
                        'dynamodb:PutItem',
                    ],
                    'Resource': [GetAtt(words_table, 'Arn')],
                },
                {
                    'Effect': 'Allow',
                    'Action': 's3:GetObject',
                    'Resource': ['*'],
                },
            ],
        }

    return iam.Role('CsvimportLambdaRole',
                    AssumeRolePolicyDocument=lambda_assume_role_policy(),
                    Policies=[
                        iam.Policy(PolicyName='lambda',
                                   PolicyDocument=lambda_role_policy()),
                        iam.Policy(PolicyName='role',
                                   PolicyDocument=role_policy()),
                    ])
예제 #2
0
파일: iam.py 프로젝트: harai/toddlr
def show_lambda_role(words_table, showeach_topic):
    def role_policy():
        return {
            'Version':
            '2012-10-17',
            'Statement': [
                {
                    'Effect':
                    'Allow',
                    'Action': [
                        'dynamodb:Query',
                    ],
                    'Resource': [
                        Join('', [
                            GetAtt(words_table, 'Arn'),
                            '/index/user_showed_reminder',
                        ]),
                    ],
                },
                {
                    'Effect': 'Allow',
                    'Action': 'sns:Publish',
                    'Resource': [Ref(showeach_topic)],
                },
            ],
        }

    return iam.Role('ShowLambdaRole',
                    AssumeRolePolicyDocument=lambda_assume_role_policy(),
                    Policies=[
                        iam.Policy(PolicyName='lambda',
                                   PolicyDocument=lambda_role_policy()),
                        iam.Policy(PolicyName='role',
                                   PolicyDocument=role_policy()),
                    ])
예제 #3
0
파일: lambdas.py 프로젝트: valgreens/gordon
    def _get_policies(self):
        """Returns a list of policies to attach to the IAM Role of this Lambda.
        Users can add more policies to this Role by defining policy documents
        in the settings of the lambda under the ``policies`` key."""

        policies = []

        if self._get_true_false('auto-run-policy', 't'):
            policies.append(
                iam.Policy(PolicyName=utils.valid_cloudformation_name(
                    self.name, 'logs', 'policy'),
                           PolicyDocument={
                               "Version":
                               "2012-10-17",
                               "Statement": [{
                                   "Effect":
                                   "Allow",
                                   "Action": ["lambda:InvokeFunction"],
                                   "Resource": ["*"]
                               }, {
                                   "Effect":
                                   "Allow",
                                   "Action": [
                                       "logs:CreateLogGroup",
                                       "logs:CreateLogStream",
                                       "logs:PutLogEvents"
                                   ],
                                   "Resource":
                                   "arn:aws:logs:*:*:*",
                               }]
                           }))

        if self.settings.get('vpc') and self._get_true_false(
                'auto-vpc-policy', 't'):
            policies.append(
                iam.Policy(PolicyName=utils.valid_cloudformation_name(
                    self.name, 'vpc'),
                           PolicyDocument={
                               "Version":
                               "2012-10-17",
                               "Statement": [{
                                   "Effect":
                                   "Allow",
                                   "Action": [
                                       "ec2:CreateNetworkInterface",
                                       "ec2:DescribeNetworkInterfaces",
                                       "ec2:DeleteNetworkInterface"
                                   ],
                                   "Resource": ["*"]
                               }]
                           }))

        for policy_nme, policy_document in six.iteritems(
                self.settings.get('policies', {})):
            policies.append(
                iam.Policy(PolicyName=utils.valid_cloudformation_name(
                    self.name, policy_nme, 'policy'),
                           PolicyDocument=policy_document))
        return policies
예제 #4
0
 def generate_iam_policies(self):
     name_prefix = self.context.get_fqn(self.name)
     s3_policy = iam.Policy(
         S3_WRITE_POLICY,
         PolicyName='{}-s3-write'.format(name_prefix),
         PolicyDocument=s3_write_policy(Ref(BUCKET)),
     )
     logs_policy = iam.Policy(
         LOGS_WRITE_POLICY,
         PolicyName='{}-logs-write'.format(name_prefix),
         PolicyDocument=logs_write_policy(),
     )
     return [s3_policy, logs_policy]
예제 #5
0
 def generate_iam_policies(self):
     ns = self.context.namespace
     s3_policy = iam.Policy(
         S3_WRITE_POLICY,
         PolicyName='{}-s3-write'.format(ns),
         PolicyDocument=s3_write_policy(Ref('BucketName')),
     )
     logs_policy = iam.Policy(
         LOGS_WRITE_POLICY,
         PolicyName='{}-logs-write'.format(ns),
         PolicyDocument=logs_write_policy(),
     )
     return [s3_policy, logs_policy]
예제 #6
0
    def create_role(self):
        t = self.template

        vpc_policy = NoValue
        if self.get_variables()["VpcConfig"]:
            # allow this Lambda to modify ENIs to allow it to run in our VPC.
            policy_prefix = self.context.get_fqn(self.name)
            vpc_policy = [
                iam.Policy(
                    PolicyName="%s-vpc-policy" % policy_prefix,
                    PolicyDocument=Policy(
                        Statement=lambda_vpc_execution_statements()
                    ),
                )
            ]

        self.role = t.add_resource(
            iam.Role(
                "Role",
                AssumeRolePolicyDocument=get_lambda_assumerole_policy(),
                Policies=vpc_policy
            )
        )

        t.add_output(
            Output("RoleName", Value=Ref(self.role))
        )

        role_arn = self.role.GetAtt("Arn")
        self.role_arn = role_arn

        t.add_output(
            Output("RoleArn", Value=role_arn)
        )
예제 #7
0
파일: iam.py 프로젝트: harai/toddlr
def events_invoke_lambda_role():
    def assume_role_policy():
        return {
            'Version':
            '2012-10-17',
            'Statement': [
                {
                    'Effect': 'Allow',
                    'Principal': {
                        'Service': 'events.amazonaws.com',
                    },
                    'Action': 'sts:AssumeRole',
                },
            ],
        }

    def role_policy():
        return {
            'Version':
            '2012-10-17',
            'Statement': [
                {
                    'Effect': 'Allow',
                    'Action': ['lambda:InvokeFunction'],
                    'Resource': ['*'],
                },
            ],
        }

    return iam.Role('EventsInvokeLambdaRole',
                    AssumeRolePolicyDocument=assume_role_policy(),
                    Policies=[
                        iam.Policy(PolicyName='event',
                                   PolicyDocument=role_policy())
                    ])
예제 #8
0
    def create_role(self):
        t = self.template

        self.role = t.add_resource(
            iam.Role(
                "Role",
                AssumeRolePolicyDocument=get_lambda_assumerole_policy()
            )
        )

        if self.get_variables()["VpcConfig"]:
            # allow this Lambda to modify ENIs to allow it to run in our VPC.
            self.role.Policies = [
                iam.Policy(
                    PolicyName=Sub("${AWS::StackName}-vpc-policy"),
                    PolicyDocument=Policy(
                        Statement=lambda_vpc_execution_statements()
                    ),
                )
            ]

        t.add_output(
            Output("RoleName", Value=Ref(self.role))
        )

        role_arn = self.role.GetAtt("Arn")
        self.role_arn = role_arn

        t.add_output(
            Output("RoleArn", Value=role_arn)
        )
예제 #9
0
    def _bind_role(self, t, r):
        brefs = []
        for b in self.buckets:
            bn = b.output_bucket_name()
            if bn in t.parameters:
                brefs.append(t.parameters[bn])
            else:
                brefs.append(t.add_parameter(Parameter(bn, Type="String")))

        r.Policies.append(
            iam.Policy(
                "s3fullaccess",
                PolicyName="s3fullaccess",
                PolicyDocument=aws.Policy(Statement=[
                    aws.Statement(
                        Action=[awacs.aws.Action("s3", "*")],
                        Effect=aws.Allow,
                        Resource=[
                            Join("", ["arn:aws:s3:::", Ref(i)]) for i in brefs
                        ]),
                    aws.Statement(Action=[awacs.aws.Action("s3", "*")],
                                  Effect=aws.Allow,
                                  Resource=[
                                      Join("", ["arn:aws:s3:::",
                                                Ref(i), "/*"]) for i in brefs
                                  ]),
                ])))
예제 #10
0
    def _create_role(self):
        # TODO set a role name here? Instead of relying on cloudformation to create a random nonsense string for the name
        role_kwargs = {
            "AssumeRolePolicyDocument":
            awacs.aws.Policy(Statement=[
                Statement(Effect=Allow,
                          Action=[AssumeRole],
                          Principal=Principal("Service",
                                              ["lambda.amazonaws.com"]))
            ]),
            "ManagedPolicyArns": [
                "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
            ],
        }
        if len(self._app.allow_policy_permissions) > 0:
            role_kwargs["Policies"] = [
                iam.Policy(
                    PolicyName="ExtraChiliPepperPermissions",
                    PolicyDocument=awacs.aws.Policy(Statement=[
                        p.statement()
                        for p in self._app.allow_policy_permissions
                    ]),
                )
            ]

        return iam.Role("FunctionRole", **role_kwargs)
예제 #11
0
def create_ci_user_resource(template, ci_user_name_variable):
    return template.add_resource(
        iam.User(
            'CiUser',
            UserName=ci_user_name_variable,
            Policies=[
                iam.Policy(
                    PolicyName='CiUserPolicy',
                    PolicyDocument={
                        'Version': '2012-10-17',
                        'Statement': [
                            {
                                'Action': 'ecr:*',
                                'Effect': 'Allow',
                                'Resource': '*'
                            },
                            {
                                'Action': 'ecs:UpdateService',
                                'Effect': 'Allow',
                                'Resource': '*'
                            },
                            {
                                'Action': 'secretsmanager:GetSecretValue',
                                'Effect': 'Allow',
                                'Resource': '*'
                            }
                        ]
                    }
                )
            ]
        )
    )
예제 #12
0
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 [[":*"], [":*/*"]]
                    ],
                )
            ],
        ),
    )
예제 #13
0
    def _bind_role(self, t, r):

        r.Policies.append(
            iam.Policy(
                'codedeploy',
                PolicyName='codedeploy',
                PolicyDocument=aws.Policy(Statement=[
                    aws.Statement(
                        Effect=aws.Allow,
                        Resource=['*'],
                        Action=[
                            aws.Action('autoscaling', '*'),
                            aws.Action('elasticloadbalancing',
                                       'DescribeLoadBalancers'),  # noqa
                            aws.Action('elasticloadbalancing',
                                       'DescribeInstanceHealth'),  # noqa
                            aws.Action('elasticloadbalancing',
                                       'RegisterInstancesWithLoadBalancer'),
                            aws.Action('elasticloadbalancing',
                                       'DeregisterInstancesFromLoadBalancer'),
                            aws.Action('ec2', 'Describe*'),
                            aws.Action('ec2', 'TerminateInstances'),
                            aws.Action('tag', 'GetTags'),
                            aws.Action('tag', 'GetResources'),
                            aws.Action('tag', 'GetTagsForResource'),
                            aws.Action('tag', 'GetTagsForResourceList'),
                            aws.Action('lambda', '*')
                        ]),
                ])))
예제 #14
0
파일: base.py 프로젝트: nxtlytics/ivy-rain
    def get_eni_policies(self):
        if not (self.instance_role or self.instance_profile):
            self.get_standard_policies()

        # iam_aws.PolicyDocument(
        #     Statement=[iam_aws.Statement(
        #         Effect=iam_aws.Allow,
        #         Action=[
        #             iam_ec2.AttachNetworkInterface,
        #             iam_ec2.DetachNetworkInterface
        #         ],
        #         Resource=[
        #             Sub('arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:network-interface/*')
        #         ],
        #     )]
        # )

        self.add_iam_policy(
            iam.Policy(PolicyName='ManageENI',
                       PolicyDocument={
                           'Statement': [{
                               'Effect':
                               'Allow',
                               'Action': [
                                   'ec2:AttachNetworkInterface',
                                   'ec2:DetachNetworkInterface'
                               ],
                               'Resource':
                               '*'
                           }]
                       }))
예제 #15
0
    def _get_instance_profile(self, chain_context):
        s3readPolicy = iam.Policy(
            PolicyName='S3ReadArtifactBucket',
            PolicyDocument=Policy(Statement=[
                Statement(Effect=Allow,
                          Action=[
                              awacs.s3.GetObject,
                          ],
                          Resource=[s3.ARN(self.bucket_name + "/*")]),
                Statement(Effect=Allow,
                          Action=[
                              awacs.s3.ListBucket,
                          ],
                          Resource=[s3.ARN(self.bucket_name)])
            ]))

        cfnrole = chain_context.template.add_resource(
            Role(EC2_ROLE_NAME,
                 AssumeRolePolicyDocument=Policy(Statement=[
                     Statement(Effect=Allow,
                               Action=[AssumeRole],
                               Principal=Principal("Service",
                                                   ["ec2.amazonaws.com"]))
                 ]),
                 Policies=[s3readPolicy]))

        instance_profile = InstanceProfile(INSTANCE_PROFILE_NAME,
                                           Roles=[Ref(cfnrole)])
        return instance_profile
예제 #16
0
파일: base.py 프로젝트: nxtlytics/ivy-rain
    def generate_docker_roles(self):
        """
        Generate assumable roles for ec2metaproxy docker containers
        """
        roles = [
            iam.Role(r['name'],
                     AssumeRolePolicyDocument={
                         'Statement': [{
                             'Effect': 'Allow',
                             'Principal': {
                                 "AWS": [GetAtt(self.instance_role, 'Arn')]
                             },
                             'Action': ['sts:AssumeRole']
                         }]
                     },
                     Path='/docker/',
                     Policies=[
                         iam.Policy(PolicyName='{}Policy'.format(r['name']),
                                    PolicyDocument={
                                        'Statement':
                                        self._generate_policy_statements(r)
                                    })
                     ]) for r in constants.ENVIRONMENTS[self.env]['mesos']
            ['agent']['iam_roles']
        ]

        return roles
예제 #17
0
def create_api_user_resource(template, api_user_name_variable, uploads_bucket_resource):
    return template.add_resource(
        iam.User(
            'ApiUser',
            UserName=api_user_name_variable,
            Policies=[
                iam.Policy(
                    PolicyName='ApiUserPolicy',
                    PolicyDocument={
                        'Version': '2012-10-17',
                        'Statement': [
                            {
                                'Action': 's3:*',
                                'Effect': 'Allow',
                                'Resource': [
                                    GetAtt(uploads_bucket_resource, 'Arn'),
                                    Join(
                                        '/', [GetAtt(uploads_bucket_resource, 'Arn'), '*'])
                                ]
                            },
                        ]
                    }
                )
            ]
        )
    )
예제 #18
0
    def add_lambda_role(self, title, extra_permissions):
        perms = self.DEFAULT_PERMISSIONS.union(extra_permissions)
        permissions = [Action(*perm) for perm in perms]

        return self.template.add_resource(
            iam.Role(title + 'LambdaRole',
                     Path='/',
                     Policies=[
                         iam.Policy(
                             PolicyName=title + 'LambdaExecution',
                             PolicyDocument=Policy(
                                 Version='2012-10-17',
                                 Statement=[
                                     Statement(Effect=Allow,
                                               Action=[Action('logs', '*')],
                                               Resource=['arn:aws:logs:*:*:*'
                                                         ]),
                                     Statement(
                                         Effect=Allow,
                                         Action=list(permissions),
                                         Resource=['*'],
                                     )
                                 ]))
                     ],
                     AssumeRolePolicyDocument=get_lambda_assumerole_policy()))
예제 #19
0
    def create_template(self):
        t = self.template

        bucket_arn = Sub("arn:aws:s3:::${StackerBucket}*")
        cloudformation_scope = Sub(
            "arn:aws:cloudformation:${AWS::Region}:${AWS::AccountId}:"
            "stack/${StackerNamespace}-*")
        changeset_scope = "*"

        # This represents the precise IAM permissions that stacker itself
        # needs.
        stacker_policy = iam.Policy(
            PolicyName="Stacker",
            PolicyDocument=Policy(Statement=[
                Statement(Effect="Allow",
                          Resource=[bucket_arn],
                          Action=[
                              awacs.s3.ListBucket, awacs.s3.GetBucketLocation,
                              awacs.s3.CreateBucket
                          ]),
                Statement(Effect="Allow",
                          Resource=[bucket_arn],
                          Action=[
                              awacs.s3.GetObject, awacs.s3.GetObjectAcl,
                              awacs.s3.PutObject, awacs.s3.PutObjectAcl
                          ]),
                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.DescribeStacks
                    ])
            ]))

        user = t.add_resource(
            iam.User("FunctionalTestUser", Policies=[stacker_policy]))

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

        t.add_output(Output("User", Value=Ref(user)))
        t.add_output(Output("AccessKeyId", Value=Ref(key)))
        t.add_output(
            Output("SecretAccessKey",
                   Value=GetAtt("FunctionalTestKey", "SecretAccessKey")))
예제 #20
0
 def _bind_role(self, t, r):
     r.Policies.append(
         iam.Policy('sqsall',
                    PolicyName='sqsall',
                    PolicyDocument=aws.Policy(Statement=[
                        aws.Statement(Action=[awacs.aws.Action("sqs", "*")],
                                      Effect=aws.Allow,
                                      Resource=["*"])
                    ])))
예제 #21
0
    def _bind_role(self, template, role):

        role.Policies.append(
            iam.Policy('ec2fullaccess',
                       PolicyName='ec2fullaccess',
                       PolicyDocument=aws.Policy(Statement=[
                           aws.Statement(Action=[awacs.aws.Action("ec2", "*")],
                                         Effect=aws.Allow,
                                         Resource=["*"])
                       ])))
예제 #22
0
def step_functions_role(name: str, *statements: AWS.Statement) -> iam.Role:
    return iam.Role(
        name,
        AssumeRolePolicyDocument=_assume_policy(STATES.prefix),
        Policies=[
            iam.Policy(
                PolicyName=f"{name}Policy",
                PolicyDocument=AWS.PolicyDocument(Statement=list(statements)))
        ],
    )
예제 #23
0
def _cloudformation_role() -> iam.Role:
    """Build and return the IAM Role resource to be used by the pipeline to interact with CloudFormation."""
    policy = iam.Policy(
        "CloudFormationPolicy",
        PolicyName="CloudFormationPolicy",
        PolicyDocument=AWS.PolicyDocument(Statement=[AllowEverywhere(Action=[AWS.Action("*")])]),
    )
    return iam.Role(
        "CloudFormationRole", AssumeRolePolicyDocument=_service_assume_role(CLOUDFORMATION.prefix), Policies=[policy]
    )
예제 #24
0
 def iam_role(self) -> iam.Role:
     """IAM role attached to the Lambda Function."""
     role = iam.Role(
         "LambdaRole",
         template=self.template,
         AssumeRolePolicyDocument=Policy(
             Version="2012-10-17",
             Statement=[
                 Statement(
                     Effect=Allow,
                     Action=[awacs.sts.AssumeRole],
                     Principal=Principal("Service",
                                         ["lambda.amazonaws.com"]),
                 )
             ],
         ),
         Path="/service-role/",
         PermissionsBoundary=self.variables["PermissionsBoundary"].ref,
         Policies=[
             iam.Policy(
                 PolicyName=f"{self.app_name}-lambda-policy",
                 PolicyDocument=Policy(
                     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/lambda/",
                                         f"{self.app_name}-*",
                                     ],
                                 )
                             ],
                             Sid="WriteLogs",
                         )
                     ],
                 ),
             )
         ],
     )
     self.add_output(role.title, role.ref())
     return role
예제 #25
0
def create_ecs_service_role_resource(template):
    return template.add_resource(
        iam.Role(
            'ECSServiceRole',
            AssumeRolePolicyDocument={
                'Version':
                '2012-10-17',
                'Statement': [{
                    'Action': 'sts:AssumeRole',
                    'Effect': 'Allow',
                    'Principal': {
                        'Service': 'ecs.amazonaws.com'
                    }
                }]
            },
            Policies=[
                iam.Policy(
                    PolicyName='ECSServiceRolePolicy',
                    PolicyDocument={
                        'Statement': [{
                            'Effect':
                            'Allow',
                            'Action': [
                                'ec2:AttachNetworkInterface',
                                'ec2:CreateNetworkInterface',
                                'ec2:CreateNetworkInterfacePermission',
                                'ec2:DeleteNetworkInterface',
                                'ec2:DeleteNetworkInterfacePermission',
                                'ec2:Describe*', 'ec2:DetachNetworkInterface',
                                'elasticloadbalancing:DeregisterInstancesFromLoadBalancer',
                                'elasticloadbalancing:DeregisterTargets',
                                'elasticloadbalancing:Describe*',
                                'elasticloadbalancing:RegisterInstancesWithLoadBalancer',
                                'elasticloadbalancing:RegisterTargets',
                                'route53:ChangeResourceRecordSets',
                                'route53:CreateHealthCheck',
                                'route53:DeleteHealthCheck', 'route53:Get*',
                                'route53:List*', 'route53:UpdateHealthCheck',
                                'servicediscovery:DeregisterInstance',
                                'servicediscovery:Get*',
                                'servicediscovery:List*',
                                'servicediscovery:RegisterInstance',
                                'servicediscovery:UpdateInstanceCustomHealthStatus'
                            ],
                            'Resource':
                            '*'
                        }, {
                            'Effect':
                            'Allow',
                            'Action': ['ec2:CreateTags'],
                            'Resource':
                            'arn:aws:ec2:*:*:network-interface/*'
                        }]
                    })
            ]))
예제 #26
0
    def add_iam_role(self):
        self.iam_role = self.template.add_resource(
            iam.Role("iamRole",
                     Path="/",
                     AssumeRolePolicyDocument={
                         "Statement": [{
                             "Effect": "Allow",
                             "Principal": {
                                 "Service": ["ec2.amazonaws.com"]
                             },
                             "Action": ["sts:AssumeRole"]
                         }]
                     },
                     Policies=[
                         iam.Policy(PolicyName="Ec2Access",
                                    PolicyDocument={
                                        "Statement": [{
                                            "Effect":
                                            "Allow",
                                            "Action":
                                            ["ec2:DescribeInstances"],
                                            "Resource":
                                            "*"
                                        }],
                                    }),
                         iam.Policy(
                             PolicyName="DynamoDB",
                             PolicyDocument={
                                 "Statement": [{
                                     "Effect":
                                     "Allow",
                                     "Action":
                                     "dynamodb:*",
                                     "Resource":
                                     "arn:aws:dynamodb:" + self.region + ":" +
                                     self.account_id + ":table/terminateDB"
                                 }]
                             })
                     ]))

        self.cfninstanceprofile = self.template.add_resource(
            iam.InstanceProfile("InstanceProfile", Roles=[Ref(self.iam_role)]))
    def lambda_role(cls, role_title):
        policies = [
            iam.Policy(
                PolicyName='WriteLogs',
                PolicyDocument={
                    "Version": "2012-10-17",
                    "Statement": [{
                        "Effect": "Allow",
                        "Action": [
                            "logs:CreateLogGroup",
                            "logs:CreateLogStream",
                            "logs:PutLogEvents",
                        ],
                        "Resource": "arn:aws:logs:*:*:*",
                    }],
                },
            )
        ]

        # Append specific policy if present
        lambda_policy = cls._lambda_policy()
        if lambda_policy is not None:
            policies.append(iam.Policy(
                PolicyName='CustomResourcePermissions',
                PolicyDocument=lambda_policy,
            ))

        return iam.Role(
                role_title,
                Path='/cfn-lambda/',
                AssumeRolePolicyDocument={
                    "Version": "2012-10-17",
                    "Statement": [{
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "lambda.amazonaws.com",
                        },
                        "Action": "sts:AssumeRole",
                    }],
                },
                Policies=policies,
            )
예제 #28
0
def generate_role_template(
    command: str,
    actions: list,
    role_name: str,
    path: str,
    assuming_account_id: str,
    assuming_resource: str,
    output_format: str,
) -> str:
    t = troposphere.Template()
    t.description = f"Role used to run the {command} command"

    t.add_resource(
        iam.Role(
            title="role",
            RoleName=role_name,
            Path=path,
            Policies=[
                iam.Policy(
                    PolicyName=f"{command}-permissions",
                    PolicyDocument=aws.PolicyDocument(
                        Version="2012-10-17",
                        Id=f"{command}-permissions",
                        Statement=[
                            aws.Statement(
                                Sid="1",
                                Effect=aws.Allow,
                                Action=actions,
                                Resource=["*"],
                            ),
                        ],
                    ),
                )
            ],
            AssumeRolePolicyDocument=aws.Policy(
                Version="2012-10-17",
                Id="AllowAssume",
                Statement=[
                    aws.Statement(
                        Sid="1",
                        Effect=aws.Allow,
                        Principal=aws.Principal("AWS", [
                            IAM_ARN(assuming_resource, "", assuming_account_id)
                        ]),
                        Action=[awacs_sts.AssumeRole],
                    ),
                ],
            ),
        ))

    if output_format == "json":
        return t.to_json()
    else:
        return t.to_yaml()
예제 #29
0
    def __init__(self, parameters):
        super(StackSetRole, self).__init__()

        self.AdministrationRole = iam.Role(
            "AdministrationRole",
            RoleName="AWSCloudFormationStackSetAdministrationRole",
            Path="/",
            AssumeRolePolicyDocument=aws.Policy(
                Version="2012-10-17",
                Statement=[
                    aws.Statement(
                        Action=[aws.Action("sts", "AssumeRole")],
                        Effect=aws.Allow,
                        Principal=aws.Principal(
                            "Service", "cloudformation.amazonaws.com"
                        )
                    )
                ],
            ),
            Policies=[
                iam.Policy(
                    PolicyName="AssumeRole-AWSCloudFormationStackSetExecutionRole",
                    PolicyDocument=aws.Policy(
                        Version="2012-10-17",
                        Statement=[
                            aws.Statement(
                                Action=[aws.Action("sts", "AssumeRole")],
                                Effect=aws.Allow,
                                Resource=["arn:aws:iam::*:role/AWSCloudFormationStackSetExecutionRole"],
                            )
                        ]
                    ),
                )
            ]
        )

        self.ExecutionRole = iam.Role(
            "ExecutionRole",
            RoleName="AWSCloudFormationStackSetExecutionRole",
            Path="/",
            ManagedPolicyArns=["arn:aws:iam::aws:policy/AdministratorAccess"],
            AssumeRolePolicyDocument=aws.Policy(
                Version="2012-10-17",
                Statement=[
                    aws.Statement(
                        Action=[aws.Action("sts", "AssumeRole")],
                        Effect=aws.Allow,
                        Principal=aws.Principal(
                            "AWS", Ref(parameters.AdministratorAccountId)
                        )
                    )
                ]
            )
        )
    def add_role(self):

        self.Ec2Role = self.template.add_resource(
            iam.Role("Ec2Role",
                     RoleName="ec2-role",
                     Policies=[
                         iam.Policy(
                             PolicyName="ec2-policy",
                             PolicyDocument={
                                 "Version":
                                 "2012-10-17",
                                 "Statement": [{
                                     "Action": [
                                         "ec2:DescribeInstances",
                                         "elasticloadbalancing:Describe*",
                                         "cloudwatch:ListMetrics",
                                         "cloudwatch:GetMetricStatistics",
                                         "cloudwatch:Describe*",
                                         "cloudwatch:PutMetricData",
                                         "autoscaling:Describe*"
                                     ],
                                     "Effect":
                                     "Allow",
                                     "Resource": ["*"]
                                 }, {
                                     "Sid":
                                     "Stmt1456922473000",
                                     "Effect":
                                     "Allow",
                                     "Action": [
                                         "logs:CreateLogGroup",
                                         "logs:CreateLogStream",
                                         "logs:PutLogEvents",
                                         "logs:DescribeLogStreams"
                                     ],
                                     "Resource": ["arn:aws:logs:*:*:*"]
                                 }]
                             },
                         )
                     ],
                     AssumeRolePolicyDocument={
                         "Version":
                         "2008-10-17",
                         "Statement": [{
                             "Action": ["sts:AssumeRole"],
                             "Effect": "Allow",
                             "Principal": {
                                 "Service": ["ec2.amazonaws.com"]
                             }
                         }]
                     }))

        self.inst_profile = self.template.add_resource(
            iam.InstanceProfile("InstanceProfile", Roles=[Ref(self.Ec2Role)]))