Path: blob/develop/awscli/customizations/cloudformation/deploy.py
2623 views
# Copyright 2015 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.1213import os14import sys15import logging1617from botocore.client import Config1819from awscli.customizations.cloudformation import exceptions20from awscli.customizations.cloudformation.deployer import Deployer21from awscli.customizations.s3uploader import S3Uploader22from awscli.customizations.cloudformation.yamlhelper import yaml_parse2324from awscli.customizations.commands import BasicCommand25from awscli.compat import get_stdout_text_writer26from awscli.customizations.utils import uni_print27from awscli.utils import create_nested_client, write_exception, resolve_v2_debug_mode2829LOG = logging.getLogger(__name__)303132class DeployCommand(BasicCommand):3334MSG_NO_EXECUTE_CHANGESET = \35("Changeset created successfully. Run the following command to "36"review changes:"37"\n"38"aws cloudformation describe-change-set --change-set-name "39"{changeset_id}"40"\n")4142MSG_EXECUTE_SUCCESS = "Successfully created/updated stack - {stack_name}\n"4344PARAMETER_OVERRIDE_CMD = "parameter-overrides"45TAGS_CMD = "tags"4647NAME = 'deploy'48DESCRIPTION = BasicCommand.FROM_FILE("cloudformation",49"_deploy_description.rst")5051ARG_TABLE = [52{53'name': 'template-file',54'required': True,55'help_text': (56'The path where your AWS CloudFormation'57' template is located.'58)59},60{61'name': 'stack-name',62'action': 'store',63'required': True,64'help_text': (65'The name of the AWS CloudFormation stack you\'re deploying to.'66' If you specify an existing stack, the command updates the'67' stack. If you specify a new stack, the command creates it.'68)69},70{71'name': 's3-bucket',72'required': False,73'help_text': (74'The name of the S3 bucket where this command uploads your '75'CloudFormation template. This is required the deployments of '76'templates sized greater than 51,200 bytes'77)78},79{80"name": "force-upload",81"action": "store_true",82"help_text": (83'Indicates whether to override existing files in the S3 bucket.'84' Specify this flag to upload artifacts even if they '85' match existing artifacts in the S3 bucket.'86)87},88{89'name': 's3-prefix',90'help_text': (91'A prefix name that the command adds to the'92' artifacts\' name when it uploads them to the S3 bucket.'93' The prefix name is a path name (folder name) for'94' the S3 bucket.'95)96},9798{99'name': 'kms-key-id',100'help_text': (101'The ID of an AWS KMS key that the command uses'102' to encrypt artifacts that are at rest in the S3 bucket.'103)104},105{106'name': PARAMETER_OVERRIDE_CMD,107'action': 'store',108'required': False,109'schema': {110'type': 'array',111'items': {112'type': 'string'113}114},115'default': [],116'help_text': (117'A list of parameter structures that specify input parameters'118' for your stack template. If you\'re updating a stack and you'119' don\'t specify a parameter, the command uses the stack\'s'120' existing value. For new stacks, you must specify'121' parameters that don\'t have a default value.'122' Syntax: ParameterKey1=ParameterValue1'123' ParameterKey2=ParameterValue2 ...'124)125},126{127'name': 'capabilities',128'action': 'store',129'required': False,130'schema': {131'type': 'array',132'items': {133'type': 'string',134'enum': [135'CAPABILITY_IAM',136'CAPABILITY_NAMED_IAM'137]138}139},140'default': [],141'help_text': (142'A list of capabilities that you must specify before AWS'143' Cloudformation can create certain stacks. Some stack'144' templates might include resources that can affect'145' permissions in your AWS account, for example, by creating'146' new AWS Identity and Access Management (IAM) users. For'147' those stacks, you must explicitly acknowledge their'148' capabilities by specifying this parameter. '149' The only valid values are CAPABILITY_IAM and'150' CAPABILITY_NAMED_IAM. If you have IAM resources, you can'151' specify either capability. If you have IAM resources with'152' custom names, you must specify CAPABILITY_NAMED_IAM. If you'153' don\'t specify this parameter, this action returns an'154' InsufficientCapabilities error.'155)156157},158{159'name': 'no-execute-changeset',160'action': 'store_false',161'dest': 'execute_changeset',162'required': False,163'help_text': (164'Indicates whether to execute the change set. Specify this'165' flag if you want to view your stack changes before'166' executing the change set. The command creates an'167' AWS CloudFormation change set and then exits without'168' executing the change set. After you view the change set,'169' execute it to implement your changes.'170)171},172{173'name': 'disable-rollback',174'required': False,175'action': 'store_true',176'group_name': 'disable-rollback',177'dest': 'disable_rollback',178'default': False,179'help_text': (180'Preserve the state of previously provisioned resources when '181'the execute-change-set operation fails.'182)183},184{185'name': 'no-disable-rollback',186'required': False,187'action': 'store_false',188'group_name': 'disable-rollback',189'dest': 'disable_rollback',190'default': True,191'help_text': (192'Roll back all resource changes when the execute-change-set '193'operation fails.'194)195},196{197'name': 'role-arn',198'required': False,199'help_text': (200'The Amazon Resource Name (ARN) of an AWS Identity and Access '201'Management (IAM) role that AWS CloudFormation assumes when '202'executing the change set.'203)204},205{206'name': 'notification-arns',207'required': False,208'schema': {209'type': 'array',210'items': {211'type': 'string'212}213},214'help_text': (215'Amazon Simple Notification Service topic Amazon Resource Names'216' (ARNs) that AWS CloudFormation associates with the stack.'217)218},219{220'name': 'fail-on-empty-changeset',221'required': False,222'action': 'store_true',223'group_name': 'fail-on-empty-changeset',224'dest': 'fail_on_empty_changeset',225'default': True,226'help_text': (227'Specify if the CLI should return a non-zero exit code '228'when there are no changes to be made to the stack. By '229'default, a non-zero exit code is returned, and this is '230'the same behavior that occurs when '231'`--fail-on-empty-changeset` is specified. If '232'`--no-fail-on-empty-changeset` is specified, then the '233'CLI will return a zero exit code.'234)235},236{237'name': 'no-fail-on-empty-changeset',238'required': False,239'action': 'store_false',240'group_name': 'fail-on-empty-changeset',241'dest': 'fail_on_empty_changeset',242'default': True,243'help_text': (244'Causes the CLI to return an exit code of 0 if there are no '245'changes to be made to the stack.'246)247},248{249'name': TAGS_CMD,250'action': 'store',251'required': False,252'schema': {253'type': 'array',254'items': {255'type': 'string'256}257},258'default': [],259'help_text': (260'A list of tags to associate with the stack that is created'261' or updated. AWS CloudFormation also propagates these tags'262' to resources in the stack if the resource supports it.'263' Syntax: TagKey1=TagValue1 TagKey2=TagValue2 ...'264)265}266]267268def _run_main(self, parsed_args, parsed_globals):269cloudformation_client = \270create_nested_client(271self._session, 'cloudformation', region_name=parsed_globals.region,272endpoint_url=parsed_globals.endpoint_url,273verify=parsed_globals.verify_ssl)274275template_path = parsed_args.template_file276if not os.path.isfile(template_path):277raise exceptions.InvalidTemplatePathError(278template_path=template_path)279280# Parse parameters281with open(template_path, "r") as handle:282template_str = handle.read()283284stack_name = parsed_args.stack_name285parameter_overrides = self.parse_key_value_arg(286parsed_args.parameter_overrides,287self.PARAMETER_OVERRIDE_CMD)288289tags_dict = self.parse_key_value_arg(parsed_args.tags, self.TAGS_CMD)290tags = [{"Key": key, "Value": value}291for key, value in tags_dict.items()]292293template_dict = yaml_parse(template_str)294295parameters = self.merge_parameters(template_dict, parameter_overrides)296297template_size = os.path.getsize(parsed_args.template_file)298if template_size > 51200 and not parsed_args.s3_bucket:299raise exceptions.DeployBucketRequiredError()300301bucket = parsed_args.s3_bucket302if bucket:303s3_client = create_nested_client(304self._session,305"s3",306config=Config(signature_version='s3v4'),307region_name=parsed_globals.region,308verify=parsed_globals.verify_ssl)309310s3_uploader = S3Uploader(s3_client,311bucket,312parsed_args.s3_prefix,313parsed_args.kms_key_id,314parsed_args.force_upload)315else:316s3_uploader = None317318deployer = Deployer(cloudformation_client)319v2_debug = resolve_v2_debug_mode(parsed_globals)320return self.deploy(deployer, stack_name, template_str,321parameters, parsed_args.capabilities,322parsed_args.execute_changeset, parsed_args.role_arn,323parsed_args.notification_arns, s3_uploader,324tags, parsed_args.fail_on_empty_changeset,325parsed_args.disable_rollback, v2_debug)326327def deploy(self, deployer, stack_name, template_str,328parameters, capabilities, execute_changeset, role_arn,329notification_arns, s3_uploader, tags,330fail_on_empty_changeset=True, disable_rollback=False,331v2_debug=False):332try:333if v2_debug and fail_on_empty_changeset:334uni_print(335'\nAWS CLI v2 UPGRADE WARNING: In AWS CLI v2, deploying '336'an AWS CloudFormation Template that results in an empty '337'changeset will NOT result in an error by default. This '338'is different from v1 behavior, where empty changesets '339'result in an error by default. To migrate to v2 behavior '340'and resolve this warning, you can add the '341'`--no-fail-on-empty-changeset` flag to the command. '342'See https://docs.aws.amazon.com/cli/latest/userguide/'343'cliv2-migration-changes.html#cliv2-migration-cfn.\n',344out_file=sys.stderr345)346result = deployer.create_and_wait_for_changeset(347stack_name=stack_name,348cfn_template=template_str,349parameter_values=parameters,350capabilities=capabilities,351role_arn=role_arn,352notification_arns=notification_arns,353s3_uploader=s3_uploader,354tags=tags355)356except exceptions.ChangeEmptyError as ex:357if fail_on_empty_changeset:358raise359write_exception(ex, outfile=get_stdout_text_writer())360return 0361362if execute_changeset:363deployer.execute_changeset(result.changeset_id, stack_name,364disable_rollback)365deployer.wait_for_execute(stack_name, result.changeset_type)366sys.stdout.write(self.MSG_EXECUTE_SUCCESS.format(367stack_name=stack_name))368else:369sys.stdout.write(self.MSG_NO_EXECUTE_CHANGESET.format(370changeset_id=result.changeset_id))371372sys.stdout.flush()373return 0374375def merge_parameters(self, template_dict, parameter_overrides):376"""377CloudFormation CreateChangeset requires a value for every parameter378from the template, either specifying a new value or use previous value.379For convenience, this method will accept new parameter values and380generates a dict of all parameters in a format that ChangeSet API381will accept382383:param parameter_overrides:384:return:385"""386parameter_values = []387388if not isinstance(template_dict.get("Parameters", None), dict):389return parameter_values390391for key, value in template_dict["Parameters"].items():392393obj = {394"ParameterKey": key395}396397if key in parameter_overrides:398obj["ParameterValue"] = parameter_overrides[key]399else:400obj["UsePreviousValue"] = True401402parameter_values.append(obj)403404return parameter_values405406def parse_key_value_arg(self, arg_value, argname):407"""408Converts arguments that are passed as list of "Key=Value" strings409into a real dictionary.410411:param arg_value list: Array of strings, where each string is of412form Key=Value413:param argname string: Name of the argument that contains the value414:return dict: Dictionary representing the key/value pairs415"""416result = {}417for data in arg_value:418419# Split at first '=' from left420key_value_pair = data.split("=", 1)421422if len(key_value_pair) != 2:423raise exceptions.InvalidKeyValuePairArgumentError(424argname=argname,425value=key_value_pair)426427result[key_value_pair[0]] = key_value_pair[1]428429return result430431432433434435