Example #1
0
class GetRolePolicy(IAMRequest):
    DESCRIPTION = "Display a role's policy"
    ARGS = [
        arg_role(help='role the poilcy is attached to (required)'),
        Arg('-p',
            '--policy-name',
            dest='PolicyName',
            metavar='POLICY',
            required=True,
            help='name of the policy to show (required)'),
        Arg('--pretty-print',
            action='store_true',
            route_to=None,
            help='reformat the policy for easier reading'), AS_ACCOUNT
    ]

    def print_result(self, result):
        policy_content = urllib.unquote(result['PolicyDocument'])
        if self.args['pretty_print']:
            try:
                policy_json = json.loads(policy_content)
            except ValueError:
                self.log.debug('JSON parse error', exc_info=True)
                raise ValueError(
                    "policy '{0}' does not appear to be valid JSON".format(
                        self.args['PolicyName']))
            policy_content = json.dumps(policy_json, indent=4)
        print policy_content
Example #2
0
class UpdateAssumeRolePolicy(IAMRequest):
    DESCRIPTION = ("Update a role's trust policy, the policy that allows "
                   "entities to assume a role")
    ARGS = [arg_role(help='role to update (required)'),
            MutuallyExclusiveArgList(
                Arg('-f', dest='PolicyDocument', metavar='FILE',
                    type=file_contents,
                    help='file containing the policy for the new role'),
                Arg('-s', '--service', route_to=None, help='''service to allow
                    access to the role (e.g. ec2.amazonaws.com)'''))
            .required(),
            Arg('-o', dest='verbose', action='store_true',
                help="also print the role's new policy"),
            AS_ACCOUNT]

    def preprocess(self):
        if self.args.get('service'):
            statement = {'Effect': 'Allow',
                         'Principal': {'Service': [self.args['service']]},
                         'Action': ['sts:AssumeRole']}
            policy = {'Version': '2008-10-17',
                      'Statement': [statement]}
            self.params['PolicyDocument'] = json.dumps(policy)

    def print_result(self, _):
        if self.args.get('verbose'):
            print self.params['PolicyDocument']
Example #3
0
class CreateRole(IAMRequest):
    DESCRIPTION = 'Create a new role'
    ARGS = [arg_role(help='name of the new role (required)'),
            Arg('-p', '--path', dest='Path',
                help='path for the new role (default: "/")'),
            MutuallyExclusiveArgList(
                Arg('-f', dest='AssumeRolePolicyDocument', metavar='FILE',
                    type=file_contents,
                    help='file containing the policy for the new role'),
                Arg('-s', '--service', dest='service_', metavar='SERVICE',
                    route_to=None, help='''service to allow access to
                    the role (e.g. ec2.amazonaws.com)'''),
                # For compatibility with a typo in < 3.2.1
                Arg('--service_', route_to=None, help=argparse.SUPPRESS))
            .required(),
            Arg('-v', '--verbose', action='store_true', route_to=None,
                help="print the new role's ARN, GUID, and policy"),
            AS_ACCOUNT]

    def preprocess(self):
        if self.args.get('service_'):
            statement = {'Effect': 'Allow',
                         'Principal': {'Service': [self.args['service_']]},
                         'Action': ['sts:AssumeRole']}
            policy = {'Version': '2008-10-17',
                      'Statement': [statement]}
            self.params['AssumeRolePolicyDocument'] = json.dumps(policy)

    def print_result(self, result):
        if self.args.get('verbose'):
            print result.get('Role', {}).get('Arn')
            print result.get('Role', {}).get('RoleId')
            print urllib.unquote(result.get('Role', {})
                                 .get('AssumeRolePolicyDocument'))
