Path: blob/develop/awscli/customizations/cloudformation/deploy.py
1567 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.utils import create_nested_client, write_exception2728LOG = logging.getLogger(__name__)293031class DeployCommand(BasicCommand):3233MSG_NO_EXECUTE_CHANGESET = \34("Changeset created successfully. Run the following command to "35"review changes:"36"\n"37"aws cloudformation describe-change-set --change-set-name "38"{changeset_id}"39"\n")4041MSG_EXECUTE_SUCCESS = "Successfully created/updated stack - {stack_name}\n"4243PARAMETER_OVERRIDE_CMD = "parameter-overrides"44TAGS_CMD = "tags"4546NAME = 'deploy'47DESCRIPTION = BasicCommand.FROM_FILE("cloudformation",48"_deploy_description.rst")4950ARG_TABLE = [51{52'name': 'template-file',53'required': True,54'help_text': (55'The path where your AWS CloudFormation'56' template is located.'57)58},59{60'name': 'stack-name',61'action': 'store',62'required': True,63'help_text': (64'The name of the AWS CloudFormation stack you\'re deploying to.'65' If you specify an existing stack, the command updates the'66' stack. If you specify a new stack, the command creates it.'67)68},69{70'name': 's3-bucket',71'required': False,72'help_text': (73'The name of the S3 bucket where this command uploads your '74'CloudFormation template. This is required the deployments of '75'templates sized greater than 51,200 bytes'76)77},78{79"name": "force-upload",80"action": "store_true",81"help_text": (82'Indicates whether to override existing files in the S3 bucket.'83' Specify this flag to upload artifacts even if they '84' match existing artifacts in the S3 bucket.'85)86},87{88'name': 's3-prefix',89'help_text': (90'A prefix name that the command adds to the'91' artifacts\' name when it uploads them to the S3 bucket.'92' The prefix name is a path name (folder name) for'93' the S3 bucket.'94)95},9697{98'name': 'kms-key-id',99'help_text': (100'The ID of an AWS KMS key that the command uses'101' to encrypt artifacts that are at rest in the S3 bucket.'102)103},104{105'name': PARAMETER_OVERRIDE_CMD,106'action': 'store',107'required': False,108'schema': {109'type': 'array',110'items': {111'type': 'string'112}113},114'default': [],115'help_text': (116'A list of parameter structures that specify input parameters'117' for your stack template. If you\'re updating a stack and you'118' don\'t specify a parameter, the command uses the stack\'s'119' existing value. For new stacks, you must specify'120' parameters that don\'t have a default value.'121' Syntax: ParameterKey1=ParameterValue1'122' ParameterKey2=ParameterValue2 ...'123)124},125{126'name': 'capabilities',127'action': 'store',128'required': False,129'schema': {130'type': 'array',131'items': {132'type': 'string',133'enum': [134'CAPABILITY_IAM',135'CAPABILITY_NAMED_IAM'136]137}138},139'default': [],140'help_text': (141'A list of capabilities that you must specify before AWS'142' Cloudformation can create certain stacks. Some stack'143' templates might include resources that can affect'144' permissions in your AWS account, for example, by creating'145' new AWS Identity and Access Management (IAM) users. For'146' those stacks, you must explicitly acknowledge their'147' capabilities by specifying this parameter. '148' The only valid values are CAPABILITY_IAM and'149' CAPABILITY_NAMED_IAM. If you have IAM resources, you can'150' specify either capability. If you have IAM resources with'151' custom names, you must specify CAPABILITY_NAMED_IAM. If you'152' don\'t specify this parameter, this action returns an'153' InsufficientCapabilities error.'154)155156},157{158'name': 'no-execute-changeset',159'action': 'store_false',160'dest': 'execute_changeset',161'required': False,162'help_text': (163'Indicates whether to execute the change set. Specify this'164' flag if you want to view your stack changes before'165' executing the change set. The command creates an'166' AWS CloudFormation change set and then exits without'167' executing the change set. After you view the change set,'168' execute it to implement your changes.'169)170},171{172'name': 'disable-rollback',173'required': False,174'action': 'store_true',175'group_name': 'disable-rollback',176'dest': 'disable_rollback',177'default': False,178'help_text': (179'Preserve the state of previously provisioned resources when '180'the execute-change-set operation fails.'181)182},183{184'name': 'no-disable-rollback',185'required': False,186'action': 'store_false',187'group_name': 'disable-rollback',188'dest': 'disable_rollback',189'default': True,190'help_text': (191'Roll back all resource changes when the execute-change-set '192'operation fails.'193)194},195{196'name': 'role-arn',197'required': False,198'help_text': (199'The Amazon Resource Name (ARN) of an AWS Identity and Access '200'Management (IAM) role that AWS CloudFormation assumes when '201'executing the change set.'202)203},204{205'name': 'notification-arns',206'required': False,207'schema': {208'type': 'array',209'items': {210'type': 'string'211}212},213'help_text': (214'Amazon Simple Notification Service topic Amazon Resource Names'215' (ARNs) that AWS CloudFormation associates with the stack.'216)217},218{219'name': 'fail-on-empty-changeset',220'required': False,221'action': 'store_true',222'group_name': 'fail-on-empty-changeset',223'dest': 'fail_on_empty_changeset',224'default': True,225'help_text': (226'Specify if the CLI should return a non-zero exit code '227'when there are no changes to be made to the stack. By '228'default, a non-zero exit code is returned, and this is '229'the same behavior that occurs when '230'`--fail-on-empty-changeset` is specified. If '231'`--no-fail-on-empty-changeset` is specified, then the '232'CLI will return a zero exit code.'233)234},235{236'name': 'no-fail-on-empty-changeset',237'required': False,238'action': 'store_false',239'group_name': 'fail-on-empty-changeset',240'dest': 'fail_on_empty_changeset',241'default': True,242'help_text': (243'Causes the CLI to return an exit code of 0 if there are no '244'changes to be made to the stack.'245)246},247{248'name': TAGS_CMD,249'action': 'store',250'required': False,251'schema': {252'type': 'array',253'items': {254'type': 'string'255}256},257'default': [],258'help_text': (259'A list of tags to associate with the stack that is created'260' or updated. AWS CloudFormation also propagates these tags'261' to resources in the stack if the resource supports it.'262' Syntax: TagKey1=TagValue1 TagKey2=TagValue2 ...'263)264}265]266267def _run_main(self, parsed_args, parsed_globals):268cloudformation_client = \269create_nested_client(270self._session, 'cloudformation', region_name=parsed_globals.region,271endpoint_url=parsed_globals.endpoint_url,272verify=parsed_globals.verify_ssl)273274template_path = parsed_args.template_file275if not os.path.isfile(template_path):276raise exceptions.InvalidTemplatePathError(277template_path=template_path)278279# Parse parameters280with open(template_path, "r") as handle:281template_str = handle.read()282283stack_name = parsed_args.stack_name284parameter_overrides = self.parse_key_value_arg(285parsed_args.parameter_overrides,286self.PARAMETER_OVERRIDE_CMD)287288tags_dict = self.parse_key_value_arg(parsed_args.tags, self.TAGS_CMD)289tags = [{"Key": key, "Value": value}290for key, value in tags_dict.items()]291292template_dict = yaml_parse(template_str)293294parameters = self.merge_parameters(template_dict, parameter_overrides)295296template_size = os.path.getsize(parsed_args.template_file)297if template_size > 51200 and not parsed_args.s3_bucket:298raise exceptions.DeployBucketRequiredError()299300bucket = parsed_args.s3_bucket301if bucket:302s3_client = create_nested_client(303self._session,304"s3",305config=Config(signature_version='s3v4'),306region_name=parsed_globals.region,307verify=parsed_globals.verify_ssl)308309s3_uploader = S3Uploader(s3_client,310bucket,311parsed_args.s3_prefix,312parsed_args.kms_key_id,313parsed_args.force_upload)314else:315s3_uploader = None316317deployer = Deployer(cloudformation_client)318return self.deploy(deployer, stack_name, template_str,319parameters, parsed_args.capabilities,320parsed_args.execute_changeset, parsed_args.role_arn,321parsed_args.notification_arns, s3_uploader,322tags, parsed_args.fail_on_empty_changeset,323parsed_args.disable_rollback)324325def deploy(self, deployer, stack_name, template_str,326parameters, capabilities, execute_changeset, role_arn,327notification_arns, s3_uploader, tags,328fail_on_empty_changeset=True, disable_rollback=False):329try:330result = deployer.create_and_wait_for_changeset(331stack_name=stack_name,332cfn_template=template_str,333parameter_values=parameters,334capabilities=capabilities,335role_arn=role_arn,336notification_arns=notification_arns,337s3_uploader=s3_uploader,338tags=tags339)340except exceptions.ChangeEmptyError as ex:341if fail_on_empty_changeset:342raise343write_exception(ex, outfile=get_stdout_text_writer())344return 0345346if execute_changeset:347deployer.execute_changeset(result.changeset_id, stack_name,348disable_rollback)349deployer.wait_for_execute(stack_name, result.changeset_type)350sys.stdout.write(self.MSG_EXECUTE_SUCCESS.format(351stack_name=stack_name))352else:353sys.stdout.write(self.MSG_NO_EXECUTE_CHANGESET.format(354changeset_id=result.changeset_id))355356sys.stdout.flush()357return 0358359def merge_parameters(self, template_dict, parameter_overrides):360"""361CloudFormation CreateChangeset requires a value for every parameter362from the template, either specifying a new value or use previous value.363For convenience, this method will accept new parameter values and364generates a dict of all parameters in a format that ChangeSet API365will accept366367:param parameter_overrides:368:return:369"""370parameter_values = []371372if not isinstance(template_dict.get("Parameters", None), dict):373return parameter_values374375for key, value in template_dict["Parameters"].items():376377obj = {378"ParameterKey": key379}380381if key in parameter_overrides:382obj["ParameterValue"] = parameter_overrides[key]383else:384obj["UsePreviousValue"] = True385386parameter_values.append(obj)387388return parameter_values389390def parse_key_value_arg(self, arg_value, argname):391"""392Converts arguments that are passed as list of "Key=Value" strings393into a real dictionary.394395:param arg_value list: Array of strings, where each string is of396form Key=Value397:param argname string: Name of the argument that contains the value398:return dict: Dictionary representing the key/value pairs399"""400result = {}401for data in arg_value:402403# Split at first '=' from left404key_value_pair = data.split("=", 1)405406if len(key_value_pair) != 2:407raise exceptions.InvalidKeyValuePairArgumentError(408argname=argname,409value=key_value_pair)410411result[key_value_pair[0]] = key_value_pair[1]412413return result414415416417418419