1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
|
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0e
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import collections
import json
import tempfile
from awscli.customizations.cloudformation import exceptions
from awscli.customizations.cloudformation.deploy import DeployCommand
from awscli.customizations.cloudformation.deployer import Deployer
from awscli.customizations.cloudformation.yamlhelper import yaml_parse
from awscli.customizations.exceptions import ParamValidationError
from awscli.testutils import mock
from tests.unit.customizations.cloudformation import BaseYAMLTest
class FakeArgs:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __contains__(self, key):
return key in self.__dict__
def get_example_template():
return {"Parameters": {"Key1": "Value1"}, "Resources": {"Resource1": {}}}
ChangeSetResult = collections.namedtuple(
"ChangeSetResult", ["changeset_id", "changeset_type"]
)
class TestDeployCommand(BaseYAMLTest):
def setUp(self):
super(TestDeployCommand, self).setUp()
self.session = mock.Mock()
self.session.get_scoped_config.return_value = {}
self.parsed_args = FakeArgs(
template_file='./foo',
stack_name="some_stack_name",
parameter_overrides=["Key1=Value1", "Key2=Value2"],
no_execute_changeset=False,
execute_changeset=True,
disable_rollback=True,
capabilities=None,
role_arn=None,
notification_arns=[],
fail_on_empty_changeset=True,
s3_bucket=None,
s3_prefix="some prefix",
kms_key_id="some kms key id",
force_upload=True,
tags=["tagkey1=tagvalue1"],
)
self.parsed_globals = FakeArgs(
region="us-east-1", endpoint_url=None, verify_ssl=None
)
self.deploy_command = DeployCommand(self.session)
self.deployer = Deployer(mock.Mock())
self.deployer.create_and_wait_for_changeset = mock.Mock()
self.deployer.execute_changeset = mock.Mock()
self.deployer.wait_for_execute = mock.Mock()
@mock.patch("awscli.customizations.cloudformation.deploy.yaml_parse")
def test_command_invoked(self, mock_yaml_parse):
"""
Tests that deploy method is invoked when command is run
"""
fake_parameter_overrides = []
fake_tags_dict = {"tagkey1": "tagvalue1"}
fake_tags = [{"Key": "tagkey1", "Value": "tagvalue1"}]
fake_parameters = "some return value"
template_str = "some template"
with tempfile.NamedTemporaryFile() as handle:
file_path = handle.name
open_mock = mock.mock_open()
# Patch the file open method to return template string
with mock.patch(
"awscli.customizations.cloudformation.deploy.compat_open",
open_mock(read_data=template_str),
) as open_mock:
fake_template = get_example_template()
mock_yaml_parse.return_value = fake_template
self.deploy_command.deploy = mock.MagicMock()
self.deploy_command.deploy.return_value = 0
self.deploy_command.parse_key_value_arg = mock.Mock()
self.deploy_command.parse_key_value_arg.side_effect = [
fake_parameter_overrides,
fake_tags_dict,
]
self.deploy_command.merge_parameters = mock.MagicMock(
return_value=fake_parameters
)
self.parsed_args.template_file = file_path
result = self.deploy_command._run_main(
self.parsed_args, parsed_globals=self.parsed_globals
)
self.assertEqual(0, result)
open_mock.assert_called_once_with(file_path, "r")
self.deploy_command.deploy.assert_called_once_with(
mock.ANY,
'some_stack_name',
mock.ANY,
fake_parameters,
None,
not self.parsed_args.no_execute_changeset,
None,
[],
None,
fake_tags,
True,
True,
)
self.deploy_command.parse_key_value_arg.assert_has_calls(
[
mock.call(
self.parsed_args.parameter_overrides,
"parameter-overrides",
),
mock.call(self.parsed_args.tags, "tags"),
]
)
self.deploy_command.merge_parameters.assert_called_once_with(
fake_template, fake_parameter_overrides
)
self.assertEqual(1, mock_yaml_parse.call_count)
def test_invalid_template_file(self):
self.parsed_args.template_file = "sometemplate"
with self.assertRaises(exceptions.InvalidTemplatePathError):
result = self.deploy_command._run_main(
self.parsed_args, parsed_globals=self.parsed_globals
)
@mock.patch(
'awscli.customizations.cloudformation.deploy.os.path.expanduser'
)
def test_expands_user_for_template_file(self, expanduser):
contents = 'Resource:\n' ' Test:\n' ' Type: AWS::Foo::Bar\n'
with tempfile.NamedTemporaryFile('w') as f:
f.write(contents)
f.flush()
fake_expanduser_path = f.name + '.expanduser-file'
with open(fake_expanduser_path, 'w') as f:
f.write(contents)
# The tempfile is now gone so if we weren't using os.path.expanduser()
# in the code, this test would fail to load the file with an
# InvalidTemplatePathError.
expanduser.return_value = fake_expanduser_path
parsed, template_str, _ = self.deploy_command.load_template_file(
f.name
)
self.assertEqual(
parsed, {'Resource': {'Test': {'Type': 'AWS::Foo::Bar'}}}
)
self.assertEqual(template_str, contents)
@mock.patch('awscli.customizations.cloudformation.deploy.os.path.isfile')
@mock.patch('awscli.customizations.cloudformation.deploy.yaml_parse')
@mock.patch('awscli.customizations.cloudformation.deploy.os.path.getsize')
def test_s3_upload_required_but_missing_bucket(
self, mock_getsize, mock_yaml_parse, mock_isfile
):
"""
Tests that large templates are detected prior to deployment
"""
template_str = get_example_template()
mock_getsize.return_value = 51201
mock_isfile.return_value = True
mock_yaml_parse.return_value = template_str
open_mock = mock.mock_open()
with mock.patch(
"awscli.customizations.cloudformation.deploy.compat_open",
open_mock(read_data=template_str),
) as open_mock:
with self.assertRaises(exceptions.DeployBucketRequiredError):
result = self.deploy_command._run_main(
self.parsed_args, parsed_globals=self.parsed_globals
)
@mock.patch('awscli.customizations.cloudformation.deploy.os.path.isfile')
@mock.patch('awscli.customizations.cloudformation.deploy.yaml_parse')
@mock.patch('awscli.customizations.cloudformation.deploy.os.path.getsize')
@mock.patch(
'awscli.customizations.cloudformation.deploy.DeployCommand.deploy'
)
@mock.patch('awscli.customizations.cloudformation.deploy.S3Uploader')
def test_s3_uploader_is_configured_properly(
self,
s3UploaderMock,
deploy_method_mock,
mock_getsize,
mock_yaml_parse,
mock_isfile,
):
"""
Tests that large templates are detected prior to deployment
"""
bucket_name = "mybucket"
template_str = get_example_template()
mock_getsize.return_value = 1024
mock_isfile.return_value = True
mock_yaml_parse.return_value = template_str
open_mock = mock.mock_open()
with mock.patch(
"awscli.customizations.cloudformation.deploy.compat_open",
open_mock(read_data=template_str),
) as open_mock:
self.parsed_args.s3_bucket = bucket_name
s3UploaderObject = mock.Mock()
s3UploaderMock.return_value = s3UploaderObject
result = self.deploy_command._run_main(
self.parsed_args, parsed_globals=self.parsed_globals
)
self.deploy_command.deploy.assert_called_once_with(
mock.ANY,
self.parsed_args.stack_name,
mock.ANY,
mock.ANY,
None,
not self.parsed_args.no_execute_changeset,
None,
[],
s3UploaderObject,
[{"Key": "tagkey1", "Value": "tagvalue1"}],
True,
True,
)
s3UploaderMock.assert_called_once_with(
mock.ANY,
bucket_name,
self.parsed_args.s3_prefix,
self.parsed_args.kms_key_id,
self.parsed_args.force_upload,
)
def test_deploy_success(self):
"""
Tests that we call the deploy command
"""
stack_name = "stack_name"
changeset_id = "some changeset"
parameters = ["a", "b"]
template = "cloudformation template"
capabilities = ["foo", "bar"]
execute_changeset = True
changeset_type = "CREATE"
role_arn = "arn:aws:iam::1234567890:role"
notification_arns = ["arn:aws:sns:region:1234567890:notify"]
s3_uploader = None
tags = [{"Key": "key1", "Value": "val1"}]
# Set the mock to return this fake changeset_id
self.deployer.create_and_wait_for_changeset.return_value = (
ChangeSetResult(changeset_id, changeset_type)
)
rc = self.deploy_command.deploy(
self.deployer,
stack_name,
template,
parameters,
capabilities,
execute_changeset,
role_arn,
notification_arns,
s3_uploader,
tags,
)
self.assertEqual(rc, 0)
self.deployer.create_and_wait_for_changeset.assert_called_once_with(
stack_name=stack_name,
cfn_template=template,
parameter_values=parameters,
capabilities=capabilities,
role_arn=role_arn,
notification_arns=notification_arns,
s3_uploader=s3_uploader,
tags=tags,
)
# since execute_changeset is set to True, deploy() will execute changeset
self.deployer.execute_changeset.assert_called_once_with(
changeset_id, stack_name, False
)
self.deployer.wait_for_execute.assert_called_once_with(
stack_name, changeset_type
)
def test_deploy_no_execute(self):
stack_name = "stack_name"
changeset_id = "some changeset"
parameters = ["a", "b"]
template = "cloudformation template"
capabilities = ["foo", "bar"]
execute_changeset = False
role_arn = "arn:aws:iam::1234567890:role"
notification_arns = ["arn:aws:sns:region:1234567890:notify"]
s3_uploader = None
tags = [{"Key": "key1", "Value": "val1"}]
self.deployer.create_and_wait_for_changeset.return_value = (
ChangeSetResult(changeset_id, "CREATE")
)
rc = self.deploy_command.deploy(
self.deployer,
stack_name,
template,
parameters,
capabilities,
execute_changeset,
role_arn,
notification_arns,
s3_uploader,
tags,
)
self.assertEqual(rc, 0)
self.deployer.create_and_wait_for_changeset.assert_called_once_with(
stack_name=stack_name,
cfn_template=template,
parameter_values=parameters,
capabilities=capabilities,
role_arn=role_arn,
notification_arns=notification_arns,
s3_uploader=s3_uploader,
tags=tags,
)
# since execute_changeset is set to True, deploy() will execute changeset
self.deployer.execute_changeset.assert_not_called()
self.deployer.wait_for_execute.assert_not_called()
def test_deploy_raise_exception(self):
stack_name = "stack_name"
changeset_id = "some changeset"
parameters = ["a", "b"]
template = "cloudformation template"
capabilities = ["foo", "bar"]
execute_changeset = True
role_arn = "arn:aws:iam::1234567890:role"
notification_arns = ["arn:aws:sns:region:1234567890:notify"]
s3_uploader = None
tags = [{"Key": "key1", "Value": "val1"}]
self.deployer.wait_for_execute.side_effect = RuntimeError("Some error")
with self.assertRaises(RuntimeError):
self.deploy_command.deploy(
self.deployer,
stack_name,
template,
parameters,
capabilities,
execute_changeset,
role_arn,
notification_arns,
s3_uploader,
tags,
)
def test_deploy_raises_exception_on_empty_changeset(self):
stack_name = "stack_name"
parameters = ["a", "b"]
template = "cloudformation template"
capabilities = ["foo", "bar"]
execute_changeset = True
role_arn = "arn:aws:iam::1234567890:role"
notification_arns = ["arn:aws:sns:region:1234567890:notify"]
tags = []
empty_changeset = exceptions.ChangeEmptyError(stack_name=stack_name)
changeset_func = self.deployer.create_and_wait_for_changeset
changeset_func.side_effect = empty_changeset
with self.assertRaises(exceptions.ChangeEmptyError):
self.deploy_command.deploy(
self.deployer,
stack_name,
template,
parameters,
capabilities,
execute_changeset,
role_arn,
notification_arns,
None,
tags,
fail_on_empty_changeset=True,
)
def test_deploy_does_not_raise_exception_on_empty_changeset(self):
stack_name = "stack_name"
parameters = ["a", "b"]
template = "cloudformation template"
capabilities = ["foo", "bar"]
execute_changeset = True
role_arn = "arn:aws:iam::1234567890:role"
notification_arns = ["arn:aws:sns:region:1234567890:notify"]
empty_changeset = exceptions.ChangeEmptyError(stack_name=stack_name)
changeset_func = self.deployer.create_and_wait_for_changeset
changeset_func.side_effect = empty_changeset
self.deploy_command.deploy(
self.deployer,
stack_name,
template,
parameters,
capabilities,
execute_changeset,
role_arn,
notification_arns,
s3_uploader=None,
tags=[],
fail_on_empty_changeset=False,
)
def test_deploy_empty_changeset_does_not_raise_exception_by_default(self):
stack_name = "stack_name"
parameters = ["a", "b"]
template = "cloudformation template"
capabilities = ["foo", "bar"]
execute_changeset = True
role_arn = "arn:aws:iam::1234567890:role"
notification_arns = ["arn:aws:sns:region:1234567890:notify"]
empty_changeset = exceptions.ChangeEmptyError(stack_name=stack_name)
changeset_func = self.deployer.create_and_wait_for_changeset
changeset_func.side_effect = empty_changeset
self.deploy_command.deploy(
self.deployer,
stack_name,
template,
parameters,
capabilities,
execute_changeset,
role_arn,
notification_arns,
s3_uploader=None,
tags=[],
)
def test_parse_key_value_arg_success(self):
"""
Tests that we can parse parameter arguments provided in proper format
Expected format: ["Key=Value", "Key=Value"]
:return:
"""
argname = "parameter-overrides"
data = ["Key1=Value1", 'Key2=[1,2,3]', 'Key3={"a":"val", "b": 2}']
output = {
"Key1": "Value1",
"Key2": '[1,2,3]',
"Key3": '{"a":"val", "b": 2}',
}
result = self.deploy_command.parse_key_value_arg(data, argname)
self.assertEqual(result, output)
# Empty input should return empty output
result = self.deploy_command.parse_key_value_arg([], argname)
self.assertEqual(result, {})
def test_parse_parameter_override_with_cf_data_format(self):
"""
Tests that we can parse parameter arguments from file in
CloudFormation parameters file format
:return:
"""
data = json.dumps(
[
{'ParameterKey': 'Key1', 'ParameterValue': 'Value1'},
{'ParameterKey': 'Key2', 'ParameterValue': '[1,2,3]'},
{
'ParameterKey': 'Key3',
'ParameterValue': '{"a":"val", "b": 2}',
},
]
)
output = {
"Key1": "Value1",
"Key2": '[1,2,3]',
"Key3": '{"a":"val", "b": 2}',
}
result = self.deploy_command.parse_parameter_overrides(data)
self.assertEqual(result, output)
def test_validate_parameter_override_with_cf_data_format(self):
"""
Tests that we through exception if have redundant keys in json
CloudFormation parameters file format
:return:
"""
data = json.dumps(
[
{
'ParameterKey': 'Key1',
'ParameterValue': 'Value1',
'RedundantKey': 'foo',
}
]
)
with self.assertRaises(ParamValidationError):
self.deploy_command.parse_parameter_overrides(data)
def test_parse_parameter_override_with_codepipeline_data_format(self):
"""
Tests that we can parse parameter arguments from file in
CodePipeline parameters file format
:return:
"""
data = json.dumps(
{
'Parameters': {
"Key1": "Value1",
"Key2": '[1,2,3]',
"Key3": '{"a":"val", "b": 2}',
}
}
)
output = {
"Key1": "Value1",
"Key2": '[1,2,3]',
"Key3": '{"a":"val", "b": 2}',
}
result = self.deploy_command.parse_parameter_overrides(data)
self.assertEqual(result, output)
def test_parse_parameter_override_with_deploy_data_format_from_file(self):
"""
Tests that we can parse parameter arguments from file in
deploy command parameters file format
:return:
"""
data = json.dumps(
['Key1=Value1', 'Key2=[1,2,3]', 'Key3={"a":"val", "b": 2}']
)
output = {
"Key1": "Value1",
"Key2": '[1,2,3]',
"Key3": '{"a":"val", "b": 2}',
}
result = self.deploy_command.parse_parameter_overrides(data)
self.assertEqual(result, output)
def test_parse_parameter_override_with_inline_json(self):
data = [
json.dumps(
['Key1=Value1', 'Key2=[1,2,3]', 'Key3={"a":"val", "b": 2}']
)
]
output = {
"Key1": "Value1",
"Key2": '[1,2,3]',
"Key3": '{"a":"val", "b": 2}',
}
result = self.deploy_command.parse_parameter_overrides(data)
self.assertEqual(result, output)
def test_parse_parameter_override_with_deploy_data_format(self):
"""
Tests that we can parse parameter arguments in
deploy command parameters command line format
:return:
"""
data = ['Key1=Value1', 'Key2=[1,2,3]', 'Key3={"a":"val", "b": 2}']
output = {
"Key1": "Value1",
"Key2": '[1,2,3]',
"Key3": '{"a":"val", "b": 2}',
}
result = self.deploy_command.parse_parameter_overrides(data)
self.assertEqual(result, output)
def test_parse_key_value_arg_invalid_input(self):
# non-list input
argname = "parameter-overrides"
with self.assertRaises(exceptions.InvalidKeyValuePairArgumentError):
self.deploy_command.parse_key_value_arg("hello=world", argname)
# missing equal to sign
with self.assertRaises(exceptions.InvalidKeyValuePairArgumentError):
self.deploy_command.parse_key_value_arg(["hello world"], argname)
def test_merge_parameters_success(self):
"""
Tests that we can merge parameters specified in CloudFormation template
with override values specified as commandline arguments
"""
template = {
"Parameters": {
"Key1": {"Type": "String"},
"Key2": {"Type": "String"},
"Key3": "Something",
"Key4": {"Type": "Number"},
"KeyWithDefaultValue": {
"Type": "String",
"Default": "something",
},
"KeyWithDefaultValueButOverridden": {
"Type": "String",
"Default": "something",
},
}
}
overrides = {
"Key1": "Value1",
"Key3": "Value3",
"KeyWithDefaultValueButOverridden": "Value4",
}
expected_result = [
# Overriden values
{"ParameterKey": "Key1", "ParameterValue": "Value1"},
{"ParameterKey": "Key3", "ParameterValue": "Value3"},
# Parameter contains default value, but overridden with new value
{
"ParameterKey": "KeyWithDefaultValueButOverridden",
"ParameterValue": "Value4",
},
# non-overriden values
{"ParameterKey": "Key2", "UsePreviousValue": True},
{"ParameterKey": "Key4", "UsePreviousValue": True},
# Parameter with default value but NOT overridden.
# Use previous value, but this gets removed later when we are creating stack for first time
{"ParameterKey": "KeyWithDefaultValue", "UsePreviousValue": True},
]
self.assertItemsEqual(
self.deploy_command.merge_parameters(template, overrides),
expected_result,
)
def test_merge_parameters_success_nothing_to_override(self):
"""
Tests that we can merge parameters specified in CloudFormation template
with override values specified as commandline arguments
"""
template = {
"Parameters": {
"Key1": {"Type": "String"},
"Key2": {"Type": "String"},
"Key3": "Something",
"Key4": {"Type": "Number"},
}
}
overrides = {
# Key5 is not in the template. We will simply skip this key
"Key5": "Value5"
}
expected_result = [
{"ParameterKey": "Key1", "UsePreviousValue": True},
{"ParameterKey": "Key2", "UsePreviousValue": True},
{"ParameterKey": "Key3", "UsePreviousValue": True},
{"ParameterKey": "Key4", "UsePreviousValue": True},
]
self.assertItemsEqual(
self.deploy_command.merge_parameters(template, overrides),
expected_result,
)
# Parameters definition is empty. Nothing to override
result = self.deploy_command.merge_parameters(
{"Parameters": {}}, overrides
)
self.assertEqual(result, [])
def test_merge_parameters_invalid_input(self):
# Template does not contain "Parameters" definition
result = self.deploy_command.merge_parameters({}, {"Key": "Value"})
self.assertEqual(result, [])
# Parameters definition is invalid
result = self.deploy_command.merge_parameters(
{"Parameters": "foo"}, {"Key": "Value"}
)
self.assertEqual(result, [])
|