Path: blob/develop/awscli/customizations/dlm/createdefaultrole.py
1567 views
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.1#2# Licensed under the Apache License, Version 2.0 (the "License"). You3# may not use this file except in compliance with the License. A copy of4# the License is located at5#6# http://aws.amazon.com/apache2.0/7#8# or in the "license" file accompanying this file. This file is9# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF10# ANY KIND, either express or implied. See the License for the specific11# language governing permissions and limitations under the License.1213# Class to create default roles for lifecycle14import logging15from awscli.clidriver import CLIOperationCaller16from awscli.customizations.utils import get_policy_arn_suffix17from awscli.customizations.commands import BasicCommand18from awscli.customizations.dlm.iam import IAM19from awscli.customizations.dlm.constants \20import RESOURCES, \21LIFECYCLE_DEFAULT_ROLE_ASSUME_POLICY, \22POLICY_ARN_PATTERN, \23RESOURCE_TYPE_SNAPSHOT, \24RESOURCE_TYPE_IMAGE25from awscli.utils import create_nested_client2627LOG = logging.getLogger(__name__)282930def _construct_result(create_role_response, get_policy_response):31get_policy_response.pop('ResponseMetadata', None)32create_role_response.pop('ResponseMetadata', None)33result = {'RolePolicy': get_policy_response}34result.update(create_role_response)35return result363738# Display the result as formatted json39def display_response(session, operation_name, result, parsed_globals):40if result is not None:41cli_operation_caller = CLIOperationCaller(session)42# Calling a private method. Should be changed after the functionality43# is moved outside CliOperationCaller.44cli_operation_caller._display_response(45operation_name, result, parsed_globals)464748# Get policy arn from region and policy name49def get_policy_arn(region, policy_name):50region_suffix = get_policy_arn_suffix(region)51role_arn = POLICY_ARN_PATTERN.format(region_suffix, policy_name)52return role_arn535455# Method to parse the arguments to get the region value56def get_region(session, parsed_globals):57region = parsed_globals.region58if region is None:59region = session.get_config_variable('region')60return region616263class CreateDefaultRole(BasicCommand):64NAME = "create-default-role"65DESCRIPTION = ('Creates the default IAM role '66' which will be used by Lifecycle service.\n'67'If the role does not exist, create-default-role '68'will automatically create it and set its policy.'69' If the role has been already '70'created, create-default-role'71' will not update its policy.'72'\n')73ARG_TABLE = [74{'name': 'iam-endpoint',75'no_paramfile': True,76'help_text': '<p>The IAM endpoint to call for creating the roles.'77' This is optional and should only be specified when a'78' custom endpoint should be called for IAM operations'79'.</p>'},80{'name': 'resource-type',81'default': RESOURCE_TYPE_SNAPSHOT,82'choices': [RESOURCE_TYPE_SNAPSHOT, RESOURCE_TYPE_IMAGE],83'help_text': (84"<p>The resource type for which the role needs to be created."85" The available options are '%s' and '%s'."86" This parameter defaults to '%s'.</p>"87% (RESOURCE_TYPE_SNAPSHOT, RESOURCE_TYPE_IMAGE,88RESOURCE_TYPE_SNAPSHOT))}8990]9192def __init__(self, session):93super(CreateDefaultRole, self).__init__(session)9495def _run_main(self, parsed_args, parsed_globals):96"""Call to run the commands"""9798self._region = get_region(self._session, parsed_globals)99self._endpoint_url = parsed_args.iam_endpoint100self._resource_type = parsed_args.resource_type101from awscli.utils import create_nested_client102self._iam_client = IAM(create_nested_client(103self._session, 'iam',104region_name=self._region,105endpoint_url=self._endpoint_url,106verify=parsed_globals.verify_ssl107))108109result = self._create_default_role_if_not_exists(parsed_globals)110111display_response(112self._session,113'create_role',114result,115parsed_globals116)117118return 0119120def _create_default_role_if_not_exists(self, parsed_globals):121"""Method to create default lifecycle role122if it doesn't exist already123"""124125role_name = RESOURCES[self._resource_type]['default_role_name']126assume_role_policy = LIFECYCLE_DEFAULT_ROLE_ASSUME_POLICY127128if self._iam_client.check_if_role_exists(role_name):129LOG.debug('Role %s exists', role_name)130return None131132LOG.debug('Role %s does not exist. '133'Creating default role for Lifecycle', role_name)134135# Get Region136region = get_region(self._session, parsed_globals)137138if region is None:139raise ValueError('You must specify a region. '140'You can also configure your region '141'by running "aws configure".')142143managed_policy_arn = get_policy_arn(144region,145RESOURCES[self._resource_type]['default_policy_name']146)147148# Don't proceed if managed policy does not exist149if not self._iam_client.check_if_policy_exists(managed_policy_arn):150LOG.debug('Managed Policy %s does not exist.', managed_policy_arn)151return None152153LOG.debug('Managed Policy %s exists.', managed_policy_arn)154# Create default role155create_role_response = \156self._iam_client.create_role_with_trust_policy(157role_name,158assume_role_policy159)160# Attach policy to role161self._iam_client.attach_policy_to_role(162managed_policy_arn,163role_name164)165166# Construct result167get_policy_response = self._iam_client.get_policy(managed_policy_arn)168return _construct_result(create_role_response, get_policy_response)169170171