class ListInstanceProfilesForRole(IAMRequest):
    DESCRIPTION = 'List all instance profiles that use a role'
    ARGS = [
        arg_role(help='role to list membership for (required)'), AS_ACCOUNT
    ]
    LIST_TAGS = ['InstanceProfiles']

    def main(self):
        return PaginatedResponse(self, (None, ), ('InstanceProfiles', ))

    def prepare_for_page(self, page):
        # Pages are defined by markers
        self.params['Marker'] = page

    # pylint: disable=no-self-use
    def get_next_page(self, response):
        if response.get('IsTruncated') == 'true':
            return response['Marker']

    # pylint: enable=no-self-use

    # pylint: disable=no-self-use
    def print_result(self, result):
        for profile in result.get('InstanceProfiles', []):
            print profile['Arn']
Example #5
0
class GetRole(IAMRequest):
    DESCRIPTION = "Display a role's ARN, GUID, and trust policy"
    ARGS = [arg_role(help='name of the role to describe (required)'),
            AS_ACCOUNT]

    # pylint: disable=no-self-use
    def print_result(self, result):
        print result.get('Role', {}).get('Arn')
        print result.get('Role', {}).get('RoleId')
        print urllib.unquote(result.get('Role', {})
                             .get('AssumeRolePolicyDocument'))
Example #6
0
class AddRolePolicy(IAMRequest):
    DESCRIPTION = ('Add a new policy to a role.  To add more complex policies '
                   'than this tool supports, see euare-roleuploadpolicy(1).')
    ARGS = [
        arg_role(help='role to attach the policy to (required)'),
        Arg('-p',
            '--policy-name',
            metavar='POLICY',
            required=True,
            help='name of the new policy (required)'),
        Arg('-e',
            '--effect',
            choices=('Allow', 'Deny'),
            required=True,
            help='whether the new policy should Allow or Deny (required)'),
        Arg('-a',
            '--action',
            dest='actions',
            action='append',
            required=True,
            help='''action(s) the policy should apply to
                (at least one required)'''),
        Arg('-c',
            '--resource',
            dest='resources',
            action='append',
            required=True,
            help='''resource(s) the policy should apply to
                (at least one required)'''),
        Arg('-o',
            '--output',
            action='store_true',
            help='also display the newly-created policy'), AS_ACCOUNT
    ]

    def main(self):
        policy = build_iam_policy(self.args['effect'], self.args['resources'],
                                  self.args['actions'])
        policy_doc = json.dumps(policy)
        req = PutRolePolicy.from_other(
            self,
            RoleName=self.args['RoleName'],
            PolicyName=self.args['policy_name'],
            PolicyDocument=policy_doc,
            DelegateAccount=self.params['DelegateAccount'])
        response = req.main()
        response['PolicyDocument'] = policy_doc
        return response

    def print_result(self, result):
        if self.args['output']:
            print result['PolicyDocument']
Example #7
0
class PutRolePolicy(IAMRequest):
    DESCRIPTION = 'Attach a policy to a role'
    ARGS = [
        arg_role(help='role to attach the policy to (required)'),
        Arg('-p',
            '--policy-name',
            dest='PolicyName',
            metavar='POLICY',
            required=True,
            help='name of the policy (required)'),
        MutuallyExclusiveArgList(
            Arg('-o',
                '--policy-content',
                dest='PolicyDocument',
                metavar='POLICY_CONTENT',
                help='the policy to attach'),
            Arg('-f',
                '--policy-document',
                dest='PolicyDocument',
                metavar='FILE',
                type=open,
                help='file containing the policy to attach')).required(),
        AS_ACCOUNT
    ]
