| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2018, 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_stack_set |
| 10 |
version_added: 1.0.0 |
| 11 |
short_description: Manage groups of CloudFormation stacks |
| 12 |
description: |
| 13 |
- Launches/updates/deletes AWS CloudFormation Stack Sets. |
| 14 |
notes: |
| 15 |
- To make an individual stack, you want the M(amazon.aws.cloudformation) module. |
| 16 |
options: |
| 17 |
name: |
| 18 |
description: |
| 19 |
- Name of the CloudFormation stack set. |
| 20 |
required: true |
| 21 |
type: str |
| 22 |
description: |
| 23 |
description: |
| 24 |
- A description of what this stack set creates. |
| 25 |
type: str |
| 26 |
parameters: |
| 27 |
description: |
| 28 |
- A list of hashes of all the template variables for the stack. The value can be a string or a dict. |
| 29 |
- Dict can be used to set additional template parameter attributes like UsePreviousValue (see example). |
| 30 |
default: {} |
| 31 |
type: dict |
| 32 |
state: |
| 33 |
description: |
| 34 |
- If I(state=present), stack will be created. If I(state=present) and if stack exists and template has changed, it will be updated. |
| 35 |
If I(state=absent), stack will be removed. |
| 36 |
default: present |
| 37 |
choices: [ present, absent ] |
| 38 |
type: str |
| 39 |
template: |
| 40 |
description: |
| 41 |
- The local path of the CloudFormation template. |
| 42 |
- This must be the full path to the file, relative to the working directory. If using roles this may look |
| 43 |
like C(roles/cloudformation/files/cloudformation-example.json). |
| 44 |
- If I(state=present) and the stack does not exist yet, either I(template), I(template_body) or I(template_url) |
| 45 |
must be specified (but only one of them). |
| 46 |
- If I(state=present), the stack does exist, and neither I(template), I(template_body) nor I(template_url) |
| 47 |
are specified, the previous template will be reused. |
| 48 |
type: path |
| 49 |
template_body: |
| 50 |
description: |
| 51 |
- Template body. Use this to pass in the actual body of the CloudFormation template. |
| 52 |
- If I(state=present) and the stack does not exist yet, either I(template), I(template_body) or I(template_url) |
| 53 |
must be specified (but only one of them). |
| 54 |
- If I(state=present), the stack does exist, and neither I(template), I(template_body) nor I(template_url) |
| 55 |
are specified, the previous template will be reused. |
| 56 |
type: str |
| 57 |
template_url: |
| 58 |
description: |
| 59 |
- Location of file containing the template body. |
| 60 |
- The URL must point to a template (max size 307,200 bytes) located in an S3 bucket in the same region |
| 61 |
as the stack. |
| 62 |
- If I(state=present) and the stack does not exist yet, either I(template), I(template_body) or I(template_url) |
| 63 |
must be specified (but only one of them). |
| 64 |
- If I(state=present), the stack does exist, and neither I(template), I(template_body) nor I(template_url) |
| 65 |
are specified, the previous template will be reused. |
| 66 |
type: str |
| 67 |
purge_stacks: |
| 68 |
description: |
| 69 |
- Only applicable when I(state=absent). Sets whether, when deleting a stack set, the stack instances should also be deleted. |
| 70 |
- By default, instances will be deleted. To keep stacks when stack set is deleted set I(purge_stacks=false). |
| 71 |
type: bool |
| 72 |
default: true |
| 73 |
wait: |
| 74 |
description: |
| 75 |
- Whether or not to wait for stack operation to complete. This includes waiting for stack instances to reach UPDATE_COMPLETE status. |
| 76 |
- If you choose not to wait, this module will not notify when stack operations fail because it will not wait for them to finish. |
| 77 |
type: bool |
| 78 |
default: false |
| 79 |
wait_timeout: |
| 80 |
description: |
| 81 |
- How long to wait (in seconds) for stacks to complete create/update/delete operations. |
| 82 |
default: 900 |
| 83 |
type: int |
| 84 |
capabilities: |
| 85 |
description: |
| 86 |
- Capabilities allow stacks to create and modify IAM resources, which may include adding users or roles. |
| 87 |
- Currently the only available values are 'CAPABILITY_IAM' and 'CAPABILITY_NAMED_IAM'. Either or both may be provided. |
| 88 |
- > |
| 89 |
The following resources require that one or both of these parameters is specified: AWS::IAM::AccessKey, |
| 90 |
AWS::IAM::Group, AWS::IAM::InstanceProfile, AWS::IAM::Policy, AWS::IAM::Role, AWS::IAM::User, AWS::IAM::UserToGroupAddition |
| 91 |
type: list |
| 92 |
elements: str |
| 93 |
choices: |
| 94 |
- 'CAPABILITY_IAM' |
| 95 |
- 'CAPABILITY_NAMED_IAM' |
| 96 |
regions: |
| 97 |
description: |
| 98 |
- A list of AWS regions to create instances of a stack in. The I(region) parameter chooses where the Stack Set is created, and I(regions) |
| 99 |
specifies the region for stack instances. |
| 100 |
- At least one region must be specified to create a stack set. On updates, if fewer regions are specified only the specified regions will |
| 101 |
have their stack instances updated. |
| 102 |
type: list |
| 103 |
elements: str |
| 104 |
accounts: |
| 105 |
description: |
| 106 |
- A list of AWS accounts in which to create instance of CloudFormation stacks. |
| 107 |
- At least one region must be specified to create a stack set. On updates, if fewer regions are specified only the specified regions will |
| 108 |
have their stack instances updated. |
| 109 |
type: list |
| 110 |
elements: str |
| 111 |
administration_role_arn: |
| 112 |
description: |
| 113 |
- ARN of the administration role, meaning the role that CloudFormation Stack Sets use to assume the roles in your child accounts. |
| 114 |
- This defaults to C(arn:aws:iam::{{ account ID }}:role/AWSCloudFormationStackSetAdministrationRole) where C({{ account ID }}) is replaced with the |
| 115 |
account number of the current IAM role/user/STS credentials. |
| 116 |
aliases: |
| 117 |
- admin_role_arn |
| 118 |
- admin_role |
| 119 |
- administration_role |
| 120 |
type: str |
| 121 |
execution_role_name: |
| 122 |
description: |
| 123 |
- ARN of the execution role, meaning the role that CloudFormation Stack Sets assumes in your child accounts. |
| 124 |
- This MUST NOT be an ARN, and the roles must exist in each child account specified. |
| 125 |
- The default name for the execution role is C(AWSCloudFormationStackSetExecutionRole) |
| 126 |
aliases: |
| 127 |
- exec_role_name |
| 128 |
- exec_role |
| 129 |
- execution_role |
| 130 |
type: str |
| 131 |
tags: |
| 132 |
description: |
| 133 |
- Dictionary of tags to associate with stack and its resources during stack creation. |
| 134 |
- Can be updated later, updating tags removes previous entries. |
| 135 |
type: dict |
| 136 |
failure_tolerance: |
| 137 |
description: |
| 138 |
- Settings to change what is considered "failed" when running stack instance updates, and how many to do at a time. |
| 139 |
type: dict |
| 140 |
default: {} |
| 141 |
suboptions: |
| 142 |
fail_count: |
| 143 |
description: |
| 144 |
- The number of accounts, per region, for which this operation can fail before CloudFormation |
| 145 |
stops the operation in that region. |
| 146 |
- You must specify one of I(fail_count) and I(fail_percentage). |
| 147 |
type: int |
| 148 |
fail_percentage: |
| 149 |
type: int |
| 150 |
description: |
| 151 |
- The percentage of accounts, per region, for which this stack operation can fail before CloudFormation |
| 152 |
stops the operation in that region. |
| 153 |
- You must specify one of I(fail_count) and I(fail_percentage). |
| 154 |
parallel_percentage: |
| 155 |
type: int |
| 156 |
description: |
| 157 |
- The maximum percentage of accounts in which to perform this operation at one time. |
| 158 |
- You must specify one of I(parallel_count) and I(parallel_percentage). |
| 159 |
- Note that this setting lets you specify the maximum for operations. |
| 160 |
For large deployments, under certain circumstances the actual percentage may be lower. |
| 161 |
parallel_count: |
| 162 |
type: int |
| 163 |
description: |
| 164 |
- The maximum number of accounts in which to perform this operation at one time. |
| 165 |
- I(parallel_count) may be at most one more than the I(fail_count). |
| 166 |
- You must specify one of I(parallel_count) and I(parallel_percentage). |
| 167 |
- Note that this setting lets you specify the maximum for operations. |
| 168 |
For large deployments, under certain circumstances the actual count may be lower. |
| 169 |
|
| 170 |
author: |
| 171 |
- "Ryan Scott Brown (@ryansb)" |
| 172 |
extends_documentation_fragment: |
| 173 |
- amazon.aws.common.modules |
| 174 |
- amazon.aws.region.modules |
| 175 |
- amazon.aws.boto3 |
| 176 |
""" |
| 177 |
|
| 178 |
EXAMPLES = r""" |
| 179 |
- name: Create a stack set with instances in two accounts |
| 180 |
community.aws.cloudformation_stack_set: |
| 181 |
name: my-stack |
| 182 |
description: Test stack in two accounts |
| 183 |
state: present |
| 184 |
template_url: https://s3.amazonaws.com/my-bucket/cloudformation.template |
| 185 |
accounts: |
| 186 |
- 123456789012 |
| 187 |
- 234567890123 |
| 188 |
regions: |
| 189 |
- us-east-1 |
| 190 |
|
| 191 |
- name: on subsequent calls, templates are optional but parameters and tags can be altered |
| 192 |
community.aws.cloudformation_stack_set: |
| 193 |
name: my-stack |
| 194 |
state: present |
| 195 |
parameters: |
| 196 |
InstanceName: my_stacked_instance |
| 197 |
tags: |
| 198 |
foo: bar |
| 199 |
test: stack |
| 200 |
accounts: |
| 201 |
- 123456789012 |
| 202 |
- 234567890123 |
| 203 |
regions: |
| 204 |
- us-east-1 |
| 205 |
|
| 206 |
- name: The same type of update, but wait for the update to complete in all stacks |
| 207 |
community.aws.cloudformation_stack_set: |
| 208 |
name: my-stack |
| 209 |
state: present |
| 210 |
wait: true |
| 211 |
parameters: |
| 212 |
InstanceName: my_restacked_instance |
| 213 |
tags: |
| 214 |
foo: bar |
| 215 |
test: stack |
| 216 |
accounts: |
| 217 |
- 123456789012 |
| 218 |
- 234567890123 |
| 219 |
regions: |
| 220 |
- us-east-1 |
| 221 |
|
| 222 |
- name: Register new accounts (create new stack instances) with an existing stack set. |
| 223 |
community.aws.cloudformation_stack_set: |
| 224 |
name: my-stack |
| 225 |
state: present |
| 226 |
wait: true |
| 227 |
parameters: |
| 228 |
InstanceName: my_restacked_instance |
| 229 |
tags: |
| 230 |
foo: bar |
| 231 |
test: stack |
| 232 |
accounts: |
| 233 |
- 123456789012 |
| 234 |
- 234567890123 |
| 235 |
- 345678901234 |
| 236 |
regions: |
| 237 |
- us-east-1 |
| 238 |
""" |
| 239 |
|
| 240 |
RETURN = r""" |
| 241 |
operations_log: |
| 242 |
type: list |
| 243 |
description: Most recent events in CloudFormation's event log. This may be from a previous run in some cases. |
| 244 |
returned: always |
| 245 |
sample: |
| 246 |
- action: CREATE |
| 247 |
creation_timestamp: '2018-06-18T17:40:46.372000+00:00' |
| 248 |
end_timestamp: '2018-06-18T17:41:24.560000+00:00' |
| 249 |
operation_id: Ansible-StackInstance-Create-0ff2af5b-251d-4fdb-8b89-1ee444eba8b8 |
| 250 |
status: FAILED |
| 251 |
stack_instances: |
| 252 |
- account: '1234567890' |
| 253 |
region: us-east-1 |
| 254 |
stack_set_id: TestStackPrime:19f3f684-aae9-4e67-ba36-e09f92cf5929 |
| 255 |
status: OUTDATED |
| 256 |
status_reason: Account 1234567890 should have 'AWSCloudFormationStackSetAdministrationRole' role with trust relationship to CloudFormation service. |
| 257 |
|
| 258 |
operations: |
| 259 |
description: All operations initiated by this run of the cloudformation_stack_set module |
| 260 |
returned: always |
| 261 |
type: list |
| 262 |
sample: |
| 263 |
- action: CREATE |
| 264 |
administration_role_arn: arn:aws:iam::1234567890:role/AWSCloudFormationStackSetAdministrationRole |
| 265 |
creation_timestamp: '2018-06-18T17:40:46.372000+00:00' |
| 266 |
end_timestamp: '2018-06-18T17:41:24.560000+00:00' |
| 267 |
execution_role_name: AWSCloudFormationStackSetExecutionRole |
| 268 |
operation_id: Ansible-StackInstance-Create-0ff2af5b-251d-4fdb-8b89-1ee444eba8b8 |
| 269 |
operation_preferences: |
| 270 |
region_order: |
| 271 |
- us-east-1 |
| 272 |
- us-east-2 |
| 273 |
stack_set_id: TestStackPrime:19f3f684-aae9-4e67-ba36-e09f92cf5929 |
| 274 |
status: FAILED |
| 275 |
stack_instances: |
| 276 |
description: CloudFormation stack instances that are members of this stack set. This will also include their region and account ID. |
| 277 |
returned: state == present |
| 278 |
type: list |
| 279 |
sample: |
| 280 |
- account: '1234567890' |
| 281 |
region: us-east-1 |
| 282 |
stack_set_id: TestStackPrime:19f3f684-aae9-4e67-ba36-e09f92cf5929 |
| 283 |
status: OUTDATED |
| 284 |
status_reason: > |
| 285 |
Account 1234567890 should have 'AWSCloudFormationStackSetAdministrationRole' role with trust relationship to CloudFormation service. |
| 286 |
- account: '1234567890' |
| 287 |
region: us-east-2 |
| 288 |
stack_set_id: TestStackPrime:19f3f684-aae9-4e67-ba36-e09f92cf5929 |
| 289 |
status: OUTDATED |
| 290 |
status_reason: Cancelled since failure tolerance has exceeded |
| 291 |
stack_set: |
| 292 |
type: dict |
| 293 |
description: Facts about the currently deployed stack set, its parameters, and its tags |
| 294 |
returned: state == present |
| 295 |
sample: |
| 296 |
administration_role_arn: arn:aws:iam::1234567890:role/AWSCloudFormationStackSetAdministrationRole |
| 297 |
capabilities: [] |
| 298 |
description: test stack PRIME |
| 299 |
execution_role_name: AWSCloudFormationStackSetExecutionRole |
| 300 |
parameters: [] |
| 301 |
stack_set_arn: arn:aws:cloudformation:us-east-1:1234567890:stackset/TestStackPrime:19f3f684-aae9-467-ba36-e09f92cf5929 |
| 302 |
stack_set_id: TestStackPrime:19f3f684-aae9-4e67-ba36-e09f92cf5929 |
| 303 |
stack_set_name: TestStackPrime |
| 304 |
status: ACTIVE |
| 305 |
tags: |
| 306 |
Some: Thing |
| 307 |
an: other |
| 308 |
template_body: | |
| 309 |
AWSTemplateFormatVersion: "2010-09-09" |
| 310 |
Parameters: {} |
| 311 |
Resources: |
| 312 |
Bukkit: |
| 313 |
Type: "AWS::S3::Bucket" |
| 314 |
Properties: {} |
| 315 |
other: |
| 316 |
Type: "AWS::SNS::Topic" |
| 317 |
Properties: {} |
| 318 |
""" |
| 319 |
|
| 320 |
import datetime |
| 321 |
import itertools |
| 322 |
import time |
| 323 |
import uuid |
| 324 |
|
| 325 |
try: |
| 326 |
from botocore.exceptions import BotoCoreError |
| 327 |
from botocore.exceptions import ClientError |
| 328 |
except ImportError: |
| 329 |
# handled by AnsibleAWSModule |
| 330 |
pass |
| 331 |
|
| 332 |
from ansible.module_utils._text import to_native |
| 333 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 334 |
|
| 335 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code |
| 336 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 337 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list |
| 338 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict |
| 339 |
|
| 340 |
from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule |
| 341 |
|
| 342 |
|
| 343 |
def create_stack_set(module, stack_params, cfn): |
| 344 |
try: |
| 345 |
cfn.create_stack_set(aws_retry=True, **stack_params) |
| 346 |
return await_stack_set_exists(cfn, stack_params["StackSetName"]) |
| 347 |
except (ClientError, BotoCoreError) as err: |
| 348 |
module.fail_json_aws(err, msg=f"Failed to create stack set {stack_params.get('StackSetName')}.") |
| 349 |
|
| 350 |
|
| 351 |
def update_stack_set(module, stack_params, cfn): |
| 352 |
# if the state is present and the stack already exists, we try to update it. |
| 353 |
# AWS will tell us if the stack template and parameters are the same and |
| 354 |
# don't need to be updated. |
| 355 |
try: |
| 356 |
cfn.update_stack_set(**stack_params) |
| 357 |
except is_boto3_error_code("StackSetNotFound") as err: # pylint: disable=duplicate-except |
| 358 |
module.fail_json_aws(err, msg="Failed to find stack set. Check the name & region.") |
| 359 |
except is_boto3_error_code("StackInstanceNotFound") as err: # pylint: disable=duplicate-except |
| 360 |
module.fail_json_aws( |
| 361 |
err, |
| 362 |
msg=( |
| 363 |
"One or more stack instances were not found for this stack set. Double check " |
| 364 |
"the `accounts` and `regions` parameters." |
| 365 |
), |
| 366 |
) |
| 367 |
except is_boto3_error_code("OperationInProgressException") as err: # pylint: disable=duplicate-except |
| 368 |
module.fail_json_aws( |
| 369 |
err, |
| 370 |
msg=( |
| 371 |
"Another operation is already in progress on this stack set - please try again later. When making" |
| 372 |
" multiple cloudformation_stack_set calls, it's best to enable `wait: true` to avoid unfinished op" |
| 373 |
" errors." |
| 374 |
), |
| 375 |
) |
| 376 |
except (ClientError, BotoCoreError) as err: # pylint: disable=duplicate-except |
| 377 |
module.fail_json_aws(err, msg="Could not update stack set.") |
| 378 |
if module.params.get("wait"): |
| 379 |
await_stack_set_operation( |
| 380 |
module, |
| 381 |
cfn, |
| 382 |
operation_id=stack_params["OperationId"], |
| 383 |
stack_set_name=stack_params["StackSetName"], |
| 384 |
max_wait=module.params.get("wait_timeout"), |
| 385 |
) |
| 386 |
|
| 387 |
return True |
| 388 |
|
| 389 |
|
| 390 |
def compare_stack_instances(cfn, stack_set_name, accounts, regions): |
| 391 |
instance_list = cfn.list_stack_instances( |
| 392 |
aws_retry=True, |
| 393 |
StackSetName=stack_set_name, |
| 394 |
)["Summaries"] |
| 395 |
desired_stack_instances = set(itertools.product(accounts, regions)) |
| 396 |
existing_stack_instances = set((i["Account"], i["Region"]) for i in instance_list) |
| 397 |
# new stacks, existing stacks, unspecified stacks |
| 398 |
return ( |
| 399 |
(desired_stack_instances - existing_stack_instances), |
| 400 |
existing_stack_instances, |
| 401 |
(existing_stack_instances - desired_stack_instances), |
| 402 |
) |
| 403 |
|
| 404 |
|
| 405 |
@AWSRetry.jittered_backoff(retries=3, delay=4) |
| 406 |
def stack_set_facts(cfn, stack_set_name): |
| 407 |
try: |
| 408 |
ss = cfn.describe_stack_set(StackSetName=stack_set_name)["StackSet"] |
| 409 |
ss["Tags"] = boto3_tag_list_to_ansible_dict(ss["Tags"]) |
| 410 |
return ss |
| 411 |
except cfn.exceptions.from_code("StackSetNotFound"): |
| 412 |
# Return None if the stack doesn't exist |
| 413 |
return |
| 414 |
|
| 415 |
|
| 416 |
def await_stack_set_operation(module, cfn, stack_set_name, operation_id, max_wait): |
| 417 |
wait_start = datetime.datetime.now() |
| 418 |
operation = None |
| 419 |
for i in range(max_wait // 15): |
| 420 |
try: |
| 421 |
operation = cfn.describe_stack_set_operation(StackSetName=stack_set_name, OperationId=operation_id) |
| 422 |
if operation["StackSetOperation"]["Status"] not in ("RUNNING", "STOPPING"): |
| 423 |
# Stack set has completed operation |
| 424 |
break |
| 425 |
except is_boto3_error_code("StackSetNotFound"): # pylint: disable=duplicate-except |
| 426 |
pass |
| 427 |
except is_boto3_error_code("OperationNotFound"): # pylint: disable=duplicate-except |
| 428 |
pass |
| 429 |
time.sleep(15) |
| 430 |
|
| 431 |
if operation and operation["StackSetOperation"]["Status"] not in ("FAILED", "STOPPED"): |
| 432 |
await_stack_instance_completion( |
| 433 |
module, |
| 434 |
cfn, |
| 435 |
stack_set_name=stack_set_name, |
| 436 |
# subtract however long we waited already |
| 437 |
max_wait=int(max_wait - (datetime.datetime.now() - wait_start).total_seconds()), |
| 438 |
) |
| 439 |
elif operation and operation["StackSetOperation"]["Status"] in ("FAILED", "STOPPED"): |
| 440 |
pass |
| 441 |
else: |
| 442 |
module.warn( |
| 443 |
f"Timed out waiting for operation {operation_id} on stack set {stack_set_name} after {max_wait} seconds." |
| 444 |
" Returning unfinished operation" |
| 445 |
) |
| 446 |
|
| 447 |
|
| 448 |
def await_stack_instance_completion(module, cfn, stack_set_name, max_wait): |
| 449 |
to_await = None |
| 450 |
for i in range(max_wait // 15): |
| 451 |
try: |
| 452 |
stack_instances = cfn.list_stack_instances(StackSetName=stack_set_name) |
| 453 |
to_await = [inst for inst in stack_instances["Summaries"] if inst["Status"] != "CURRENT"] |
| 454 |
if not to_await: |
| 455 |
return stack_instances["Summaries"] |
| 456 |
except is_boto3_error_code("StackSetNotFound"): # pylint: disable=duplicate-except |
| 457 |
# this means the deletion beat us, or the stack set is not yet propagated |
| 458 |
pass |
| 459 |
time.sleep(15) |
| 460 |
|
| 461 |
module.warn( |
| 462 |
f"Timed out waiting for stack set {stack_set_name} instances {', '.join(s['StackId'] for s in to_await)} to" |
| 463 |
f" complete after {max_wait} seconds. Returning unfinished operation" |
| 464 |
) |
| 465 |
|
| 466 |
|
| 467 |
def await_stack_set_exists(cfn, stack_set_name): |
| 468 |
# AWSRetry will retry on `StackSetNotFound` errors for us |
| 469 |
ss = cfn.describe_stack_set(StackSetName=stack_set_name, aws_retry=True)["StackSet"] |
| 470 |
ss["Tags"] = boto3_tag_list_to_ansible_dict(ss["Tags"]) |
| 471 |
return camel_dict_to_snake_dict(ss, ignore_list=("Tags",)) |
| 472 |
|
| 473 |
|
| 474 |
def describe_stack_tree(module, stack_set_name, operation_ids=None): |
| 475 |
jittered_backoff_decorator = AWSRetry.jittered_backoff( |
| 476 |
retries=5, delay=3, max_delay=5, catch_extra_error_codes=["StackSetNotFound"] |
| 477 |
) |
| 478 |
cfn = module.client("cloudformation", retry_decorator=jittered_backoff_decorator) |
| 479 |
result = dict() |
| 480 |
result["stack_set"] = camel_dict_to_snake_dict( |
| 481 |
cfn.describe_stack_set( |
| 482 |
StackSetName=stack_set_name, |
| 483 |
aws_retry=True, |
| 484 |
)["StackSet"] |
| 485 |
) |
| 486 |
result["stack_set"]["tags"] = boto3_tag_list_to_ansible_dict(result["stack_set"]["tags"]) |
| 487 |
result["operations_log"] = sorted( |
| 488 |
camel_dict_to_snake_dict( |
| 489 |
cfn.list_stack_set_operations( |
| 490 |
StackSetName=stack_set_name, |
| 491 |
aws_retry=True, |
| 492 |
) |
| 493 |
)["summaries"], |
| 494 |
key=lambda x: x["creation_timestamp"], |
| 495 |
) |
| 496 |
result["stack_instances"] = sorted( |
| 497 |
[camel_dict_to_snake_dict(i) for i in cfn.list_stack_instances(StackSetName=stack_set_name)["Summaries"]], |
| 498 |
key=lambda i: i["region"] + i["account"], |
| 499 |
) |
| 500 |
|
| 501 |
if operation_ids: |
| 502 |
result["operations"] = [] |
| 503 |
for op_id in operation_ids: |
| 504 |
try: |
| 505 |
result["operations"].append( |
| 506 |
camel_dict_to_snake_dict( |
| 507 |
cfn.describe_stack_set_operation( |
| 508 |
StackSetName=stack_set_name, |
| 509 |
OperationId=op_id, |
| 510 |
)["StackSetOperation"] |
| 511 |
) |
| 512 |
) |
| 513 |
except is_boto3_error_code("OperationNotFoundException"): # pylint: disable=duplicate-except |
| 514 |
pass |
| 515 |
return result |
| 516 |
|
| 517 |
|
| 518 |
def get_operation_preferences(module): |
| 519 |
params = dict() |
| 520 |
if module.params.get("regions"): |
| 521 |
params["RegionOrder"] = list(module.params["regions"]) |
| 522 |
for param, api_name in { |
| 523 |
"fail_count": "FailureToleranceCount", |
| 524 |
"fail_percentage": "FailureTolerancePercentage", |
| 525 |
"parallel_percentage": "MaxConcurrentPercentage", |
| 526 |
"parallel_count": "MaxConcurrentCount", |
| 527 |
}.items(): |
| 528 |
if module.params.get("failure_tolerance", {}).get(param): |
| 529 |
params[api_name] = module.params.get("failure_tolerance", {}).get(param) |
| 530 |
return params |
| 531 |
|
| 532 |
|
| 533 |
def main(): |
| 534 |
argument_spec = dict( |
| 535 |
name=dict(required=True), |
| 536 |
description=dict(), |
| 537 |
wait=dict(type="bool", default=False), |
| 538 |
wait_timeout=dict(type="int", default=900), |
| 539 |
state=dict(default="present", choices=["present", "absent"]), |
| 540 |
purge_stacks=dict(type="bool", default=True), |
| 541 |
parameters=dict(type="dict", default={}), |
| 542 |
template=dict(type="path"), |
| 543 |
template_url=dict(), |
| 544 |
template_body=dict(), |
| 545 |
capabilities=dict(type="list", elements="str", choices=["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"]), |
| 546 |
regions=dict(type="list", elements="str"), |
| 547 |
accounts=dict(type="list", elements="str"), |
| 548 |
failure_tolerance=dict( |
| 549 |
type="dict", |
| 550 |
default={}, |
| 551 |
options=dict( |
| 552 |
fail_count=dict(type="int"), |
| 553 |
fail_percentage=dict(type="int"), |
| 554 |
parallel_percentage=dict(type="int"), |
| 555 |
parallel_count=dict(type="int"), |
| 556 |
), |
| 557 |
mutually_exclusive=[ |
| 558 |
["fail_count", "fail_percentage"], |
| 559 |
["parallel_count", "parallel_percentage"], |
| 560 |
], |
| 561 |
), |
| 562 |
administration_role_arn=dict(aliases=["admin_role_arn", "administration_role", "admin_role"]), |
| 563 |
execution_role_name=dict(aliases=["execution_role", "exec_role", "exec_role_name"]), |
| 564 |
tags=dict(type="dict"), |
| 565 |
) |
| 566 |
|
| 567 |
module = AnsibleAWSModule( |
| 568 |
argument_spec=argument_spec, |
| 569 |
mutually_exclusive=[["template_url", "template", "template_body"]], |
| 570 |
supports_check_mode=True, |
| 571 |
) |
| 572 |
|
| 573 |
# Wrap the cloudformation client methods that this module uses with |
| 574 |
# automatic backoff / retry for throttling error codes |
| 575 |
jittered_backoff_decorator = AWSRetry.jittered_backoff( |
| 576 |
retries=10, delay=3, max_delay=30, catch_extra_error_codes=["StackSetNotFound"] |
| 577 |
) |
| 578 |
cfn = module.client("cloudformation", retry_decorator=jittered_backoff_decorator) |
| 579 |
existing_stack_set = stack_set_facts(cfn, module.params["name"]) |
| 580 |
|
| 581 |
operation_uuid = to_native(uuid.uuid4()) |
| 582 |
operation_ids = [] |
| 583 |
# collect the parameters that are passed to boto3. Keeps us from having so many scalars floating around. |
| 584 |
stack_params = {} |
| 585 |
state = module.params["state"] |
| 586 |
if state == "present" and not module.params["accounts"]: |
| 587 |
module.fail_json( |
| 588 |
msg=( |
| 589 |
"Can't create a stack set without choosing at least one account. " |
| 590 |
"To get the ID of the current account, use the aws_caller_info module." |
| 591 |
) |
| 592 |
) |
| 593 |
|
| 594 |
module.params["accounts"] = [to_native(a) for a in module.params["accounts"]] |
| 595 |
|
| 596 |
stack_params["StackSetName"] = module.params["name"] |
| 597 |
if module.params.get("description"): |
| 598 |
stack_params["Description"] = module.params["description"] |
| 599 |
|
| 600 |
if module.params.get("capabilities"): |
| 601 |
stack_params["Capabilities"] = module.params["capabilities"] |
| 602 |
|
| 603 |
if module.params["template"] is not None: |
| 604 |
with open(module.params["template"], "r") as tpl: |
| 605 |
stack_params["TemplateBody"] = tpl.read() |
| 606 |
elif module.params["template_body"] is not None: |
| 607 |
stack_params["TemplateBody"] = module.params["template_body"] |
| 608 |
elif module.params["template_url"] is not None: |
| 609 |
stack_params["TemplateURL"] = module.params["template_url"] |
| 610 |
else: |
| 611 |
# no template is provided, but if the stack set exists already, we can use the existing one. |
| 612 |
if existing_stack_set: |
| 613 |
stack_params["UsePreviousTemplate"] = True |
| 614 |
else: |
| 615 |
module.fail_json( |
| 616 |
msg=( |
| 617 |
f"The Stack Set {module.params['name']} does not exist, and no template was provided. Provide one" |
| 618 |
" of `template`, `template_body`, or `template_url`" |
| 619 |
) |
| 620 |
) |
| 621 |
|
| 622 |
stack_params["Parameters"] = [] |
| 623 |
for k, v in module.params["parameters"].items(): |
| 624 |
if isinstance(v, dict): |
| 625 |
# set parameter based on a dict to allow additional CFN Parameter Attributes |
| 626 |
param = dict(ParameterKey=k) |
| 627 |
|
| 628 |
if "value" in v: |
| 629 |
param["ParameterValue"] = to_native(v["value"]) |
| 630 |
|
| 631 |
if "use_previous_value" in v and bool(v["use_previous_value"]): |
| 632 |
param["UsePreviousValue"] = True |
| 633 |
param.pop("ParameterValue", None) |
| 634 |
|
| 635 |
stack_params["Parameters"].append(param) |
| 636 |
else: |
| 637 |
# allow default k/v configuration to set a template parameter |
| 638 |
stack_params["Parameters"].append({"ParameterKey": k, "ParameterValue": str(v)}) |
| 639 |
|
| 640 |
if module.params.get("tags") and isinstance(module.params.get("tags"), dict): |
| 641 |
stack_params["Tags"] = ansible_dict_to_boto3_tag_list(module.params["tags"]) |
| 642 |
|
| 643 |
if module.params.get("administration_role_arn"): |
| 644 |
# TODO loosen the semantics here to autodetect the account ID and build the ARN |
| 645 |
stack_params["AdministrationRoleARN"] = module.params["administration_role_arn"] |
| 646 |
if module.params.get("execution_role_name"): |
| 647 |
stack_params["ExecutionRoleName"] = module.params["execution_role_name"] |
| 648 |
|
| 649 |
result = {} |
| 650 |
|
| 651 |
if module.check_mode: |
| 652 |
if state == "absent" and existing_stack_set: |
| 653 |
module.exit_json(changed=True, msg="Stack set would be deleted", meta=[]) |
| 654 |
elif state == "absent" and not existing_stack_set: |
| 655 |
module.exit_json(changed=False, msg="Stack set doesn't exist", meta=[]) |
| 656 |
elif state == "present" and not existing_stack_set: |
| 657 |
module.exit_json(changed=True, msg="New stack set would be created", meta=[]) |
| 658 |
elif state == "present" and existing_stack_set: |
| 659 |
new_stacks, existing_stacks, unspecified_stacks = compare_stack_instances( |
| 660 |
cfn, |
| 661 |
module.params["name"], |
| 662 |
module.params["accounts"], |
| 663 |
module.params["regions"], |
| 664 |
) |
| 665 |
if new_stacks: |
| 666 |
module.exit_json(changed=True, msg="New stack instance(s) would be created", meta=[]) |
| 667 |
elif unspecified_stacks and module.params.get("purge_stack_instances"): |
| 668 |
module.exit_json(changed=True, msg="Old stack instance(s) would be deleted", meta=[]) |
| 669 |
else: |
| 670 |
# TODO: need to check the template and other settings for correct check mode |
| 671 |
module.exit_json(changed=False, msg="No changes detected", meta=[]) |
| 672 |
|
| 673 |
changed = False |
| 674 |
if state == "present": |
| 675 |
if not existing_stack_set: |
| 676 |
# on create this parameter has a different name, and cannot be referenced later in the job log |
| 677 |
stack_params["ClientRequestToken"] = f"Ansible-StackSet-Create-{operation_uuid}" |
| 678 |
changed = True |
| 679 |
create_stack_set(module, stack_params, cfn) |
| 680 |
else: |
| 681 |
stack_params["OperationId"] = f"Ansible-StackSet-Update-{operation_uuid}" |
| 682 |
operation_ids.append(stack_params["OperationId"]) |
| 683 |
if module.params.get("regions"): |
| 684 |
stack_params["OperationPreferences"] = get_operation_preferences(module) |
| 685 |
changed |= update_stack_set(module, stack_params, cfn) |
| 686 |
|
| 687 |
await_stack_set_operation( |
| 688 |
module, |
| 689 |
cfn, |
| 690 |
operation_id=stack_params["OperationId"], |
| 691 |
stack_set_name=stack_params["StackSetName"], |
| 692 |
max_wait=module.params.get("wait_timeout"), |
| 693 |
) |
| 694 |
|
| 695 |
# now create/update any appropriate stack instances |
| 696 |
new_stack_instances, existing_stack_instances, unspecified_stack_instances = compare_stack_instances( |
| 697 |
cfn, |
| 698 |
module.params["name"], |
| 699 |
module.params["accounts"], |
| 700 |
module.params["regions"], |
| 701 |
) |
| 702 |
if new_stack_instances: |
| 703 |
operation_ids.append(f"Ansible-StackInstance-Create-{operation_uuid}") |
| 704 |
changed = True |
| 705 |
cfn.create_stack_instances( |
| 706 |
StackSetName=module.params["name"], |
| 707 |
Accounts=list(set(acct for acct, region in new_stack_instances)), |
| 708 |
Regions=list(set(region for acct, region in new_stack_instances)), |
| 709 |
OperationPreferences=get_operation_preferences(module), |
| 710 |
OperationId=operation_ids[-1], |
| 711 |
) |
| 712 |
else: |
| 713 |
operation_ids.append(f"Ansible-StackInstance-Update-{operation_uuid}") |
| 714 |
cfn.update_stack_instances( |
| 715 |
StackSetName=module.params["name"], |
| 716 |
Accounts=list(set(acct for acct, region in existing_stack_instances)), |
| 717 |
Regions=list(set(region for acct, region in existing_stack_instances)), |
| 718 |
OperationPreferences=get_operation_preferences(module), |
| 719 |
OperationId=operation_ids[-1], |
| 720 |
) |
| 721 |
for op in operation_ids: |
| 722 |
await_stack_set_operation( |
| 723 |
module, |
| 724 |
cfn, |
| 725 |
operation_id=op, |
| 726 |
stack_set_name=module.params["name"], |
| 727 |
max_wait=module.params.get("wait_timeout"), |
| 728 |
) |
| 729 |
|
| 730 |
elif state == "absent": |
| 731 |
if not existing_stack_set: |
| 732 |
module.exit_json(msg=f"Stack set {module.params['name']} does not exist") |
| 733 |
if module.params.get("purge_stack_instances") is False: |
| 734 |
pass |
| 735 |
try: |
| 736 |
cfn.delete_stack_set( |
| 737 |
StackSetName=module.params["name"], |
| 738 |
) |
| 739 |
module.exit_json(msg=f"Stack set {module.params['name']} deleted") |
| 740 |
except is_boto3_error_code("OperationInProgressException") as e: # pylint: disable=duplicate-except |
| 741 |
module.fail_json_aws( |
| 742 |
e, msg=f"Cannot delete stack {module.params['name']} while there is an operation in progress" |
| 743 |
) |
| 744 |
except is_boto3_error_code("StackSetNotEmptyException"): # pylint: disable=duplicate-except |
| 745 |
delete_instances_op = f"Ansible-StackInstance-Delete-{operation_uuid}" |
| 746 |
cfn.delete_stack_instances( |
| 747 |
StackSetName=module.params["name"], |
| 748 |
Accounts=module.params["accounts"], |
| 749 |
Regions=module.params["regions"], |
| 750 |
RetainStacks=(not module.params.get("purge_stacks")), |
| 751 |
OperationId=delete_instances_op, |
| 752 |
) |
| 753 |
await_stack_set_operation( |
| 754 |
module, |
| 755 |
cfn, |
| 756 |
operation_id=delete_instances_op, |
| 757 |
stack_set_name=stack_params["StackSetName"], |
| 758 |
max_wait=module.params.get("wait_timeout"), |
| 759 |
) |
| 760 |
try: |
| 761 |
cfn.delete_stack_set( |
| 762 |
StackSetName=module.params["name"], |
| 763 |
) |
| 764 |
except is_boto3_error_code("StackSetNotEmptyException") as exc: # pylint: disable=duplicate-except |
| 765 |
# this time, it is likely that either the delete failed or there are more stacks. |
| 766 |
instances = cfn.list_stack_instances( |
| 767 |
StackSetName=module.params["name"], |
| 768 |
) |
| 769 |
stack_states = ", ".join( |
| 770 |
"(account={Account}, region={Region}, state={Status})".format(**i) for i in instances["Summaries"] |
| 771 |
) |
| 772 |
module.fail_json_aws( |
| 773 |
exc, |
| 774 |
msg="Could not purge all stacks, or not all accounts/regions were chosen for deletion: " |
| 775 |
+ stack_states, |
| 776 |
) |
| 777 |
module.exit_json(changed=True, msg=f"Stack set {module.params['name']} deleted") |
| 778 |
|
| 779 |
result.update(**describe_stack_tree(module, stack_params["StackSetName"], operation_ids=operation_ids)) |
| 780 |
if any(o["status"] == "FAILED" for o in result["operations"]): |
| 781 |
module.fail_json(msg="One or more operations failed to execute", **result) |
| 782 |
module.exit_json(changed=changed, **result) |
| 783 |
|
| 784 |
|
| 785 |
if __name__ == "__main__": |
| 786 |
main() |