예제 #1
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)
                        )
                    )
                ]
            )
        )
예제 #2
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)
예제 #3
0
    def _build_template(self, template):

        t = template

        if self.principals == "*":
            principal_title = "*"
        else:
            principal_title = "Service"

        role = t.add_resource(
            iam.Role(self.name,
                     AssumeRolePolicyDocument=aws.Policy(Statement=[
                         aws.Statement(Action=[awacs.sts.AssumeRole],
                                       Effect=aws.Allow,
                                       Principal=aws.Principal(
                                           principal_title, self.principals))
                     ]),
                     Path="/",
                     Policies=[],
                     ManagedPolicyArns=[]))

        for p in self.policies:
            p._bind_role(t, role)

        for m in self.managed_policies:
            role.ManagedPolicyArns.append(m)

        t.add_output([
            Output('{}Role'.format(self.name), Value=Ref(role)),
            Output('{}RoleArn'.format(self.name), Value=GetAtt(role, "Arn"))
        ])

        return t
예제 #4
0
    def get_role(self):
        """Returns the role this lambda function will use. Users can customize
        which role to apply by referencing the ARN of the role. If no Role
        is defined, gordon will create and assing one with the basic
        permissions suggested by AWS.

        Users can customize the policies attached to the role using
        ``policies`` in the lambda settings."""

        role = self.settings.get('role')

        if isinstance(role, six.string_types) or isinstance(
                role, troposphere.Ref):
            return role
        elif role is None:
            pass
        else:
            raise exceptions.InvalidLambdaRoleError(self.name, role)

        return iam.Role(utils.valid_cloudformation_name(self.name, 'role'),
                        AssumeRolePolicyDocument={
                            "Version":
                            "2012-10-17",
                            "Statement": [{
                                "Effect": "Allow",
                                "Principal": {
                                    "Service": ["lambda.amazonaws.com"]
                                },
                                "Action": ["sts:AssumeRole"]
                            }]
                        },
                        Policies=self._get_policies())
예제 #5
0
파일: base.py 프로젝트: nxtlytics/ivy-rain
 def add_iam_policy(self, policy):
     if not hasattr(self, 'policies'):
         self.policies = []
     if not isinstance(policy, iam.Policy):
         raise RuntimeError('Policy must be a troposhere iam.Policy object')
     self.policies.append(policy)
     self.instance_role = iam.Role('{}InstanceRole'.format(self.name),
                                   AssumeRolePolicyDocument={
                                       'Statement': [{
                                           'Effect':
                                           'Allow',
                                           'Principal': {
                                               'Service':
                                               ['ec2.amazonaws.com']
                                           },
                                           'Action': ['sts:AssumeRole']
                                       }]
                                   },
                                   Path='/',
                                   Policies=self.policies)
     self.instance_profile = iam.InstanceProfile(
         '{}InstanceProfile'.format(self.name),
         Path='/',
         Roles=[Ref(self.instance_role)])
     self.resources[self.instance_role.title] = self.instance_role
     self.resources[self.instance_profile.title] = self.instance_profile
예제 #6
0
    def _create_role(self, managed_policy):
        """
        Adds a iam.Role to the template.

        The role will have sufficient privileges to manage the resources required for alerts
        related to AWS Budgets

        :param managed_policy: the managed policy to associate with this role (iam.ManagedPolicy)

        :return: an iam.Role object
        """
        return self.add_resource(
            iam.Role(
                'AwsBudgetAlertingManagementRole',
                RoleName='budget-alerting-management',
                AssumeRolePolicyDocument={
                    "Statement": [{
                        "Effect": "Allow",
                        "Principal": {
                            # arn:aws:iam::AWS-account-ID:role/role-name
                            "AWS":
                            Join('', [
                                'arn:aws:iam::',
                                Ref("AWS::AccountId"), ':role/',
                                Ref(self.assume_role_name_param)
                            ])
                        },
                        "Action": ["sts:AssumeRole"]
                    }]
                },
                ManagedPolicyArns=[Ref(managed_policy)],
            ))
    def get_cfn_role(self, chain_context, step_policies=None):
        """
        Default role for cloudformation with access to the S3 bucket and cloudformation assumerole.
        :param chain_context: chaincontext.ChainContext
        :type step_policies: [troposphere.iam.Policy]
        """
        policy_name = "CloudFormationPolicy%stage" % chain_context.instance_name
        role_name = "CloudFormationRole%stage" % self.action_name

        all_policies = [
            cumulus.policies.cloudformation.
            get_policy_cloudformation_general_access(policy_name)
        ]

        if step_policies:
            all_policies += step_policies

        cloud_formation_role = iam.Role(
            role_name,
            Path="/",
            AssumeRolePolicyDocument=awacs.aws.Policy(Statement=[
                awacs.aws.Statement(Effect=awacs.aws.Allow,
                                    Action=[awacs.sts.AssumeRole],
                                    Principal=awacs.aws.Principal(
                                        'Service',
                                        ["cloudformation.amazonaws.com"]))
            ]),
            Policies=all_policies,
            ManagedPolicyArns=[
                chain_context.metadata[META_PIPELINE_BUCKET_POLICY_REF]
            ])
        return cloud_formation_role
