| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2017, Ansible Project |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
--- |
| 9 |
module: cloudformation |
| 10 |
version_added: 1.0.0 |
| 11 |
short_description: Create or delete an AWS CloudFormation stack |
| 12 |
description: |
| 13 |
- Launches or updates an AWS CloudFormation stack and waits for it complete. |
| 14 |
options: |
| 15 |
stack_name: |
| 16 |
description: |
| 17 |
- Name of the CloudFormation stack. |
| 18 |
required: true |
| 19 |
type: str |
| 20 |
disable_rollback: |
| 21 |
description: |
| 22 |
- If a stacks fails to form, rollback will remove the stack. |
| 23 |
default: false |
| 24 |
type: bool |
| 25 |
on_create_failure: |
| 26 |
description: |
| 27 |
- Action to take upon failure of stack creation. Incompatible with the O(disable_rollback) option. |
| 28 |
choices: |
| 29 |
- DO_NOTHING |
| 30 |
- ROLLBACK |
| 31 |
- DELETE |
| 32 |
type: str |
| 33 |
create_timeout: |
| 34 |
description: |
| 35 |
- The amount of time (in minutes) that can pass before the stack status becomes V(CREATE_FAILED). |
| 36 |
type: int |
| 37 |
template_parameters: |
| 38 |
description: |
| 39 |
- A list of hashes of all the template variables for the stack. The value can be a string or a dict. |
| 40 |
- Dict can be used to set additional template parameter attributes like UsePreviousValue (see example). |
| 41 |
default: {} |
| 42 |
type: dict |
| 43 |
state: |
| 44 |
description: |
| 45 |
- If O(state=present), stack will be created. |
| 46 |
- If O(state=present) and if stack exists and template has changed, it will be updated. |
| 47 |
- If O(state=absent), stack will be removed. |
| 48 |
default: present |
| 49 |
choices: [ present, absent ] |
| 50 |
type: str |
| 51 |
template: |
| 52 |
description: |
| 53 |
- The local path of the CloudFormation template. |
| 54 |
- This must be the full path to the file, relative to the working directory. If using roles this may look |
| 55 |
like V(roles/cloudformation/files/cloudformation-example.json). |
| 56 |
- If O(state=present) and the stack does not exist yet, either O(template), O(template_body) or O(template_url) |
| 57 |
must be specified (but only one of them). |
| 58 |
- If O(state=present), the stack does exist, and neither O(template), |
| 59 |
O(template_body) nor O(template_url) are specified, the previous template will be reused. |
| 60 |
- The O(template) parameter has been deprecated and will be remove in a release after |
| 61 |
2026-05-01. It is recommended to use O(template_body) with the P(ansible.builtin.template#lookup) lookup plugin. |
| 62 |
type: path |
| 63 |
notification_arns: |
| 64 |
description: |
| 65 |
- A comma separated list of Simple Notification Service (SNS) topic ARNs to publish stack related events. |
| 66 |
type: str |
| 67 |
stack_policy: |
| 68 |
description: |
| 69 |
- The path of the file containing the CloudFormation stack policy. A policy cannot be removed once placed, but it can be modified. |
| 70 |
for instance, allow all updates U(https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html#d0e9051) |
| 71 |
type: str |
| 72 |
stack_policy_body: |
| 73 |
description: |
| 74 |
- The CloudFormation stack policy in JSON. A policy cannot be removed once placed, but it can be modified. |
| 75 |
for instance, allow all updates U(https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html#d0e9051) |
| 76 |
type: json |
| 77 |
version_added: 1.5.0 |
| 78 |
stack_policy_on_update_body: |
| 79 |
description: |
| 80 |
- The body of the cloudformation stack policy only applied during this update. |
| 81 |
type: json |
| 82 |
version_added: 1.5.0 |
| 83 |
tags: |
| 84 |
description: |
| 85 |
- Dictionary of tags to associate with stack and its resources during stack creation. |
| 86 |
- Can be updated later, updating tags removes previous entries. |
| 87 |
type: dict |
| 88 |
template_url: |
| 89 |
description: |
| 90 |
- Location of file containing the template body. The URL must point to a template (max size 307,200 bytes) located in an |
| 91 |
S3 bucket in the same region as the stack. |
| 92 |
- If O(state=present) and the stack does not exist yet, either O(template), O(template_body) or O(template_url) |
| 93 |
must be specified (but only one of them). |
| 94 |
- If O(state=present), the stack does exist, and neither O(template), O(template_body) nor O(template_url) are specified, |
| 95 |
the previous template will be reused. |
| 96 |
type: str |
| 97 |
create_changeset: |
| 98 |
description: |
| 99 |
- If stack already exists create a changeset instead of directly applying changes. See the AWS Change Sets docs |
| 100 |
U(https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets.html). |
| 101 |
- B(WARNING:) if the stack does not exist, it will be created without changeset. If O(state=absent), the stack will be |
| 102 |
deleted immediately with no changeset. |
| 103 |
type: bool |
| 104 |
default: false |
| 105 |
changeset_name: |
| 106 |
description: |
| 107 |
- Name given to the changeset when creating a changeset. |
| 108 |
- Only used when O(create_changeset=true). |
| 109 |
- By default a name prefixed with Ansible-STACKNAME is generated based on input parameters. |
| 110 |
See the AWS Change Sets docs for more information |
| 111 |
U(https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets.html) |
| 112 |
type: str |
| 113 |
role_arn: |
| 114 |
description: |
| 115 |
- The role that AWS CloudFormation assumes to create the stack. See the AWS CloudFormation Service Role |
| 116 |
docs U(https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-servicerole.html) |
| 117 |
type: str |
| 118 |
termination_protection: |
| 119 |
description: |
| 120 |
- Enable or disable termination protection on the stack. |
| 121 |
type: bool |
| 122 |
template_body: |
| 123 |
description: |
| 124 |
- Template body. Use this to pass in the actual body of the CloudFormation template. |
| 125 |
- If O(state=present) and the stack does not exist yet, either O(template), O(template_body) or O(template_url) |
| 126 |
must be specified (but only one of them). |
| 127 |
- If O(state=present), the stack does exist, and neither O(template), O(template_body) nor O(template_url) |
| 128 |
are specified, the previous template will be reused. |
| 129 |
type: str |
| 130 |
events_limit: |
| 131 |
description: |
| 132 |
- Maximum number of CloudFormation events to fetch from a stack when creating or updating it. |
| 133 |
default: 200 |
| 134 |
type: int |
| 135 |
backoff_delay: |
| 136 |
description: |
| 137 |
- Number of seconds to wait for the next retry. |
| 138 |
default: 3 |
| 139 |
type: int |
| 140 |
required: False |
| 141 |
backoff_max_delay: |
| 142 |
description: |
| 143 |
- Maximum amount of time to wait between retries. |
| 144 |
default: 30 |
| 145 |
type: int |
| 146 |
required: False |
| 147 |
backoff_retries: |
| 148 |
description: |
| 149 |
- Number of times to retry operation. |
| 150 |
- AWS API throttling mechanism fails CloudFormation module so we have to retry a couple of times. |
| 151 |
default: 10 |
| 152 |
type: int |
| 153 |
required: False |
| 154 |
capabilities: |
| 155 |
description: |
| 156 |
- Specify capabilities that stack template contains. |
| 157 |
- Valid values are V(CAPABILITY_IAM), V(CAPABILITY_NAMED_IAM) and V(CAPABILITY_AUTO_EXPAND). |
| 158 |
type: list |
| 159 |
elements: str |
| 160 |
default: [ CAPABILITY_IAM, CAPABILITY_NAMED_IAM ] |
| 161 |
|
| 162 |
author: |
| 163 |
- "James S. Martin (@jsmartin)" |
| 164 |
extends_documentation_fragment: |
| 165 |
- amazon.aws.common.modules |
| 166 |
- amazon.aws.region.modules |
| 167 |
- amazon.aws.boto3 |
| 168 |
""" |
| 169 |
|
| 170 |
EXAMPLES = r""" |
| 171 |
- name: create a cloudformation stack |
| 172 |
amazon.aws.cloudformation: |
| 173 |
stack_name: "ansible-cloudformation" |
| 174 |
state: "present" |
| 175 |
region: "us-east-1" |
| 176 |
disable_rollback: true |
| 177 |
# The template parameter has been deprecated, use template_body with lookup instead. |
| 178 |
# template: "files/cloudformation-example.json" |
| 179 |
template_body: "{{ lookup('file', 'cloudformation-example.json') }}" |
| 180 |
template_parameters: |
| 181 |
KeyName: "jmartin" |
| 182 |
DiskType: "ephemeral" |
| 183 |
InstanceType: "m1.small" |
| 184 |
ClusterSize: 3 |
| 185 |
tags: |
| 186 |
Stack: "ansible-cloudformation" |
| 187 |
|
| 188 |
# Basic role example |
| 189 |
- name: create a stack, specify role that cloudformation assumes |
| 190 |
amazon.aws.cloudformation: |
| 191 |
stack_name: "ansible-cloudformation" |
| 192 |
state: "present" |
| 193 |
region: "us-east-1" |
| 194 |
disable_rollback: true |
| 195 |
# The template parameter has been deprecated, use template_body with lookup instead. |
| 196 |
# template: "roles/cloudformation/files/cloudformation-example.json" |
| 197 |
template_body: "{{ lookup('file', 'cloudformation-example.json') }}" |
| 198 |
role_arn: 'arn:aws:iam::123456789012:role/cloudformation-iam-role' |
| 199 |
|
| 200 |
- name: delete a stack |
| 201 |
amazon.aws.cloudformation: |
| 202 |
stack_name: "ansible-cloudformation-old" |
| 203 |
state: "absent" |
| 204 |
|
| 205 |
# Create a stack, pass in template from a URL, disable rollback if stack creation fails, |
| 206 |
# pass in some parameters to the template, provide tags for resources created |
| 207 |
- name: create a stack, pass in the template via an URL |
| 208 |
amazon.aws.cloudformation: |
| 209 |
stack_name: "ansible-cloudformation" |
| 210 |
state: present |
| 211 |
region: us-east-1 |
| 212 |
disable_rollback: true |
| 213 |
template_url: https://s3.amazonaws.com/my-bucket/cloudformation.template |
| 214 |
template_parameters: |
| 215 |
KeyName: jmartin |
| 216 |
DiskType: ephemeral |
| 217 |
InstanceType: m1.small |
| 218 |
ClusterSize: 3 |
| 219 |
tags: |
| 220 |
Stack: ansible-cloudformation |
| 221 |
|
| 222 |
# Create a stack, passing in template body using lookup of Jinja2 template, disable rollback if stack creation fails, |
| 223 |
# pass in some parameters to the template, provide tags for resources created |
| 224 |
- name: create a stack, pass in the template body via lookup template |
| 225 |
amazon.aws.cloudformation: |
| 226 |
stack_name: "ansible-cloudformation" |
| 227 |
state: present |
| 228 |
region: us-east-1 |
| 229 |
disable_rollback: true |
| 230 |
template_body: "{{ lookup('template', 'cloudformation.j2') }}" |
| 231 |
template_parameters: |
| 232 |
KeyName: jmartin |
| 233 |
DiskType: ephemeral |
| 234 |
InstanceType: m1.small |
| 235 |
ClusterSize: 3 |
| 236 |
tags: |
| 237 |
Stack: ansible-cloudformation |
| 238 |
|
| 239 |
# Pass a template parameter which uses CloudFormation's UsePreviousValue attribute |
| 240 |
# When use_previous_value is set to True, the given value will be ignored and |
| 241 |
# CloudFormation will use the value from a previously submitted template. |
| 242 |
# If use_previous_value is set to False (default) the given value is used. |
| 243 |
- amazon.aws.cloudformation: |
| 244 |
stack_name: "ansible-cloudformation" |
| 245 |
state: "present" |
| 246 |
region: "us-east-1" |
| 247 |
template: "files/cloudformation-example.json" |
| 248 |
template_parameters: |
| 249 |
DBSnapshotIdentifier: |
| 250 |
use_previous_value: true |
| 251 |
value: arn:aws:rds:es-east-1:123456789012:snapshot:rds:my-db-snapshot |
| 252 |
DBName: |
| 253 |
use_previous_value: true |
| 254 |
tags: |
| 255 |
Stack: "ansible-cloudformation" |
| 256 |
|
| 257 |
# Enable termination protection on a stack. |
| 258 |
# If the stack already exists, this will update its termination protection |
| 259 |
- name: enable termination protection during stack creation |
| 260 |
amazon.aws.cloudformation: |
| 261 |
stack_name: my_stack |
| 262 |
state: present |
| 263 |
template_url: https://s3.amazonaws.com/my-bucket/cloudformation.template |
| 264 |
termination_protection: true |
| 265 |
|
| 266 |
# Configure TimeoutInMinutes before the stack status becomes CREATE_FAILED |
| 267 |
# In this case, if disable_rollback is not set or is set to false, the stack will be rolled back. |
| 268 |
- name: enable termination protection during stack creation |
| 269 |
amazon.aws.cloudformation: |
| 270 |
stack_name: my_stack |
| 271 |
state: present |
| 272 |
template_url: https://s3.amazonaws.com/my-bucket/cloudformation.template |
| 273 |
create_timeout: 5 |
| 274 |
|
| 275 |
# Configure rollback behaviour on the unsuccessful creation of a stack allowing |
| 276 |
# CloudFormation to clean up, or do nothing in the event of an unsuccessful |
| 277 |
# deployment |
| 278 |
# In this case, if on_create_failure is set to "DELETE", it will clean up the stack if |
| 279 |
# it fails to create |
| 280 |
- name: create stack which will delete on creation failure |
| 281 |
amazon.aws.cloudformation: |
| 282 |
stack_name: my_stack |
| 283 |
state: present |
| 284 |
template_url: https://s3.amazonaws.com/my-bucket/cloudformation.template |
| 285 |
on_create_failure: DELETE |
| 286 |
""" |
| 287 |
|
| 288 |
RETURN = r""" |
| 289 |
events: |
| 290 |
description: Most recent events in CloudFormation's event log. This may be from a previous run in some cases. |
| 291 |
returned: always |
| 292 |
type: list |
| 293 |
sample: [ |
| 294 |
"StackEvent AWS::CloudFormation::Stack stackname UPDATE_COMPLETE", |
| 295 |
"StackEvent AWS::CloudFormation::Stack stackname UPDATE_COMPLETE_CLEANUP_IN_PROGRESS" |
| 296 |
] |
| 297 |
log: |
| 298 |
description: Debugging logs. Useful when modifying or finding an error. |
| 299 |
returned: always |
| 300 |
type: list |
| 301 |
elements: str |
| 302 |
sample: ["updating stack"] |
| 303 |
change_set_id: |
| 304 |
description: The ID of the stack change set when created. |
| 305 |
returned: when O(state=present) and O(create_changeset=true). |
| 306 |
type: str |
| 307 |
sample: "arn:aws:cloudformation:us-east-1:123456789012:changeSet/Ansible-StackName-f4496805bd1b2be824d1e315c6884247ede41eb0" |
| 308 |
stack_resources: |
| 309 |
description: AWS stack resources and their status. List of dictionaries, one dict per resource. |
| 310 |
returned: when O(state=present) |
| 311 |
type: list |
| 312 |
elements: dict |
| 313 |
sample: [ |
| 314 |
{ |
| 315 |
"last_updated_time": "2016-10-11T19:40:14.979000+00:00", |
| 316 |
"logical_resource_id": "CFTestSg", |
| 317 |
"physical_resource_id": "cloudformation2-CFTestSg-16UQ4CYQ57O9F", |
| 318 |
"resource_type": "AWS::EC2::SecurityGroup", |
| 319 |
"status": "UPDATE_COMPLETE", |
| 320 |
"status_reason": null |
| 321 |
} |
| 322 |
] |
| 323 |
stack_outputs: |
| 324 |
description: A key:value dictionary of all the stack outputs currently defined. If there are no stack outputs, it is an empty dictionary. |
| 325 |
returned: When O(state=present) |
| 326 |
type: dict |
| 327 |
sample: {"MySg": "AnsibleModuleTestYAML-CFTestSg-C8UVS567B6NS"} |
| 328 |
""" |
| 329 |
|
| 330 |
import json |
| 331 |
import time |
| 332 |
import traceback |
| 333 |
import uuid |
| 334 |
from hashlib import sha1 |
| 335 |
|
| 336 |
try: |
| 337 |
import botocore |
| 338 |
except ImportError: |
| 339 |
pass # Handled by AnsibleAWSModule |
| 340 |
|
| 341 |
from ansible.module_utils.common.text.converters import to_bytes |
| 342 |
from ansible.module_utils.common.text.converters import to_native |
| 343 |
|
| 344 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import boto_exception |
| 345 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_message |
| 346 |
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule |
| 347 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 348 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list |
| 349 |
|
| 350 |
|
| 351 |
@AWSRetry.jittered_backoff() |
| 352 |
def _search_events(cfn, stack_name, events_limit, token_filter): |
| 353 |
pg = cfn.get_paginator("describe_stack_events").paginate( |
| 354 |
StackName=stack_name, |
| 355 |
PaginationConfig={"MaxItems": events_limit}, |
| 356 |
) |
| 357 |
if token_filter is None: |
| 358 |
return list(pg.search("StackEvents[*]")) |
| 359 |
|
| 360 |
return list(pg.search(f"StackEvents[?ClientRequestToken == '{token_filter}']")) |
| 361 |
|
| 362 |
|
| 363 |
def get_stack_events(cfn, stack_name, events_limit, token_filter=None): |
| 364 |
"""This event data was never correct, it worked as a side effect. So the v2.3 format is different.""" |
| 365 |
ret = {"events": [], "log": []} |
| 366 |
|
| 367 |
try: |
| 368 |
events = _search_events(cfn, stack_name, events_limit, token_filter) |
| 369 |
except is_boto3_error_message("does not exist"): |
| 370 |
ret["log"].append("Stack does not exist.") |
| 371 |
return ret |
| 372 |
except ( |
| 373 |
botocore.exceptions.ValidationError, |
| 374 |
botocore.exceptions.ClientError, |
| 375 |
) as err: # pylint: disable=duplicate-except |
| 376 |
error_msg = boto_exception(err) |
| 377 |
ret["log"].append("Unknown error: " + str(error_msg)) |
| 378 |
return ret |
| 379 |
|
| 380 |
for e in events: |
| 381 |
eventline = f"StackEvent {e['ResourceType']} {e['LogicalResourceId']} {e['ResourceStatus']}" |
| 382 |
ret["events"].append(eventline) |
| 383 |
|
| 384 |
if e["ResourceStatus"].endswith("FAILED"): |
| 385 |
failure = f"{e['ResourceType']} {e['LogicalResourceId']} {e['ResourceStatus']}: {e['ResourceStatusReason']}" |
| 386 |
ret["log"].append(failure) |
| 387 |
|
| 388 |
return ret |
| 389 |
|
| 390 |
|
| 391 |
def create_stack(module, stack_params, cfn, events_limit): |
| 392 |
if "TemplateBody" not in stack_params and "TemplateURL" not in stack_params: |
| 393 |
module.fail_json( |
| 394 |
msg="Either 'template', 'template_body' or 'template_url' is required when the stack does not exist." |
| 395 |
) |
| 396 |
|
| 397 |
# 'TimeoutInMinutes', 'EnableTerminationProtection' and |
| 398 |
# 'OnFailure' only apply on creation, not update. |
| 399 |
if module.params.get("on_create_failure") is not None: |
| 400 |
stack_params["OnFailure"] = module.params["on_create_failure"] |
| 401 |
else: |
| 402 |
stack_params["DisableRollback"] = module.params["disable_rollback"] |
| 403 |
|
| 404 |
if module.params.get("create_timeout") is not None: |
| 405 |
stack_params["TimeoutInMinutes"] = module.params["create_timeout"] |
| 406 |
if module.params.get("termination_protection") is not None: |
| 407 |
stack_params["EnableTerminationProtection"] = bool(module.params.get("termination_protection")) |
| 408 |
|
| 409 |
try: |
| 410 |
response = cfn.create_stack(aws_retry=True, **stack_params) |
| 411 |
# Use stack ID to follow stack state in case of on_create_failure = DELETE |
| 412 |
result = stack_operation( |
| 413 |
module, cfn, response["StackId"], "CREATE", events_limit, stack_params.get("ClientRequestToken", None) |
| 414 |
) |
| 415 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as err: |
| 416 |
module.fail_json_aws(err, msg=f"Failed to create stack {stack_params.get('StackName')}") |
| 417 |
if not result: |
| 418 |
module.fail_json(msg="empty result") |
| 419 |
return result |
| 420 |
|
| 421 |
|
| 422 |
def list_changesets(cfn, stack_name): |
| 423 |
res = cfn.list_change_sets(aws_retry=True, StackName=stack_name) |
| 424 |
return [cs["ChangeSetName"] for cs in res["Summaries"]] |
| 425 |
|
| 426 |
|
| 427 |
def create_changeset(module, stack_params, cfn, events_limit): |
| 428 |
if "TemplateBody" not in stack_params and "TemplateURL" not in stack_params: |
| 429 |
module.fail_json(msg="Either 'template' or 'template_url' is required.") |
| 430 |
if module.params["changeset_name"] is not None: |
| 431 |
stack_params["ChangeSetName"] = module.params["changeset_name"] |
| 432 |
|
| 433 |
# changesets don't accept ClientRequestToken parameters |
| 434 |
stack_params.pop("ClientRequestToken", None) |
| 435 |
|
| 436 |
try: |
| 437 |
changeset_name = build_changeset_name(stack_params) |
| 438 |
stack_params["ChangeSetName"] = changeset_name |
| 439 |
|
| 440 |
# Determine if this changeset already exists |
| 441 |
pending_changesets = list_changesets(cfn, stack_params["StackName"]) |
| 442 |
if changeset_name in pending_changesets: |
| 443 |
warning = f"WARNING: {len(pending_changesets)} pending changeset(s) exist(s) for this stack!" |
| 444 |
result = dict(changed=False, output=f"ChangeSet {changeset_name} already exists.", warnings=[warning]) |
| 445 |
else: |
| 446 |
cs = cfn.create_change_set(aws_retry=True, **stack_params) |
| 447 |
# Make sure we don't enter an infinite loop |
| 448 |
time_end = time.time() + 600 |
| 449 |
while time.time() < time_end: |
| 450 |
try: |
| 451 |
newcs = cfn.describe_change_set(aws_retry=True, ChangeSetName=cs["Id"]) |
| 452 |
except botocore.exceptions.BotoCoreError as err: |
| 453 |
module.fail_json_aws(err) |
| 454 |
if newcs["Status"] == "CREATE_PENDING" or newcs["Status"] == "CREATE_IN_PROGRESS": |
| 455 |
time.sleep(1) |
| 456 |
elif newcs["Status"] == "FAILED" and ( |
| 457 |
"The submitted information didn't contain changes" in newcs["StatusReason"] |
| 458 |
or "No updates are to be performed" in newcs["StatusReason"] |
| 459 |
): |
| 460 |
cfn.delete_change_set(aws_retry=True, ChangeSetName=cs["Id"]) |
| 461 |
result = dict( |
| 462 |
changed=False, |
| 463 |
output="The created Change Set did not contain any changes to this stack and was deleted.", |
| 464 |
) |
| 465 |
# a failed change set does not trigger any stack events so we just want to |
| 466 |
# skip any further processing of result and just return it directly |
| 467 |
return result |
| 468 |
else: |
| 469 |
break |
| 470 |
# Lets not hog the cpu/spam the AWS API |
| 471 |
time.sleep(1) |
| 472 |
result = stack_operation(module, cfn, stack_params["StackName"], "CREATE_CHANGESET", events_limit) |
| 473 |
result["change_set_id"] = cs["Id"] |
| 474 |
result["warnings"] = [ |
| 475 |
f"Created changeset named {changeset_name} for stack {stack_params['StackName']}", |
| 476 |
f"You can execute it using: aws cloudformation execute-change-set --change-set-name {cs['Id']}", |
| 477 |
"NOTE that dependencies on this stack might fail due to pending changes!", |
| 478 |
] |
| 479 |
except is_boto3_error_message("No updates are to be performed."): |
| 480 |
result = dict(changed=False, output="Stack is already up-to-date.") |
| 481 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as err: |
| 482 |
module.fail_json_aws(err, msg="Failed to create change set") |
| 483 |
|
| 484 |
if not result: |
| 485 |
module.fail_json(msg="empty result") |
| 486 |
return result |
| 487 |
|
| 488 |
|
| 489 |
def update_stack(module, stack_params, cfn, events_limit): |
| 490 |
if "TemplateBody" not in stack_params and "TemplateURL" not in stack_params: |
| 491 |
stack_params["UsePreviousTemplate"] = True |
| 492 |
|
| 493 |
if module.params["stack_policy_on_update_body"] is not None: |
| 494 |
stack_params["StackPolicyDuringUpdateBody"] = module.params["stack_policy_on_update_body"] |
| 495 |
|
| 496 |
stack_params["DisableRollback"] = module.params["disable_rollback"] |
| 497 |
|
| 498 |
# if the state is present and the stack already exists, we try to update it. |
| 499 |
# AWS will tell us if the stack template and parameters are the same and |
| 500 |
# don't need to be updated. |
| 501 |
try: |
| 502 |
cfn.update_stack(aws_retry=True, **stack_params) |
| 503 |
result = stack_operation( |
| 504 |
module, cfn, stack_params["StackName"], "UPDATE", events_limit, stack_params.get("ClientRequestToken", None) |
| 505 |
) |
| 506 |
except is_boto3_error_message("No updates are to be performed."): |
| 507 |
result = dict(changed=False, output="Stack is already up-to-date.") |
| 508 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as err: |
| 509 |
module.fail_json_aws(err, msg=f"Failed to update stack {stack_params.get('StackName')}") |
| 510 |
if not result: |
| 511 |
module.fail_json(msg="empty result") |
| 512 |
return result |
| 513 |
|
| 514 |
|
| 515 |
def update_termination_protection(module, cfn, stack_name, desired_termination_protection_state): |
| 516 |
"""updates termination protection of a stack""" |
| 517 |
changed = False |
| 518 |
stack = get_stack_facts(module, cfn, stack_name) |
| 519 |
if stack: |
| 520 |
if stack["EnableTerminationProtection"] is not desired_termination_protection_state: |
| 521 |
try: |
| 522 |
cfn.update_termination_protection( |
| 523 |
aws_retry=True, |
| 524 |
EnableTerminationProtection=desired_termination_protection_state, |
| 525 |
StackName=stack_name, |
| 526 |
) |
| 527 |
changed = True |
| 528 |
except botocore.exceptions.ClientError as e: |
| 529 |
module.fail_json_aws(e) |
| 530 |
return changed |
| 531 |
|
| 532 |
|
| 533 |
def stack_operation(module, cfn, stack_name, operation, events_limit, op_token=None): |
| 534 |
"""gets the status of a stack while it is created/updated/deleted""" |
| 535 |
existed = [] |
| 536 |
while True: |
| 537 |
try: |
| 538 |
stack = get_stack_facts(module, cfn, stack_name, raise_errors=True) |
| 539 |
existed.append("yes") |
| 540 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError): |
| 541 |
# If the stack previously existed, and now can't be found then it's |
| 542 |
# been deleted successfully. |
| 543 |
if "yes" in existed or operation == "DELETE": # stacks may delete fast, look in a few ways. |
| 544 |
ret = get_stack_events(cfn, stack_name, events_limit, op_token) |
| 545 |
ret.update({"changed": True, "output": "Stack Deleted"}) |
| 546 |
return ret |
| 547 |
else: |
| 548 |
return { |
| 549 |
"changed": True, |
| 550 |
"failed": True, |
| 551 |
"output": "Stack Not Found", |
| 552 |
"exception": traceback.format_exc(), |
| 553 |
} |
| 554 |
ret = get_stack_events(cfn, stack_name, events_limit, op_token) |
| 555 |
if not stack: |
| 556 |
if "yes" in existed or operation == "DELETE": # stacks may delete fast, look in a few ways. |
| 557 |
ret = get_stack_events(cfn, stack_name, events_limit, op_token) |
| 558 |
ret.update({"changed": True, "output": "Stack Deleted"}) |
| 559 |
return ret |
| 560 |
else: |
| 561 |
ret.update({"changed": False, "failed": True, "output": "Stack not found."}) |
| 562 |
return ret |
| 563 |
# it covers ROLLBACK_COMPLETE and UPDATE_ROLLBACK_COMPLETE |
| 564 |
# Possible states: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html#w1ab2c15c17c21c13 |
| 565 |
elif stack["StackStatus"].endswith("ROLLBACK_COMPLETE") and operation != "CREATE_CHANGESET": |
| 566 |
ret.update({"changed": True, "failed": True, "output": f"Problem with {operation}. Rollback complete"}) |
| 567 |
return ret |
| 568 |
elif stack["StackStatus"] == "DELETE_COMPLETE" and operation == "CREATE": |
| 569 |
ret.update({"changed": True, "failed": True, "output": "Stack create failed. Delete complete."}) |
| 570 |
return ret |
| 571 |
# note the ordering of ROLLBACK_COMPLETE, DELETE_COMPLETE, and COMPLETE, because otherwise COMPLETE will match all cases. |
| 572 |
elif stack["StackStatus"].endswith("_COMPLETE"): |
| 573 |
ret.update({"changed": True, "output": f"Stack {operation} complete"}) |
| 574 |
return ret |
| 575 |
elif stack["StackStatus"].endswith("_ROLLBACK_FAILED"): |
| 576 |
ret.update({"changed": True, "failed": True, "output": f"Stack {operation} rollback failed"}) |
| 577 |
return ret |
| 578 |
# note the ordering of ROLLBACK_FAILED and FAILED, because otherwise FAILED will match both cases. |
| 579 |
elif stack["StackStatus"].endswith("_FAILED"): |
| 580 |
ret.update({"changed": True, "failed": True, "output": f"Stack {operation} failed"}) |
| 581 |
return ret |
| 582 |
else: |
| 583 |
# this can loop forever :/ |
| 584 |
time.sleep(5) |
| 585 |
return {"failed": True, "output": "Failed for unknown reasons."} |
| 586 |
|
| 587 |
|
| 588 |
def build_changeset_name(stack_params): |
| 589 |
if "ChangeSetName" in stack_params: |
| 590 |
return stack_params["ChangeSetName"] |
| 591 |
|
| 592 |
json_params = json.dumps(stack_params, sort_keys=True) |
| 593 |
|
| 594 |
changeset_sha = sha1(to_bytes(json_params, errors="surrogate_or_strict")).hexdigest() |
| 595 |
return f"Ansible-{stack_params['StackName']}-{changeset_sha}" |
| 596 |
|
| 597 |
|
| 598 |
def check_mode_changeset(module, stack_params, cfn): |
| 599 |
"""Create a change set, describe it and delete it before returning check mode outputs.""" |
| 600 |
stack_params["ChangeSetName"] = build_changeset_name(stack_params) |
| 601 |
# changesets don't accept ClientRequestToken parameters |
| 602 |
stack_params.pop("ClientRequestToken", None) |
| 603 |
|
| 604 |
try: |
| 605 |
for _i in range(60): # total time 5 min |
| 606 |
# check stack is ready to have a change set created |
| 607 |
stack = get_stack_facts(module, cfn, stack_params["StackName"], raise_errors=True) |
| 608 |
if stack["StackStatus"].endswith("_COMPLETE"): |
| 609 |
break |
| 610 |
time.sleep(5) |
| 611 |
change_set = cfn.create_change_set(aws_retry=True, **stack_params) |
| 612 |
for _i in range(60): # total time 5 min |
| 613 |
description = cfn.describe_change_set(aws_retry=True, ChangeSetName=change_set["Id"]) |
| 614 |
if description["Status"] in ("CREATE_COMPLETE", "FAILED"): |
| 615 |
break |
| 616 |
time.sleep(5) |
| 617 |
else: |
| 618 |
# if the changeset doesn't finish in 5 mins, this `else` will trigger and fail |
| 619 |
module.fail_json(msg=f"Failed to create change set {stack_params['ChangeSetName']}") |
| 620 |
|
| 621 |
cfn.delete_change_set(aws_retry=True, ChangeSetName=change_set["Id"]) |
| 622 |
|
| 623 |
reason = description.get("StatusReason") |
| 624 |
|
| 625 |
if description["Status"] == "FAILED" and ( |
| 626 |
"didn't contain changes" in reason or "No updates are to be performed" in reason |
| 627 |
): |
| 628 |
return {"changed": False, "msg": reason, "meta": reason} |
| 629 |
return {"changed": True, "msg": reason, "meta": description["Changes"]} |
| 630 |
|
| 631 |
except (botocore.exceptions.ValidationError, botocore.exceptions.ClientError) as err: |
| 632 |
module.fail_json_aws(err) |
| 633 |
|
| 634 |
|
| 635 |
def get_stack_facts(module, cfn, stack_name, raise_errors=False): |
| 636 |
try: |
| 637 |
stack_response = cfn.describe_stacks(aws_retry=True, StackName=stack_name) |
| 638 |
stack_info = stack_response["Stacks"][0] |
| 639 |
except is_boto3_error_message("does not exist"): |
| 640 |
return None |
| 641 |
except ( |
| 642 |
botocore.exceptions.ValidationError, |
| 643 |
botocore.exceptions.ClientError, |
| 644 |
) as err: # pylint: disable=duplicate-except |
| 645 |
if raise_errors: |
| 646 |
raise err |
| 647 |
module.fail_json_aws(err, msg="Failed to describe stack") |
| 648 |
|
| 649 |
if stack_response and stack_response.get("Stacks", None): |
| 650 |
stacks = stack_response["Stacks"] |
| 651 |
if len(stacks): |
| 652 |
stack_info = stacks[0] |
| 653 |
|
| 654 |
return stack_info |
| 655 |
|
| 656 |
|
| 657 |
def main(): |
| 658 |
argument_spec = dict( |
| 659 |
stack_name=dict(required=True), |
| 660 |
template_parameters=dict(required=False, type="dict", default={}), |
| 661 |
state=dict(default="present", choices=["present", "absent"]), |
| 662 |
template=dict( |
| 663 |
default=None, |
| 664 |
required=False, |
| 665 |
type="path", |
| 666 |
removed_at_date="2026-05-01", |
| 667 |
removed_from_collection="amazon.aws", |
| 668 |
), |
| 669 |
notification_arns=dict(default=None, required=False), |
| 670 |
stack_policy=dict(default=None, required=False), |
| 671 |
stack_policy_body=dict(default=None, required=False, type="json"), |
| 672 |
stack_policy_on_update_body=dict(default=None, required=False, type="json"), |
| 673 |
disable_rollback=dict(default=False, type="bool"), |
| 674 |
on_create_failure=dict(default=None, required=False, choices=["DO_NOTHING", "ROLLBACK", "DELETE"]), |
| 675 |
create_timeout=dict(default=None, type="int"), |
| 676 |
template_url=dict(default=None, required=False), |
| 677 |
template_body=dict(default=None, required=False), |
| 678 |
create_changeset=dict(default=False, type="bool"), |
| 679 |
changeset_name=dict(default=None, required=False), |
| 680 |
role_arn=dict(default=None, required=False), |
| 681 |
tags=dict(default=None, type="dict"), |
| 682 |
termination_protection=dict(default=None, type="bool"), |
| 683 |
events_limit=dict(default=200, type="int"), |
| 684 |
backoff_retries=dict(type="int", default=10, required=False), |
| 685 |
backoff_delay=dict(type="int", default=3, required=False), |
| 686 |
backoff_max_delay=dict(type="int", default=30, required=False), |
| 687 |
capabilities=dict(type="list", elements="str", default=["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"]), |
| 688 |
) |
| 689 |
|
| 690 |
module = AnsibleAWSModule( |
| 691 |
argument_spec=argument_spec, |
| 692 |
mutually_exclusive=[["template_url", "template", "template_body"], ["disable_rollback", "on_create_failure"]], |
| 693 |
supports_check_mode=True, |
| 694 |
) |
| 695 |
|
| 696 |
invalid_capabilities = [] |
| 697 |
user_capabilities = module.params.get("capabilities") |
| 698 |
for user_cap in user_capabilities: |
| 699 |
if user_cap not in ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND"]: |
| 700 |
invalid_capabilities.append(user_cap) |
| 701 |
|
| 702 |
if invalid_capabilities: |
| 703 |
module.fail_json( |
| 704 |
msg=f"Specified capabilities are invalid : {invalid_capabilities!r}, please check documentation for valid capabilities" |
| 705 |
) |
| 706 |
|
| 707 |
# collect the parameters that are passed to boto3. Keeps us from having so many scalars floating around. |
| 708 |
stack_params = { |
| 709 |
"Capabilities": user_capabilities, |
| 710 |
"ClientRequestToken": to_native(uuid.uuid4()), |
| 711 |
} |
| 712 |
state = module.params["state"] |
| 713 |
stack_params["StackName"] = module.params["stack_name"] |
| 714 |
|
| 715 |
if module.params["template"] is not None: |
| 716 |
with open(module.params["template"], "r") as template_fh: |
| 717 |
stack_params["TemplateBody"] = template_fh.read() |
| 718 |
elif module.params["template_body"] is not None: |
| 719 |
stack_params["TemplateBody"] = module.params["template_body"] |
| 720 |
elif module.params["template_url"] is not None: |
| 721 |
stack_params["TemplateURL"] = module.params["template_url"] |
| 722 |
|
| 723 |
if module.params.get("notification_arns"): |
| 724 |
stack_params["NotificationARNs"] = module.params["notification_arns"].split(",") |
| 725 |
else: |
| 726 |
stack_params["NotificationARNs"] = [] |
| 727 |
|
| 728 |
# can't check the policy when verifying. |
| 729 |
if ( |
| 730 |
module.params["stack_policy_body"] is not None |
| 731 |
and not module.check_mode |
| 732 |
and not module.params["create_changeset"] |
| 733 |
): |
| 734 |
stack_params["StackPolicyBody"] = module.params["stack_policy_body"] |
| 735 |
elif module.params["stack_policy"] is not None and not module.check_mode and not module.params["create_changeset"]: |
| 736 |
with open(module.params["stack_policy"], "r") as stack_policy_fh: |
| 737 |
stack_params["StackPolicyBody"] = stack_policy_fh.read() |
| 738 |
|
| 739 |
template_parameters = module.params["template_parameters"] |
| 740 |
|
| 741 |
stack_params["Parameters"] = [] |
| 742 |
for k, v in template_parameters.items(): |
| 743 |
if isinstance(v, dict): |
| 744 |
# set parameter based on a dict to allow additional CFN Parameter Attributes |
| 745 |
param = dict(ParameterKey=k) |
| 746 |
|
| 747 |
if "value" in v: |
| 748 |
param["ParameterValue"] = str(v["value"]) |
| 749 |
|
| 750 |
if "use_previous_value" in v and bool(v["use_previous_value"]): |
| 751 |
param["UsePreviousValue"] = True |
| 752 |
param.pop("ParameterValue", None) |
| 753 |
|
| 754 |
stack_params["Parameters"].append(param) |
| 755 |
else: |
| 756 |
# allow default k/v configuration to set a template parameter |
| 757 |
stack_params["Parameters"].append({"ParameterKey": k, "ParameterValue": str(v)}) |
| 758 |
|
| 759 |
if isinstance(module.params.get("tags"), dict): |
| 760 |
stack_params["Tags"] = ansible_dict_to_boto3_tag_list(module.params["tags"]) |
| 761 |
|
| 762 |
if module.params.get("role_arn"): |
| 763 |
stack_params["RoleARN"] = module.params["role_arn"] |
| 764 |
|
| 765 |
result = {} |
| 766 |
|
| 767 |
# Wrap the cloudformation client methods that this module uses with |
| 768 |
# automatic backoff / retry for throttling error codes |
| 769 |
retry_decorator = AWSRetry.jittered_backoff( |
| 770 |
retries=module.params.get("backoff_retries"), |
| 771 |
delay=module.params.get("backoff_delay"), |
| 772 |
max_delay=module.params.get("backoff_max_delay"), |
| 773 |
) |
| 774 |
cfn = module.client("cloudformation", retry_decorator=retry_decorator) |
| 775 |
|
| 776 |
stack_info = get_stack_facts(module, cfn, stack_params["StackName"]) |
| 777 |
|
| 778 |
if module.check_mode: |
| 779 |
if state == "absent" and stack_info: |
| 780 |
module.exit_json(changed=True, msg="Stack would be deleted", meta=[]) |
| 781 |
elif state == "absent" and not stack_info: |
| 782 |
module.exit_json(changed=False, msg="Stack doesn't exist", meta=[]) |
| 783 |
elif state == "present" and not stack_info: |
| 784 |
module.exit_json(changed=True, msg="New stack would be created", meta=[]) |
| 785 |
else: |
| 786 |
module.exit_json(**check_mode_changeset(module, stack_params, cfn)) |
| 787 |
|
| 788 |
if state == "present": |
| 789 |
if not stack_info: |
| 790 |
result = create_stack(module, stack_params, cfn, module.params.get("events_limit")) |
| 791 |
else: |
| 792 |
changeset_updated = False |
| 793 |
if module.params.get("create_changeset"): |
| 794 |
result = create_changeset(module, stack_params, cfn, module.params.get("events_limit")) |
| 795 |
changeset_updated = True |
| 796 |
if module.params.get("termination_protection") is not None: |
| 797 |
result["changed"] = update_termination_protection( |
| 798 |
module, cfn, stack_params["StackName"], bool(module.params.get("termination_protection")) |
| 799 |
) |
| 800 |
if not changeset_updated: |
| 801 |
result = update_stack(module, stack_params, cfn, module.params.get("events_limit")) |
| 802 |
|
| 803 |
# format the stack output |
| 804 |
|
| 805 |
stack = get_stack_facts(module, cfn, stack_params["StackName"]) |
| 806 |
if stack is not None: |
| 807 |
if result.get("stack_outputs") is None: |
| 808 |
# always define stack_outputs, but it may be empty |
| 809 |
result["stack_outputs"] = {} |
| 810 |
for output in stack.get("Outputs", []): |
| 811 |
result["stack_outputs"][output["OutputKey"]] = output["OutputValue"] |
| 812 |
stack_resources = [] |
| 813 |
reslist = cfn.list_stack_resources(aws_retry=True, StackName=stack_params["StackName"]) |
| 814 |
for res in reslist.get("StackResourceSummaries", []): |
| 815 |
stack_resources.append( |
| 816 |
{ |
| 817 |
"logical_resource_id": res["LogicalResourceId"], |
| 818 |
"physical_resource_id": res.get("PhysicalResourceId", ""), |
| 819 |
"resource_type": res["ResourceType"], |
| 820 |
"last_updated_time": res["LastUpdatedTimestamp"], |
| 821 |
"status": res["ResourceStatus"], |
| 822 |
"status_reason": res.get("ResourceStatusReason"), # can be blank, apparently |
| 823 |
} |
| 824 |
) |
| 825 |
result["stack_resources"] = stack_resources |
| 826 |
|
| 827 |
elif state == "absent": |
| 828 |
# absent state is different because of the way delete_stack works. |
| 829 |
# problem is it it doesn't give an error if stack isn't found |
| 830 |
# so must describe the stack first |
| 831 |
|
| 832 |
try: |
| 833 |
stack = get_stack_facts(module, cfn, stack_params["StackName"]) |
| 834 |
if not stack: |
| 835 |
result = {"changed": False, "output": "Stack not found."} |
| 836 |
else: |
| 837 |
if stack_params.get("RoleARN") is None: |
| 838 |
cfn.delete_stack(aws_retry=True, StackName=stack_params["StackName"]) |
| 839 |
else: |
| 840 |
cfn.delete_stack( |
| 841 |
aws_retry=True, StackName=stack_params["StackName"], RoleARN=stack_params["RoleARN"] |
| 842 |
) |
| 843 |
result = stack_operation( |
| 844 |
module, |
| 845 |
cfn, |
| 846 |
stack_params["StackName"], |
| 847 |
"DELETE", |
| 848 |
module.params.get("events_limit"), |
| 849 |
stack_params.get("ClientRequestToken", None), |
| 850 |
) |
| 851 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as err: |
| 852 |
module.fail_json_aws(err) |
| 853 |
|
| 854 |
module.exit_json(**result) |
| 855 |
|
| 856 |
|
| 857 |
if __name__ == "__main__": |
| 858 |
main() |