class ListRolePolicies(IAMRequest):
    DESCRIPTION = 'List one or all policies attached to a role'
    ARGS = [
        arg_role(help='role owning the policies to list (required)'),
        Arg('-p',
            '--policy-name',
            metavar='POLICY',
            route_to=None,
            help='display a specific policy'),
        Arg('-v',
            '--verbose',
            action='store_true',
            route_to=None,
            help='''display the contents of the resulting policies (in
                        addition to their names)'''),
        Arg('--pretty-print',
            action='store_true',
            route_to=None,
            help='''when printing the contents of policies, reformat them
                        for easier reading'''), AS_ACCOUNT
    ]
    LIST_TAGS = ['PolicyNames']

    def main(self):
        return PaginatedResponse(self, (None, ), ('PolicyNames', ))

    def prepare_for_page(self, page):
        # Pages are defined by markers
        self.params['Marker'] = page

    # pylint: disable=no-self-use
    def get_next_page(self, response):
        if response.get('IsTruncated') == 'true':
            return response['Marker']

    # pylint: enable=no-self-use

    def print_result(self, result):
        if self.args.get('policy_name'):
            # Look for the specific policy the user asked for
            for policy_name in result.get('PolicyNames', []):
                if policy_name == self.args['policy_name']:
                    if self.args['verbose']:
                        self.print_policy(policy_name)
                    else:
                        print policy_name
                    break
        else:
            for policy_name in result.get('PolicyNames', []):
                print policy_name
                if self.args['verbose']:
                    self.print_policy(policy_name)
        # We already take care of pagination
        print 'IsTruncated: false'

    def print_policy(self, policy_name):
        req = GetRolePolicy.from_other(
            self,
            RoleName=self.args['RoleName'],
            PolicyName=policy_name,
            pretty_print=self.args['pretty_print'],
            DelegateAccount=self.params.get('DelegateAccount'))
        response = req.main()
        req.print_result(response)
Example #9
0
class DeleteRole(IAMRequest):
    DESCRIPTION = 'Delete a role'
    ARGS = [arg_role(help='name of the role to delete (required)'),
            Arg('-c', '--recursive', action='store_true', route_to=None,
                help='''remove all IAM resources associated with the role
                first'''),
            Arg('-p', '--pretend', action='store_true', route_to=None,
                help='''list the resources that would be deleted instead of
                actually deleting them.  Implies -c.'''),
            AS_ACCOUNT]

    def main(self):
        if self.args.get('recursive') or self.args.get('pretend'):
            # Figure out what we have to delete
            req = ListInstanceProfilesForRole.from_other(
                self, RoleName=self.args['RoleName'],
                DelegateAccount=self.args.get('DelegateAccount'))
            response = req.main()
            instance_profiles = []
            for profile in response.get('InstanceProfiles') or []:
                instance_profiles.append(
                    {'arn': profile.get('Arn'),
                     'name': profile.get('InstanceProfileName')})

            req = ListRolePolicies.from_other(
                self, RoleName=self.args['RoleName'],
                DelegateAccount=self.args.get('DelegateAccount'))
            response = req.main()
            policies = []
            for policy in response.get('PolicyNames') or []:
                policies.append(policy)
        else:
            # Just in case
            instance_profiles = []
            policies = []
        if self.args.get('pretend'):
            return {'instance_profiles': instance_profiles,
                    'policies': policies}
        else:
            if self.args.get('recursive'):
                for profile in instance_profiles:
                    req = RemoveRoleFromInstanceProfile.from_other(
                        self, RoleName=self.args['RoleName'],
                        InstanceProfileName=profile['name'],
                        DelegateAccount=self.args.get('DelegateAccount'))
                    req.main()
                for policy in policies:
                    req = DeleteRolePolicy.from_other(
                        self, RoleName=self.args['RoleName'],
                        PolicyName=policy,
                        DelegateAccount=self.args.get('DelegateAccount'))
                    req.main()
        return self.send()

    def print_result(self, result):
        if self.args.get('pretend'):
            print 'instance profiles'
            for profile in result['instance_profiles']:
                print '\t' + profile['arn']
            print 'policies'
            for policy in result['policies']:
                print '\t' + policy
class DeleteRolePolicy(IAMRequest):
    DESCRIPTION = 'Remove a policy from a role'
    ARGS = [arg_role(help='role the policy is attached to (required)'),
            Arg('-p', '--policy-name', dest='PolicyName', metavar='POLICY',
                required=True, help='name of the policy to delete (required)'),
            AS_ACCOUNT]