예제 #8
0
    def create_template(self):
        """Create template (main function called by Stacker)."""
        template = self.template
        template.set_version("2010-09-09")
        template.set_description("Runway Integration Testing - IAM Role")

        # Resources
        template.add_resource(
            iam.Role(
                "CodeBuildRole",
                AssumeRolePolicyDocument=PolicyDocument(
                    Statement=[
                        Statement(
                            Effect=Allow,
                            Action=[awacs.sts.AssumeRole],
                            Principal=Principal("AWS", TESTING_ACCOUNT_ID),
                        )
                    ]
                ),
                Description="Role used for cross account testing in runway",
                ManagedPolicyArns=["arn:aws:iam::aws:policy/AdministratorAccess"],
                RoleName=Join(
                    "-",
                    [
                        "runway-integration-test-role",
                        self.variables["EnvironmentName"].ref,
                    ],
                ),
            )
        )
예제 #9
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()),
                    ])
예제 #10
0
def ssm_global():
    template = Template()

    ssm_role = iam.Role(
        'SsmRole',
        RoleName="SsmRole",
        ManagedPolicyArns=[
            "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
            "arn:aws:iam::aws:policy/AmazonS3FullAccess",
            "arn:aws:iam::aws:policy/AmazonEC2FullAccess"
        ],
        AssumeRolePolicyDocument=PolicyDocument(Statement=[
            Statement(Effect=Allow,
                      Action=[Action("sts", "AssumeRole")],
                      Principal=Principal("Service", "ec2.amazonaws.com"))
        ]))

    ssm_profile = iam.InstanceProfile('SsmProfile',
                                      Roles=[Ref(ssm_role)],
                                      InstanceProfileName="SsmProfile")

    template.add_resource(ssm_role)
    template.add_resource(ssm_profile)

    with open(
            os.path.dirname(os.path.realpath(__file__)) + '/ssm_global.yml',
            'w') as cf_file:
        cf_file.write(template.to_yaml())

    return template.to_yaml()
예제 #11
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()),
                    ])
예제 #12
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())
                    ])
예제 #13
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)
        )
예제 #14
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
예제 #15
0
    def add_instance_profile_ecs(self, layer_name, iam_policies, path_prefix):
        """
        Helper function to add role and instance profile resources to this
        template using the provided iam_policies. The instance_profile will be
        created at:
        '/<path_prefix>/<layer_name>/'
        """
        iam_role_obj = iam.Role(
            layer_name + 'IAMRole',
            AssumeRolePolicyDocument={
                'Statement': [{
                    'Effect': 'Allow',
                    'Principal': {
                        'Service': ['ec2.amazonaws.com', 'ecs.amazonaws.com']
                    },
                    'Action': ['sts:AssumeRole']
                }]
            },
            Path=Join('', ['/' + path_prefix + '/', layer_name, '/']))

        if iam_policies is not None:
            iam_role_obj.Policies = iam_policies

        iam_role = self.add_resource(iam_role_obj)

        return self.add_resource(
            iam.InstanceProfile(layer_name + 'InstancePolicy',
                                Path='/' + path_prefix + '/',
                                Roles=[Ref(iam_role)]))
예제 #16
0
    def add_resources_and_outputs(self):
        """Add resources to template."""
        template = self.template
        variables = self.get_variables()

        # build the list of managed policy ARNs to attach to the role
        managed_policy_arns = []
        for mpa in variables['ManagedPolicyArns']:
            managed_policy_arns.append(mpa)

        iamrole = template.add_resource(
            iam.Role('IamRole',
                     AssumeRolePolicyDocument=get_ecs_task_assumerole_policy(),
                     RoleName=variables['RoleName'].ref,
                     ManagedPolicyArns=managed_policy_arns))

        template.add_output(
            Output(
                "{}Arn".format(iamrole.title),
                Description="IAM Role ARN",
                Value=GetAtt(iamrole, "Arn"),
            ))

        template.add_output(
            Output(
                "{}Name".format(iamrole.title),
                Description="IAM Role name",
                Value=Ref(iamrole),
            ))
예제 #17
0
    def add_role(self, title, role_name_suffix, managed_policy):
        """
        Adds a iam.Role associated with the given managed policy to the template.

        :param title: (str) the title of the resource
        :param role_name_suffix: (str) the suffix to append to the role name, e.g. 'readonly'
        :param managed_policy: the managed policy to associate with this role (iam.ManagedPolicy)

        :return: an iam.Role object
        """
        return self.add_resource(
            iam.Role(
                title,
                RoleName=self.resource_name(
                    f"{PerfTestingTemplate.BUCKET_SHORT_NAME}-bucket-{role_name_suffix}",
                ),
                AssumeRolePolicyDocument={
                    "Statement": [{
                        "Effect": "Allow",
                        "Principal": {
                            # arn:aws:iam::AWS-account-ID:role/role-name
                            "AWS": [
                                Ref("AWS::AccountId"),
                            ]
                        },
                        "Action": ["sts:AssumeRole"]
                    }]
                },
                ManagedPolicyArns=[Ref(managed_policy)],
            ))
