Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aws
GitHub Repository: aws/aws-cli
Path: blob/develop/awscli/customizations/cloudformation/deploy.py
2623 views
1
# Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License"). You
4
# may not use this file except in compliance with the License. A copy of
5
# the License is located at
6
#
7
# http://aws.amazon.com/apache2.0/
8
#
9
# or in the "license" file accompanying this file. This file is
10
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
# ANY KIND, either express or implied. See the License for the specific
12
# language governing permissions and limitations under the License.
13
14
import os
15
import sys
16
import logging
17
18
from botocore.client import Config
19
20
from awscli.customizations.cloudformation import exceptions
21
from awscli.customizations.cloudformation.deployer import Deployer
22
from awscli.customizations.s3uploader import S3Uploader
23
from awscli.customizations.cloudformation.yamlhelper import yaml_parse
24
25
from awscli.customizations.commands import BasicCommand
26
from awscli.compat import get_stdout_text_writer
27
from awscli.customizations.utils import uni_print
28
from awscli.utils import create_nested_client, write_exception, resolve_v2_debug_mode
29
30
LOG = logging.getLogger(__name__)
31
32
33
class DeployCommand(BasicCommand):
34
35
MSG_NO_EXECUTE_CHANGESET = \
36
("Changeset created successfully. Run the following command to "
37
"review changes:"
38
"\n"
39
"aws cloudformation describe-change-set --change-set-name "
40
"{changeset_id}"
41
"\n")
42
43
MSG_EXECUTE_SUCCESS = "Successfully created/updated stack - {stack_name}\n"
44
45
PARAMETER_OVERRIDE_CMD = "parameter-overrides"
46
TAGS_CMD = "tags"
47
48
NAME = 'deploy'
49
DESCRIPTION = BasicCommand.FROM_FILE("cloudformation",
50
"_deploy_description.rst")
51
52
ARG_TABLE = [
53
{
54
'name': 'template-file',
55
'required': True,
56
'help_text': (
57
'The path where your AWS CloudFormation'
58
' template is located.'
59
)
60
},
61
{
62
'name': 'stack-name',
63
'action': 'store',
64
'required': True,
65
'help_text': (
66
'The name of the AWS CloudFormation stack you\'re deploying to.'
67
' If you specify an existing stack, the command updates the'
68
' stack. If you specify a new stack, the command creates it.'
69
)
70
},
71
{
72
'name': 's3-bucket',
73
'required': False,
74
'help_text': (
75
'The name of the S3 bucket where this command uploads your '
76
'CloudFormation template. This is required the deployments of '
77
'templates sized greater than 51,200 bytes'
78
)
79
},
80
{
81
"name": "force-upload",
82
"action": "store_true",
83
"help_text": (
84
'Indicates whether to override existing files in the S3 bucket.'
85
' Specify this flag to upload artifacts even if they '
86
' match existing artifacts in the S3 bucket.'
87
)
88
},
89
{
90
'name': 's3-prefix',
91
'help_text': (
92
'A prefix name that the command adds to the'
93
' artifacts\' name when it uploads them to the S3 bucket.'
94
' The prefix name is a path name (folder name) for'
95
' the S3 bucket.'
96
)
97
},
98
99
{
100
'name': 'kms-key-id',
101
'help_text': (
102
'The ID of an AWS KMS key that the command uses'
103
' to encrypt artifacts that are at rest in the S3 bucket.'
104
)
105
},
106
{
107
'name': PARAMETER_OVERRIDE_CMD,
108
'action': 'store',
109
'required': False,
110
'schema': {
111
'type': 'array',
112
'items': {
113
'type': 'string'
114
}
115
},
116
'default': [],
117
'help_text': (
118
'A list of parameter structures that specify input parameters'
119
' for your stack template. If you\'re updating a stack and you'
120
' don\'t specify a parameter, the command uses the stack\'s'
121
' existing value. For new stacks, you must specify'
122
' parameters that don\'t have a default value.'
123
' Syntax: ParameterKey1=ParameterValue1'
124
' ParameterKey2=ParameterValue2 ...'
125
)
126
},
127
{
128
'name': 'capabilities',
129
'action': 'store',
130
'required': False,
131
'schema': {
132
'type': 'array',
133
'items': {
134
'type': 'string',
135
'enum': [
136
'CAPABILITY_IAM',
137
'CAPABILITY_NAMED_IAM'
138
]
139
}
140
},
141
'default': [],
142
'help_text': (
143
'A list of capabilities that you must specify before AWS'
144
' Cloudformation can create certain stacks. Some stack'
145
' templates might include resources that can affect'
146
' permissions in your AWS account, for example, by creating'
147
' new AWS Identity and Access Management (IAM) users. For'
148
' those stacks, you must explicitly acknowledge their'
149
' capabilities by specifying this parameter. '
150
' The only valid values are CAPABILITY_IAM and'
151
' CAPABILITY_NAMED_IAM. If you have IAM resources, you can'
152
' specify either capability. If you have IAM resources with'
153
' custom names, you must specify CAPABILITY_NAMED_IAM. If you'
154
' don\'t specify this parameter, this action returns an'
155
' InsufficientCapabilities error.'
156
)
157
158
},
159
{
160
'name': 'no-execute-changeset',
161
'action': 'store_false',
162
'dest': 'execute_changeset',
163
'required': False,
164
'help_text': (
165
'Indicates whether to execute the change set. Specify this'
166
' flag if you want to view your stack changes before'
167
' executing the change set. The command creates an'
168
' AWS CloudFormation change set and then exits without'
169
' executing the change set. After you view the change set,'
170
' execute it to implement your changes.'
171
)
172
},
173
{
174
'name': 'disable-rollback',
175
'required': False,
176
'action': 'store_true',
177
'group_name': 'disable-rollback',
178
'dest': 'disable_rollback',
179
'default': False,
180
'help_text': (
181
'Preserve the state of previously provisioned resources when '
182
'the execute-change-set operation fails.'
183
)
184
},
185
{
186
'name': 'no-disable-rollback',
187
'required': False,
188
'action': 'store_false',
189
'group_name': 'disable-rollback',
190
'dest': 'disable_rollback',
191
'default': True,
192
'help_text': (
193
'Roll back all resource changes when the execute-change-set '
194
'operation fails.'
195
)
196
},
197
{
198
'name': 'role-arn',
199
'required': False,
200
'help_text': (
201
'The Amazon Resource Name (ARN) of an AWS Identity and Access '
202
'Management (IAM) role that AWS CloudFormation assumes when '
203
'executing the change set.'
204
)
205
},
206
{
207
'name': 'notification-arns',
208
'required': False,
209
'schema': {
210
'type': 'array',
211
'items': {
212
'type': 'string'
213
}
214
},
215
'help_text': (
216
'Amazon Simple Notification Service topic Amazon Resource Names'
217
' (ARNs) that AWS CloudFormation associates with the stack.'
218
)
219
},
220
{
221
'name': 'fail-on-empty-changeset',
222
'required': False,
223
'action': 'store_true',
224
'group_name': 'fail-on-empty-changeset',
225
'dest': 'fail_on_empty_changeset',
226
'default': True,
227
'help_text': (
228
'Specify if the CLI should return a non-zero exit code '
229
'when there are no changes to be made to the stack. By '
230
'default, a non-zero exit code is returned, and this is '
231
'the same behavior that occurs when '
232
'`--fail-on-empty-changeset` is specified. If '
233
'`--no-fail-on-empty-changeset` is specified, then the '
234
'CLI will return a zero exit code.'
235
)
236
},
237
{
238
'name': 'no-fail-on-empty-changeset',
239
'required': False,
240
'action': 'store_false',
241
'group_name': 'fail-on-empty-changeset',
242
'dest': 'fail_on_empty_changeset',
243
'default': True,
244
'help_text': (
245
'Causes the CLI to return an exit code of 0 if there are no '
246
'changes to be made to the stack.'
247
)
248
},
249
{
250
'name': TAGS_CMD,
251
'action': 'store',
252
'required': False,
253
'schema': {
254
'type': 'array',
255
'items': {
256
'type': 'string'
257
}
258
},
259
'default': [],
260
'help_text': (
261
'A list of tags to associate with the stack that is created'
262
' or updated. AWS CloudFormation also propagates these tags'
263
' to resources in the stack if the resource supports it.'
264
' Syntax: TagKey1=TagValue1 TagKey2=TagValue2 ...'
265
)
266
}
267
]
268
269
def _run_main(self, parsed_args, parsed_globals):
270
cloudformation_client = \
271
create_nested_client(
272
self._session, 'cloudformation', region_name=parsed_globals.region,
273
endpoint_url=parsed_globals.endpoint_url,
274
verify=parsed_globals.verify_ssl)
275
276
template_path = parsed_args.template_file
277
if not os.path.isfile(template_path):
278
raise exceptions.InvalidTemplatePathError(
279
template_path=template_path)
280
281
# Parse parameters
282
with open(template_path, "r") as handle:
283
template_str = handle.read()
284
285
stack_name = parsed_args.stack_name
286
parameter_overrides = self.parse_key_value_arg(
287
parsed_args.parameter_overrides,
288
self.PARAMETER_OVERRIDE_CMD)
289
290
tags_dict = self.parse_key_value_arg(parsed_args.tags, self.TAGS_CMD)
291
tags = [{"Key": key, "Value": value}
292
for key, value in tags_dict.items()]
293
294
template_dict = yaml_parse(template_str)
295
296
parameters = self.merge_parameters(template_dict, parameter_overrides)
297
298
template_size = os.path.getsize(parsed_args.template_file)
299
if template_size > 51200 and not parsed_args.s3_bucket:
300
raise exceptions.DeployBucketRequiredError()
301
302
bucket = parsed_args.s3_bucket
303
if bucket:
304
s3_client = create_nested_client(
305
self._session,
306
"s3",
307
config=Config(signature_version='s3v4'),
308
region_name=parsed_globals.region,
309
verify=parsed_globals.verify_ssl)
310
311
s3_uploader = S3Uploader(s3_client,
312
bucket,
313
parsed_args.s3_prefix,
314
parsed_args.kms_key_id,
315
parsed_args.force_upload)
316
else:
317
s3_uploader = None
318
319
deployer = Deployer(cloudformation_client)
320
v2_debug = resolve_v2_debug_mode(parsed_globals)
321
return self.deploy(deployer, stack_name, template_str,
322
parameters, parsed_args.capabilities,
323
parsed_args.execute_changeset, parsed_args.role_arn,
324
parsed_args.notification_arns, s3_uploader,
325
tags, parsed_args.fail_on_empty_changeset,
326
parsed_args.disable_rollback, v2_debug)
327
328
def deploy(self, deployer, stack_name, template_str,
329
parameters, capabilities, execute_changeset, role_arn,
330
notification_arns, s3_uploader, tags,
331
fail_on_empty_changeset=True, disable_rollback=False,
332
v2_debug=False):
333
try:
334
if v2_debug and fail_on_empty_changeset:
335
uni_print(
336
'\nAWS CLI v2 UPGRADE WARNING: In AWS CLI v2, deploying '
337
'an AWS CloudFormation Template that results in an empty '
338
'changeset will NOT result in an error by default. This '
339
'is different from v1 behavior, where empty changesets '
340
'result in an error by default. To migrate to v2 behavior '
341
'and resolve this warning, you can add the '
342
'`--no-fail-on-empty-changeset` flag to the command. '
343
'See https://docs.aws.amazon.com/cli/latest/userguide/'
344
'cliv2-migration-changes.html#cliv2-migration-cfn.\n',
345
out_file=sys.stderr
346
)
347
result = deployer.create_and_wait_for_changeset(
348
stack_name=stack_name,
349
cfn_template=template_str,
350
parameter_values=parameters,
351
capabilities=capabilities,
352
role_arn=role_arn,
353
notification_arns=notification_arns,
354
s3_uploader=s3_uploader,
355
tags=tags
356
)
357
except exceptions.ChangeEmptyError as ex:
358
if fail_on_empty_changeset:
359
raise
360
write_exception(ex, outfile=get_stdout_text_writer())
361
return 0
362
363
if execute_changeset:
364
deployer.execute_changeset(result.changeset_id, stack_name,
365
disable_rollback)
366
deployer.wait_for_execute(stack_name, result.changeset_type)
367
sys.stdout.write(self.MSG_EXECUTE_SUCCESS.format(
368
stack_name=stack_name))
369
else:
370
sys.stdout.write(self.MSG_NO_EXECUTE_CHANGESET.format(
371
changeset_id=result.changeset_id))
372
373
sys.stdout.flush()
374
return 0
375
376
def merge_parameters(self, template_dict, parameter_overrides):
377
"""
378
CloudFormation CreateChangeset requires a value for every parameter
379
from the template, either specifying a new value or use previous value.
380
For convenience, this method will accept new parameter values and
381
generates a dict of all parameters in a format that ChangeSet API
382
will accept
383
384
:param parameter_overrides:
385
:return:
386
"""
387
parameter_values = []
388
389
if not isinstance(template_dict.get("Parameters", None), dict):
390
return parameter_values
391
392
for key, value in template_dict["Parameters"].items():
393
394
obj = {
395
"ParameterKey": key
396
}
397
398
if key in parameter_overrides:
399
obj["ParameterValue"] = parameter_overrides[key]
400
else:
401
obj["UsePreviousValue"] = True
402
403
parameter_values.append(obj)
404
405
return parameter_values
406
407
def parse_key_value_arg(self, arg_value, argname):
408
"""
409
Converts arguments that are passed as list of "Key=Value" strings
410
into a real dictionary.
411
412
:param arg_value list: Array of strings, where each string is of
413
form Key=Value
414
:param argname string: Name of the argument that contains the value
415
:return dict: Dictionary representing the key/value pairs
416
"""
417
result = {}
418
for data in arg_value:
419
420
# Split at first '=' from left
421
key_value_pair = data.split("=", 1)
422
423
if len(key_value_pair) != 2:
424
raise exceptions.InvalidKeyValuePairArgumentError(
425
argname=argname,
426
value=key_value_pair)
427
428
result[key_value_pair[0]] = key_value_pair[1]
429
430
return result
431
432
433
434
435