-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathmanaged_cloudformation_stack.py
More file actions
309 lines (276 loc) · 12.3 KB
/
managed_cloudformation_stack.py
File metadata and controls
309 lines (276 loc) · 12.3 KB
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
"""
Bootstrap's user's development environment by creating cloud resources required by SAM CLI
"""
import logging
from collections.abc import Collection
from typing import Dict, List, Optional, Union, cast
import boto3
import click
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError, NoCredentialsError, NoRegionError, ProfileNotFound
from samcli.commands.exceptions import AWSServiceClientError, RegionError, UserException
LOG = logging.getLogger(__name__)
class ManagedStackError(UserException):
def __init__(self, ex):
self.ex = ex
message_fmt = f"Failed to create managed resources: {ex}"
super().__init__(message=message_fmt.format(ex=self.ex))
class StackOutput:
def __init__(self, stack_output: List[Dict[str, str]]):
self._stack_output: List[Dict[str, str]] = stack_output
def get(self, key) -> Optional[str]:
try:
return next(o for o in self._stack_output if o.get("OutputKey") == key).get("OutputValue")
except StopIteration:
return None
def update_stack(
region: Optional[str],
stack_name: str,
template_body: str,
profile: Optional[str] = None,
parameter_overrides: Optional[Dict[str, Union[str, List[str]]]] = None,
) -> StackOutput:
"""
create or update a CloudFormation stack
Parameters
----------
region: str
AWS region for the CloudFormation stack
stack_name: str
CloudFormation stack name
template_body: str
CloudFormation template's content
profile: Optional[str]
AWS named profile for the AWS account
parameter_overrides: Optional[Dict[str, Union[str, List[str]]]]
Values of template parameters, if any.
Returns
-------
StackOutput:
Stack output section(list of OutputKey, OutputValue pairs)
"""
try:
if profile:
session = boto3.Session(profile_name=profile, region_name=region if region else None)
cloudformation_client = session.client("cloudformation")
else:
cloudformation_client = boto3.client(
"cloudformation", config=Config(region_name=region if region else None)
)
except ProfileNotFound as ex:
raise AWSServiceClientError(
f"Error Setting Up Managed Stack Client: the provided AWS name profile '{profile}' is not found. "
"please check the documentation for setting up a named profile: "
"https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html"
) from ex
except NoCredentialsError as ex:
raise AWSServiceClientError(
"Error Setting Up Managed Stack Client: Unable to resolve credentials for the AWS SDK for Python client. "
"Please see their documentation for options to pass in credentials: "
"https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html"
) from ex
except NoRegionError as ex:
raise RegionError(
"Error Setting Up Managed Stack Client: Unable to resolve a region. "
"Please provide a region via the --region parameter or by the AWS_DEFAULT_REGION environment variable."
) from ex
return _create_or_update_stack(cloudformation_client, stack_name, template_body, parameter_overrides)
def manage_stack(
region: Optional[str],
stack_name: str,
template_body: str,
profile: Optional[str] = None,
parameter_overrides: Optional[Dict[str, Union[str, List[str]]]] = None,
) -> StackOutput:
"""
get or create a CloudFormation stack
Parameters
----------
region: str
AWS region for the CloudFormation stack
stack_name: str
CloudFormation stack name
template_body: str
CloudFormation template's content
profile: Optional[str]
AWS named profile for the AWS account
parameter_overrides: Optional[Dict[str, Union[str, List[str]]]]
Values of template parameters, if any.
Returns
-------
StackOutput:
Stack output section(list of OutputKey, OutputValue pairs)
"""
try:
if profile:
session = boto3.Session(profile_name=profile, region_name=region if region else None)
cloudformation_client = session.client("cloudformation")
else:
cloudformation_client = boto3.client(
"cloudformation", config=Config(region_name=region if region else None)
)
except ProfileNotFound as ex:
raise AWSServiceClientError(
f"Error Setting Up Managed Stack Client: the provided AWS name profile '{profile}' is not found. "
"please check the documentation for setting up a named profile: "
"https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html"
) from ex
except NoCredentialsError as ex:
raise AWSServiceClientError(
"Error Setting Up Managed Stack Client: Unable to resolve credentials for the AWS SDK for Python client. "
"Please see their documentation for options to pass in credentials: "
"https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html"
) from ex
except NoRegionError as ex:
raise RegionError(
"Error Setting Up Managed Stack Client: Unable to resolve a region. "
"Please provide a region via the --region parameter or by the AWS_DEFAULT_REGION environment variable."
) from ex
return _create_or_get_stack(cloudformation_client, stack_name, template_body, parameter_overrides)
# Todo Add _update_stack to handle the case when the values of the stack parameter got changed
def _create_or_get_stack(
cloudformation_client,
stack_name: str,
template_body: str,
parameter_overrides: Optional[Dict[str, Union[str, List[str]]]] = None,
) -> StackOutput:
try:
ds_resp = cloudformation_client.describe_stacks(StackName=stack_name)
stacks = ds_resp["Stacks"]
stack = stacks[0]
_check_sanity_of_stack(stack)
stack_outputs = cast(List[Dict[str, str]], stack["Outputs"])
return StackOutput(stack_outputs)
except ClientError:
LOG.debug("Managed S3 stack [%s] not found. Creating a new one.", stack_name)
try:
stack = _create_stack(
cloudformation_client, stack_name, template_body, parameter_overrides
) # exceptions are not captured from subcommands
_check_sanity_of_stack(stack)
stack_outputs = cast(List[Dict[str, str]], stack["Outputs"])
return StackOutput(stack_outputs)
except (ClientError, BotoCoreError) as ex:
LOG.debug("Failed to create managed resources", exc_info=ex)
raise ManagedStackError(str(ex)) from ex
def _create_or_update_stack(
cloudformation_client,
stack_name: str,
template_body: str,
parameter_overrides: Optional[Dict[str, Union[str, List[str]]]] = None,
) -> StackOutput:
try:
cloudformation_client.describe_stacks(StackName=stack_name)
stack = _update_stack(cloudformation_client, stack_name, template_body, parameter_overrides)
_check_sanity_of_stack(stack)
stack_outputs = cast(List[Dict[str, str]], stack["Outputs"])
return StackOutput(stack_outputs)
except ClientError:
LOG.debug("Managed S3 stack [%s] not found. Creating a new one.", stack_name)
try:
stack = _create_stack(
cloudformation_client, stack_name, template_body, parameter_overrides
) # exceptions are not captured from subcommands
_check_sanity_of_stack(stack)
stack_outputs = cast(List[Dict[str, str]], stack["Outputs"])
return StackOutput(stack_outputs)
except (ClientError, BotoCoreError) as ex:
LOG.debug("Failed to create managed resources", exc_info=ex)
raise ManagedStackError(str(ex)) from ex
def _check_sanity_of_stack(stack):
stack_name = stack.get("StackName")
tags = stack.get("Tags", None)
outputs = stack.get("Outputs", None)
# For some edge cases, stack could be in invalid state
# Check if stack information contains the Tags and Outputs as we expected
if tags is None or outputs is None:
stack_state = stack.get("StackStatus", None)
msg = (
f"Stack {stack_name} is missing Tags and/or Outputs information and therefore not in a "
f"healthy state (Current state:{stack_state}). Failing as the stack was likely not created "
f"by the AWS SAM CLI"
)
raise UserException(msg)
# Sanity check for non-none stack? Sanity check for tag?
try:
sam_cli_tag = next(t for t in tags if t["Key"] == "ManagedStackSource")
if not sam_cli_tag["Value"] == "AwsSamCli":
msg = (
"Stack "
+ stack_name
+ " ManagedStackSource tag shows "
+ sam_cli_tag["Value"]
+ " which does not match the AWS SAM CLI generated tag value of AwsSamCli. "
"Failing as the stack was likely not created by the AWS SAM CLI."
)
raise UserException(msg)
except StopIteration as ex:
msg = (
"Stack " + stack_name + " exists, but the ManagedStackSource tag is missing. "
"Failing as the stack was likely not created by the AWS SAM CLI."
)
raise UserException(msg) from ex
def _create_stack(
cloudformation_client,
stack_name: str,
template_body: str,
parameter_overrides: Optional[Dict[str, Union[str, List[str]]]] = None,
):
click.echo("\tCreating the required resources...")
change_set_name = "InitialCreation"
parameters = _generate_stack_parameters(parameter_overrides)
change_set_resp = cloudformation_client.create_change_set(
StackName=stack_name,
TemplateBody=template_body,
Tags=[{"Key": "ManagedStackSource", "Value": "AwsSamCli"}],
ChangeSetType="CREATE",
ChangeSetName=change_set_name, # this must be unique for the stack, but we only create so that's fine
Capabilities=["CAPABILITY_IAM"],
Parameters=parameters,
)
stack_id = change_set_resp["StackId"]
change_waiter = cloudformation_client.get_waiter("change_set_create_complete")
change_waiter.wait(
ChangeSetName=change_set_name, StackName=stack_name, WaiterConfig={"Delay": 15, "MaxAttempts": 60}
)
cloudformation_client.execute_change_set(ChangeSetName=change_set_name, StackName=stack_name)
stack_waiter = cloudformation_client.get_waiter("stack_create_complete")
stack_waiter.wait(StackName=stack_id, WaiterConfig={"Delay": 15, "MaxAttempts": 60})
ds_resp = cloudformation_client.describe_stacks(StackName=stack_name)
stacks = ds_resp["Stacks"]
click.echo("\tSuccessfully created!")
return stacks[0]
def _update_stack(
cloudformation_client,
stack_name: str,
template_body: str,
parameter_overrides: Optional[Dict[str, Union[str, List[str]]]] = None,
):
click.echo("\tUpdating the required resources...")
parameters = _generate_stack_parameters(parameter_overrides)
us_resp = cloudformation_client.update_stack(
StackName=stack_name,
TemplateBody=template_body,
Tags=[{"Key": "ManagedStackSource", "Value": "AwsSamCli"}],
Capabilities=["CAPABILITY_IAM", "CAPABILITY_AUTO_EXPAND"],
Parameters=parameters,
)
stack_id = us_resp["StackId"]
stack_waiter = cloudformation_client.get_waiter("stack_update_complete")
stack_waiter.wait(StackName=stack_id, WaiterConfig={"Delay": 15, "MaxAttempts": 60})
ds_resp = cloudformation_client.describe_stacks(StackName=stack_name)
stacks = ds_resp["Stacks"]
click.echo("\tSuccessfully updated!")
return stacks[0]
def _generate_stack_parameters(
parameter_overrides: Optional[Dict[str, Union[str, List[str]]]] = None,
) -> List[Dict[str, str]]:
parameters = []
if parameter_overrides:
for key, value in parameter_overrides.items():
norm_value = value
if isinstance(norm_value, Collection) and not isinstance(norm_value, str):
# Assumption: values don't include commas or spaces. Need to refactor to handle such a case if needed.
norm_value = ",".join(norm_value)
parameters.append({"ParameterKey": key, "ParameterValue": norm_value})
return parameters