예제 #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 iam_adder(self, name, managed_policies, role_policy):
     role = iam.Role(name,
                     AssumeRolePolicyDocument=role_policy,
                     RoleName=name,
                     ManagedPolicyArns=managed_policies)
     self.template.add_resource(role)
     return role
    def run(self):
        puppet_version = constants.VERSION
        description = f"""Bootstrap template used to configure spoke account for stack use
        {{"version": "{puppet_version}", "framework": "servicecatalog-puppet", "role": "bootstrap-spoke-stack"}}"""

        template = t.Template(Description=description)

        template.add_resource(
            iam.Role(
                "PuppetStackRole",
                RoleName="PuppetStackRole",
                ManagedPolicyArns=[
                    t.Sub(
                        "arn:${AWS::Partition}:iam::aws:policy/AdministratorAccess"
                    )
                ],
                Path=config.get_puppet_role_path(),
                AssumeRolePolicyDocument={
                    "Version":
                    "2012-10-17",
                    "Statement": [{
                        "Action": ["sts:AssumeRole"],
                        "Effect": "Allow",
                        "Principal": {
                            "Service": ["cloudformation.amazonaws.com"]
                        },
                    }],
                },
            ))

        self.write_output(template.to_yaml(), skip_json_dump=True)
예제 #21
0
    def create_instance_profile(self, layer_name, iam_policies=None):
        '''
        Helper method creates an IAM Role and Instance Profile for the optoinally specified IAM policies
        @param layer_name [string] friendly name for the Role and Instance Profile used for naming and path organization
        @param iam_policies [Troposphere.iam.Policy[]] array of IAM Policies to be associated with the Role and Instance Profile created
        '''
        iam_role_obj = iam.Role(
            layer_name + 'IAMRole',
            AssumeRolePolicyDocument={
                'Statement': [{
                    'Effect': 'Allow',
                    'Principal': {
                        'Service': ['ec2.amazonaws.com']
                    },
                    'Action': ['sts:AssumeRole']
                }]
            },
            Path=Join('', [
                '/' + self.globals.get('environment_name', 'environmentbase') +
                '/', layer_name, '/'
            ]))

        if iam_policies != None:
            iam_role_obj.Policies = iam_policies

        iam_role = self.template.add_resource(iam_role_obj)

        return self.template.add_resource(
            iam.InstanceProfile(
                layer_name + 'InstancePolicy',
                Path='/' +
                self.globals.get('environment_name', 'environmentbase') + '/',
                Roles=[Ref(iam_role)]))
예제 #22
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)
        )
예제 #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 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)))
        ],
    )
예제 #25
0
 def test_valid_data(self):
     t = Template()
     cd = ecs.ContainerDefinition.from_dict("mycontainer", self.d)
     self.assertEquals(cd.Links[0], "containerA")
     td = ecs.TaskDefinition("taskdef",
                             ContainerDefinitions=[cd],
                             Volumes=[ecs.Volume(Name="myvol")],
                             TaskRoleArn=Ref(iam.Role("myecsrole")))
     t.add_resource(td)
     t.to_json()
예제 #26
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
예제 #27
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/*'
                        }]
                    })
            ]))
예제 #28
0
    def create_template(self):
        t = self.template
        t.add_description("Acceptance Tests for cumulus scaling groups")

        # TODO fix
        # instance = self.name + self.context.environment['env']
        instance = "someinstance"
        # TODO: give to builder
        the_chain = chain.Chain()

        the_chain.add(ingress_rule.IngressRule(
            port_to_open="22",
            cidr="10.0.0.0/8"
        ))

        instance_profile_name = "InstanceProfile" + self.name

        the_chain.add(InstanceProfileRole(
            instance_profile_name=instance_profile_name,
            role=iam.Role(
                "SomeRoleName1",
                AssumeRolePolicyDocument=Policy(
                    Statement=[
                        Statement(
                            Effect=Allow,
                            Action=[AssumeRole],
                            Principal=Principal("Service", ["ec2.amazonaws.com", "s3.amazonaws.com"])
                        )
                    ]
                ),
            )))

        launchConfigName = 'lc' + self.name

        the_chain.add(launch_config.LaunchConfig(asg_name=self.name,
                                                 launch_config_name=launchConfigName,
                                                 meta_data=self.get_metadata(),
                                                 instance_profile_name=instance_profile_name), )

        the_chain.add(block_device_data.BlockDeviceData(ec2.BlockDeviceMapping(
            DeviceName="/dev/xvda",
            Ebs=ec2.EBSBlockDevice(
                VolumeSize="40"
            ))))

        the_chain.add(scaling_group.ScalingGroup(
            launch_config_name=launchConfigName,
        ))

        chain_context = chaincontext.ChainContext(
            template=t,
            instance_name=instance
        )

        the_chain.run(chain_context)
예제 #29
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()
    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)]))