Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aws
GitHub Repository: aws/aws-cli
Path: blob/develop/awscli/customizations/cloudformation/deploy.py
1567 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.utils import create_nested_client, write_exception
28
29
LOG = logging.getLogger(__name__)
30
31
32
class DeployCommand(BasicCommand):
33
34
MSG_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")
41
42
MSG_EXECUTE_SUCCESS = "Successfully created/updated stack - {stack_name}\n"
43
44
PARAMETER_OVERRIDE_CMD = "parameter-overrides"
45
TAGS_CMD = "tags"
46
47
NAME = 'deploy'
48
DESCRIPTION = BasicCommand.FROM_FILE("cloudformation",
49
"_deploy_description.rst")
50
51
ARG_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
},
97
98
{
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
)
156
157
},
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
]
267
268
def _run_main(self, parsed_args, parsed_globals):
269
cloudformation_client = \
270
create_nested_client(
271
self._session, 'cloudformation', region_name=parsed_globals.region,
272
endpoint_url=parsed_globals.endpoint_url,
273
verify=parsed_globals.verify_ssl)
274
275
template_path = parsed_args.template_file
276
if not os.path.isfile(template_path):
277
raise exceptions.InvalidTemplatePathError(
278
template_path=template_path)
279
280
# Parse parameters
281
with open(template_path, "r") as handle:
282
template_str = handle.read()
283
284
stack_name = parsed_args.stack_name
285
parameter_overrides = self.parse_key_value_arg(
286
parsed_args.parameter_overrides,
287
self.PARAMETER_OVERRIDE_CMD)
288
289
tags_dict = self.parse_key_value_arg(parsed_args.tags, self.TAGS_CMD)
290
tags = [{"Key": key, "Value": value}
291
for key, value in tags_dict.items()]
292
293
template_dict = yaml_parse(template_str)
294
295
parameters = self.merge_parameters(template_dict, parameter_overrides)
296
297
template_size = os.path.getsize(parsed_args.template_file)
298
if template_size > 51200 and not parsed_args.s3_bucket:
299
raise exceptions.DeployBucketRequiredError()
300
301
bucket = parsed_args.s3_bucket
302
if bucket:
303
s3_client = create_nested_client(
304
self._session,
305
"s3",
306
config=Config(signature_version='s3v4'),
307
region_name=parsed_globals.region,
308
verify=parsed_globals.verify_ssl)
309
310
s3_uploader = S3Uploader(s3_client,
311
bucket,
312
parsed_args.s3_prefix,
313
parsed_args.kms_key_id,
314
parsed_args.force_upload)
315
else:
316
s3_uploader = None
317
318
deployer = Deployer(cloudformation_client)
319
return self.deploy(deployer, stack_name, template_str,
320
parameters, parsed_args.capabilities,
321
parsed_args.execute_changeset, parsed_args.role_arn,
322
parsed_args.notification_arns, s3_uploader,
323
tags, parsed_args.fail_on_empty_changeset,
324
parsed_args.disable_rollback)
325
326
def deploy(self, deployer, stack_name, template_str,
327
parameters, capabilities, execute_changeset, role_arn,
328
notification_arns, s3_uploader, tags,
329
fail_on_empty_changeset=True, disable_rollback=False):
330
try:
331
result = deployer.create_and_wait_for_changeset(
332
stack_name=stack_name,
333
cfn_template=template_str,
334
parameter_values=parameters,
335
capabilities=capabilities,
336
role_arn=role_arn,
337
notification_arns=notification_arns,
338
s3_uploader=s3_uploader,
339
tags=tags
340
)
341
except exceptions.ChangeEmptyError as ex:
342
if fail_on_empty_changeset:
343
raise
344
write_exception(ex, outfile=get_stdout_text_writer())
345
return 0
346
347
if execute_changeset:
348
deployer.execute_changeset(result.changeset_id, stack_name,
349
disable_rollback)
350
deployer.wait_for_execute(stack_name, result.changeset_type)
351
sys.stdout.write(self.MSG_EXECUTE_SUCCESS.format(
352
stack_name=stack_name))
353
else:
354
sys.stdout.write(self.MSG_NO_EXECUTE_CHANGESET.format(
355
changeset_id=result.changeset_id))
356
357
sys.stdout.flush()
358
return 0
359
360
def merge_parameters(self, template_dict, parameter_overrides):
361
"""
362
CloudFormation CreateChangeset requires a value for every parameter
363
from the template, either specifying a new value or use previous value.
364
For convenience, this method will accept new parameter values and
365
generates a dict of all parameters in a format that ChangeSet API
366
will accept
367
368
:param parameter_overrides:
369
:return:
370
"""
371
parameter_values = []
372
373
if not isinstance(template_dict.get("Parameters", None), dict):
374
return parameter_values
375
376
for key, value in template_dict["Parameters"].items():
377
378
obj = {
379
"ParameterKey": key
380
}
381
382
if key in parameter_overrides:
383
obj["ParameterValue"] = parameter_overrides[key]
384
else:
385
obj["UsePreviousValue"] = True
386
387
parameter_values.append(obj)
388
389
return parameter_values
390
391
def parse_key_value_arg(self, arg_value, argname):
392
"""
393
Converts arguments that are passed as list of "Key=Value" strings
394
into a real dictionary.
395
396
:param arg_value list: Array of strings, where each string is of
397
form Key=Value
398
:param argname string: Name of the argument that contains the value
399
:return dict: Dictionary representing the key/value pairs
400
"""
401
result = {}
402
for data in arg_value:
403
404
# Split at first '=' from left
405
key_value_pair = data.split("=", 1)
406
407
if len(key_value_pair) != 2:
408
raise exceptions.InvalidKeyValuePairArgumentError(
409
argname=argname,
410
value=key_value_pair)
411
412
result[key_value_pair[0]] = key_value_pair[1]
413
414
return result
415
416
417
418
419