| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: 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: sqs_queue |
| 10 |
version_added: 1.0.0 |
| 11 |
short_description: Creates or deletes AWS SQS queues |
| 12 |
description: |
| 13 |
- Create or delete AWS SQS queues. |
| 14 |
- Update attributes on existing queues. |
| 15 |
author: |
| 16 |
- Alan Loi (@loia) |
| 17 |
- Fernando Jose Pando (@nand0p) |
| 18 |
- Nadir Lloret (@nadirollo) |
| 19 |
- Dennis Podkovyrin (@sbj-ss) |
| 20 |
options: |
| 21 |
state: |
| 22 |
description: |
| 23 |
- Create or delete the queue. |
| 24 |
choices: ['present', 'absent'] |
| 25 |
default: 'present' |
| 26 |
type: str |
| 27 |
name: |
| 28 |
description: |
| 29 |
- Name of the queue. |
| 30 |
required: true |
| 31 |
type: str |
| 32 |
queue_type: |
| 33 |
description: |
| 34 |
- Standard or FIFO queue. |
| 35 |
- I(queue_type) can only be set at queue creation and will otherwise be |
| 36 |
ignored. |
| 37 |
choices: ['standard', 'fifo'] |
| 38 |
default: 'standard' |
| 39 |
type: str |
| 40 |
deduplication_scope: |
| 41 |
description: |
| 42 |
- Deduplication scope for FIFO queues. |
| 43 |
- C(messageGroup) is required for high throughput FIFO. |
| 44 |
- Defaults to C(queue) on creation. |
| 45 |
choices: ['queue', 'messageGroup'] |
| 46 |
type: str |
| 47 |
version_added: 5.3.0 |
| 48 |
fifo_throughput_limit: |
| 49 |
description: |
| 50 |
- Throughput limit for FIFO queues. |
| 51 |
- C(perMessageGroupId) is required for high throughput FIFO. |
| 52 |
- Defaults to C(perQueue) on creation. |
| 53 |
choices: ['perQueue', 'perMessageGroupId'] |
| 54 |
type: str |
| 55 |
version_added: 5.3.0 |
| 56 |
visibility_timeout: |
| 57 |
description: |
| 58 |
- The default visibility timeout in seconds. |
| 59 |
aliases: [default_visibility_timeout] |
| 60 |
type: int |
| 61 |
message_retention_period: |
| 62 |
description: |
| 63 |
- The message retention period in seconds. |
| 64 |
type: int |
| 65 |
maximum_message_size: |
| 66 |
description: |
| 67 |
- The maximum message size in bytes. |
| 68 |
type: int |
| 69 |
delay_seconds: |
| 70 |
description: |
| 71 |
- The delivery delay in seconds. |
| 72 |
aliases: [delivery_delay] |
| 73 |
type: int |
| 74 |
receive_message_wait_time_seconds: |
| 75 |
description: |
| 76 |
- The receive message wait time in seconds. |
| 77 |
aliases: [receive_message_wait_time] |
| 78 |
type: int |
| 79 |
policy: |
| 80 |
description: |
| 81 |
- Policy to attach to the queue. |
| 82 |
- Policy body can be YAML or JSON. |
| 83 |
- This is required for certain use cases for example with S3 bucket notifications. |
| 84 |
type: dict |
| 85 |
redrive_policy: |
| 86 |
description: |
| 87 |
- JSON dict with the redrive_policy (see example). |
| 88 |
type: dict |
| 89 |
kms_master_key_id: |
| 90 |
description: |
| 91 |
- The ID of an AWS-managed customer master key (CMK) for Amazon SQS or a custom CMK. |
| 92 |
- Specifying a valid I(kms_master_key_id) will enable encryption automatically. |
| 93 |
type: str |
| 94 |
kms_data_key_reuse_period_seconds: |
| 95 |
description: |
| 96 |
- The length of time, in seconds, for which Amazon SQS can reuse a data key to encrypt or decrypt messages before calling AWS KMS again. |
| 97 |
aliases: [kms_data_key_reuse_period] |
| 98 |
type: int |
| 99 |
content_based_deduplication: |
| 100 |
type: bool |
| 101 |
description: |
| 102 |
- Enables content-based deduplication. Used for FIFOs only. |
| 103 |
- Defaults to C(false). |
| 104 |
extends_documentation_fragment: |
| 105 |
- amazon.aws.common.modules |
| 106 |
- amazon.aws.region.modules |
| 107 |
- amazon.aws.tags |
| 108 |
- amazon.aws.boto3 |
| 109 |
""" |
| 110 |
|
| 111 |
RETURN = r""" |
| 112 |
content_based_deduplication: |
| 113 |
description: Enables content-based deduplication. Used for FIFOs only. |
| 114 |
type: bool |
| 115 |
returned: always |
| 116 |
sample: True |
| 117 |
fifo_throughput_limit: |
| 118 |
description: Which throughput limit strategy is applied. |
| 119 |
type: str |
| 120 |
returned: always |
| 121 |
sample: perQueue |
| 122 |
deduplication_scope: |
| 123 |
description: The deduplication setting. |
| 124 |
type: str |
| 125 |
returned: always |
| 126 |
sample: messageGroup |
| 127 |
visibility_timeout: |
| 128 |
description: The default visibility timeout in seconds. |
| 129 |
type: int |
| 130 |
returned: always |
| 131 |
sample: 30 |
| 132 |
delay_seconds: |
| 133 |
description: The delivery delay in seconds. |
| 134 |
type: int |
| 135 |
returned: always |
| 136 |
sample: 0 |
| 137 |
kms_master_key_id: |
| 138 |
description: The ID of an AWS-managed customer master key (CMK) for Amazon SQS or a custom CMK. |
| 139 |
type: str |
| 140 |
returned: if value exists |
| 141 |
sample: alias/MyAlias |
| 142 |
kms_data_key_reuse_period_seconds: |
| 143 |
description: The length of time, in seconds, for which Amazon SQS can reuse a data key to encrypt or decrypt messages before calling AWS KMS again. |
| 144 |
type: int |
| 145 |
returned: always |
| 146 |
sample: 300 |
| 147 |
maximum_message_size: |
| 148 |
description: The maximum message size in bytes. |
| 149 |
type: int |
| 150 |
returned: always |
| 151 |
sample: 262144 |
| 152 |
message_retention_period: |
| 153 |
description: The message retention period in seconds. |
| 154 |
type: int |
| 155 |
returned: always |
| 156 |
sample: 345600 |
| 157 |
name: |
| 158 |
description: Name of the SQS Queue |
| 159 |
type: str |
| 160 |
returned: always |
| 161 |
sample: "queuename-987d2de0" |
| 162 |
queue_arn: |
| 163 |
description: The queue's Amazon resource name (ARN). |
| 164 |
type: str |
| 165 |
returned: on success |
| 166 |
sample: 'arn:aws:sqs:us-east-1:123456789012:queuename-987d2de0' |
| 167 |
queue_url: |
| 168 |
description: URL to access the queue |
| 169 |
type: str |
| 170 |
returned: on success |
| 171 |
sample: 'https://queue.amazonaws.com/123456789012/MyQueue' |
| 172 |
receive_message_wait_time_seconds: |
| 173 |
description: The receive message wait time in seconds. |
| 174 |
type: int |
| 175 |
returned: always |
| 176 |
sample: 0 |
| 177 |
region: |
| 178 |
description: Region that the queue was created within |
| 179 |
type: str |
| 180 |
returned: always |
| 181 |
sample: 'us-east-1' |
| 182 |
tags: |
| 183 |
description: List of queue tags |
| 184 |
type: dict |
| 185 |
returned: always |
| 186 |
sample: '{"Env": "prod"}' |
| 187 |
""" |
| 188 |
|
| 189 |
EXAMPLES = r""" |
| 190 |
- name: Create SQS queue with redrive policy |
| 191 |
community.aws.sqs_queue: |
| 192 |
name: my-queue |
| 193 |
region: ap-southeast-2 |
| 194 |
default_visibility_timeout: 120 |
| 195 |
message_retention_period: 86400 |
| 196 |
maximum_message_size: 1024 |
| 197 |
delivery_delay: 30 |
| 198 |
receive_message_wait_time: 20 |
| 199 |
policy: "{{ json_dict }}" |
| 200 |
redrive_policy: |
| 201 |
maxReceiveCount: 5 |
| 202 |
deadLetterTargetArn: arn:aws:sqs:eu-west-1:123456789012:my-dead-queue |
| 203 |
|
| 204 |
- name: Drop redrive policy |
| 205 |
community.aws.sqs_queue: |
| 206 |
name: my-queue |
| 207 |
region: ap-southeast-2 |
| 208 |
redrive_policy: {} |
| 209 |
|
| 210 |
- name: Create FIFO queue |
| 211 |
community.aws.sqs_queue: |
| 212 |
name: fifo-queue |
| 213 |
region: ap-southeast-2 |
| 214 |
queue_type: fifo |
| 215 |
content_based_deduplication: true |
| 216 |
|
| 217 |
- name: Tag queue |
| 218 |
community.aws.sqs_queue: |
| 219 |
name: fifo-queue |
| 220 |
region: ap-southeast-2 |
| 221 |
tags: |
| 222 |
example: SomeValue |
| 223 |
|
| 224 |
- name: Configure Encryption, automatically uses a new data key every hour |
| 225 |
community.aws.sqs_queue: |
| 226 |
name: fifo-queue |
| 227 |
region: ap-southeast-2 |
| 228 |
kms_master_key_id: alias/MyQueueKey |
| 229 |
kms_data_key_reuse_period_seconds: 3600 |
| 230 |
|
| 231 |
- name: Example queue allowing s3 bucket notifications |
| 232 |
sqs_queue: |
| 233 |
name: "S3Notifications" |
| 234 |
default_visibility_timeout: 120 |
| 235 |
message_retention_period: 86400 |
| 236 |
maximum_message_size: 1024 |
| 237 |
delivery_delay: 30 |
| 238 |
receive_message_wait_time: 20 |
| 239 |
policy: |
| 240 |
Version: 2012-10-17 |
| 241 |
Id: s3-queue-policy |
| 242 |
Statement: |
| 243 |
- Sid: allowNotifications |
| 244 |
Effect: Allow |
| 245 |
Principal: |
| 246 |
Service: s3.amazonaws.com |
| 247 |
Action: |
| 248 |
- SQS:SendMessage |
| 249 |
Resource: "arn:aws:sqs:*:*:S3Notifications" |
| 250 |
Condition: |
| 251 |
ArnLike: |
| 252 |
aws:SourceArn: "arn:aws:s3:*:*:SomeBucket" |
| 253 |
|
| 254 |
- name: Delete SQS queue |
| 255 |
community.aws.sqs_queue: |
| 256 |
name: my-queue |
| 257 |
region: ap-southeast-2 |
| 258 |
state: absent |
| 259 |
""" |
| 260 |
|
| 261 |
import json |
| 262 |
|
| 263 |
try: |
| 264 |
import botocore |
| 265 |
except ImportError: |
| 266 |
pass # handled by AnsibleAWSModule |
| 267 |
|
| 268 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 269 |
from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict |
| 270 |
|
| 271 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code |
| 272 |
from ansible_collections.amazon.aws.plugins.module_utils.policy import compare_policies |
| 273 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 274 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags |
| 275 |
|
| 276 |
from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule |
| 277 |
|
| 278 |
|
| 279 |
def get_queue_name(module, is_fifo=False): |
| 280 |
name = module.params.get("name") |
| 281 |
if not is_fifo or name.endswith(".fifo"): |
| 282 |
return name |
| 283 |
return name + ".fifo" |
| 284 |
|
| 285 |
|
| 286 |
# NonExistentQueue is explicitly expected when a queue doesn't exist |
| 287 |
@AWSRetry.jittered_backoff() |
| 288 |
def get_queue_url(client, name): |
| 289 |
try: |
| 290 |
return client.get_queue_url(QueueName=name)["QueueUrl"] |
| 291 |
except is_boto3_error_code("AWS.SimpleQueueService.NonExistentQueue"): |
| 292 |
return None |
| 293 |
|
| 294 |
|
| 295 |
def describe_queue(client, queue_url): |
| 296 |
""" |
| 297 |
Description a queue in snake format |
| 298 |
""" |
| 299 |
attributes = client.get_queue_attributes(QueueUrl=queue_url, AttributeNames=["All"], aws_retry=True)["Attributes"] |
| 300 |
description = dict(attributes) |
| 301 |
description.pop("Policy", None) |
| 302 |
description.pop("RedrivePolicy", None) |
| 303 |
description = camel_dict_to_snake_dict(description) |
| 304 |
description["policy"] = attributes.get("Policy", None) |
| 305 |
description["redrive_policy"] = attributes.get("RedrivePolicy", None) |
| 306 |
|
| 307 |
# Boto3 returns everything as a string, convert them back to integers/dicts if |
| 308 |
# that's what we expected. |
| 309 |
for key, value in description.items(): |
| 310 |
if value is None: |
| 311 |
continue |
| 312 |
|
| 313 |
if key in ["policy", "redrive_policy"]: |
| 314 |
policy = json.loads(value) |
| 315 |
description[key] = policy |
| 316 |
continue |
| 317 |
|
| 318 |
if key == "content_based_deduplication": |
| 319 |
try: |
| 320 |
description[key] = bool(value) |
| 321 |
except (TypeError, ValueError): |
| 322 |
pass |
| 323 |
|
| 324 |
try: |
| 325 |
if value == str(int(value)): |
| 326 |
description[key] = int(value) |
| 327 |
except (TypeError, ValueError): |
| 328 |
pass |
| 329 |
|
| 330 |
return description |
| 331 |
|
| 332 |
|
| 333 |
def create_or_update_sqs_queue(client, module): |
| 334 |
is_fifo = module.params.get("queue_type") == "fifo" |
| 335 |
kms_master_key_id = module.params.get("kms_master_key_id") |
| 336 |
queue_name = get_queue_name(module, is_fifo) |
| 337 |
result = dict( |
| 338 |
name=queue_name, |
| 339 |
region=module.params.get("region"), |
| 340 |
changed=False, |
| 341 |
) |
| 342 |
|
| 343 |
queue_url = get_queue_url(client, queue_name) |
| 344 |
result["queue_url"] = queue_url |
| 345 |
|
| 346 |
# Create a dict() to hold attributes that will be passed to boto3 |
| 347 |
create_attributes = {} |
| 348 |
|
| 349 |
if not queue_url: |
| 350 |
if is_fifo: |
| 351 |
create_attributes["FifoQueue"] = "True" |
| 352 |
if kms_master_key_id: |
| 353 |
create_attributes["KmsMasterKeyId"] = kms_master_key_id |
| 354 |
result["changed"] = True |
| 355 |
if module.check_mode: |
| 356 |
return result |
| 357 |
queue_url = client.create_queue(QueueName=queue_name, Attributes=create_attributes, aws_retry=True)["QueueUrl"] |
| 358 |
|
| 359 |
changed, arn = update_sqs_queue(module, client, queue_url) |
| 360 |
result["changed"] |= changed |
| 361 |
result["queue_arn"] = arn |
| 362 |
|
| 363 |
changed, tags = update_tags(client, queue_url, module) |
| 364 |
result["changed"] |= changed |
| 365 |
result["tags"] = tags |
| 366 |
|
| 367 |
result.update(describe_queue(client, queue_url)) |
| 368 |
|
| 369 |
COMPATABILITY_KEYS = dict( |
| 370 |
delay_seconds="delivery_delay", |
| 371 |
receive_message_wait_time_seconds="receive_message_wait_time", |
| 372 |
visibility_timeout="default_visibility_timeout", |
| 373 |
kms_data_key_reuse_period_seconds="kms_data_key_reuse_period", |
| 374 |
) |
| 375 |
for key in list(result.keys()): |
| 376 |
# The return values changed between boto and boto3, add the old keys too |
| 377 |
# for backwards compatibility |
| 378 |
return_name = COMPATABILITY_KEYS.get(key) |
| 379 |
if return_name: |
| 380 |
result[return_name] = result.get(key) |
| 381 |
|
| 382 |
return result |
| 383 |
|
| 384 |
|
| 385 |
def update_sqs_queue(module, client, queue_url): |
| 386 |
check_mode = module.check_mode |
| 387 |
changed = False |
| 388 |
existing_attributes = client.get_queue_attributes(QueueUrl=queue_url, AttributeNames=["All"], aws_retry=True)[ |
| 389 |
"Attributes" |
| 390 |
] |
| 391 |
new_attributes = snake_dict_to_camel_dict(module.params, capitalize_first=True) |
| 392 |
attributes_to_set = dict() |
| 393 |
|
| 394 |
# Boto3 SQS deals with policies as strings, we want to deal with them as |
| 395 |
# dicts |
| 396 |
if module.params.get("policy") is not None: |
| 397 |
policy = module.params.get("policy") |
| 398 |
current_value = existing_attributes.get("Policy", "{}") |
| 399 |
current_policy = json.loads(current_value) |
| 400 |
if compare_policies(current_policy, policy): |
| 401 |
attributes_to_set["Policy"] = json.dumps(policy) |
| 402 |
changed = True |
| 403 |
if module.params.get("redrive_policy") is not None: |
| 404 |
policy = module.params.get("redrive_policy") |
| 405 |
current_value = existing_attributes.get("RedrivePolicy", "{}") |
| 406 |
current_policy = json.loads(current_value) |
| 407 |
if compare_policies(current_policy, policy): |
| 408 |
attributes_to_set["RedrivePolicy"] = json.dumps(policy) |
| 409 |
changed = True |
| 410 |
|
| 411 |
for attribute, value in existing_attributes.items(): |
| 412 |
# We handle these as a special case because they're IAM policies |
| 413 |
if attribute in ["Policy", "RedrivePolicy"]: |
| 414 |
continue |
| 415 |
|
| 416 |
if attribute not in new_attributes.keys(): |
| 417 |
continue |
| 418 |
|
| 419 |
if new_attributes.get(attribute) is None: |
| 420 |
continue |
| 421 |
|
| 422 |
new_value = new_attributes[attribute] |
| 423 |
|
| 424 |
if isinstance(new_value, bool): |
| 425 |
new_value = str(new_value).lower() |
| 426 |
value = str(value).lower() |
| 427 |
|
| 428 |
if str(new_value) == str(value): |
| 429 |
continue |
| 430 |
|
| 431 |
# Boto3 expects strings |
| 432 |
attributes_to_set[attribute] = str(new_value) |
| 433 |
changed = True |
| 434 |
|
| 435 |
if changed and not check_mode: |
| 436 |
client.set_queue_attributes(QueueUrl=queue_url, Attributes=attributes_to_set, aws_retry=True) |
| 437 |
|
| 438 |
return changed, existing_attributes.get("queue_arn") |
| 439 |
|
| 440 |
|
| 441 |
def delete_sqs_queue(client, module): |
| 442 |
is_fifo = module.params.get("queue_type") == "fifo" |
| 443 |
queue_name = get_queue_name(module, is_fifo) |
| 444 |
result = dict(name=queue_name, region=module.params.get("region"), changed=False) |
| 445 |
|
| 446 |
queue_url = get_queue_url(client, queue_name) |
| 447 |
if not queue_url: |
| 448 |
return result |
| 449 |
|
| 450 |
result["changed"] = bool(queue_url) |
| 451 |
if not module.check_mode: |
| 452 |
AWSRetry.jittered_backoff()(client.delete_queue)(QueueUrl=queue_url) |
| 453 |
|
| 454 |
return result |
| 455 |
|
| 456 |
|
| 457 |
def update_tags(client, queue_url, module): |
| 458 |
new_tags = module.params.get("tags") |
| 459 |
purge_tags = module.params.get("purge_tags") |
| 460 |
if new_tags is None: |
| 461 |
return False, {} |
| 462 |
|
| 463 |
try: |
| 464 |
existing_tags = client.list_queue_tags(QueueUrl=queue_url, aws_retry=True)["Tags"] |
| 465 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError, KeyError): |
| 466 |
existing_tags = {} |
| 467 |
|
| 468 |
tags_to_add, tags_to_remove = compare_aws_tags(existing_tags, new_tags, purge_tags=purge_tags) |
| 469 |
|
| 470 |
if not module.check_mode: |
| 471 |
if tags_to_remove: |
| 472 |
client.untag_queue(QueueUrl=queue_url, TagKeys=tags_to_remove, aws_retry=True) |
| 473 |
if tags_to_add: |
| 474 |
client.tag_queue(QueueUrl=queue_url, Tags=tags_to_add) |
| 475 |
existing_tags = client.list_queue_tags(QueueUrl=queue_url, aws_retry=True).get("Tags", {}) |
| 476 |
else: |
| 477 |
existing_tags = new_tags |
| 478 |
|
| 479 |
changed = bool(tags_to_remove) or bool(tags_to_add) |
| 480 |
return changed, existing_tags |
| 481 |
|
| 482 |
|
| 483 |
def main(): |
| 484 |
argument_spec = dict( |
| 485 |
state=dict(type="str", default="present", choices=["present", "absent"]), |
| 486 |
name=dict(type="str", required=True), |
| 487 |
queue_type=dict(type="str", default="standard", choices=["standard", "fifo"]), |
| 488 |
delay_seconds=dict(type="int", aliases=["delivery_delay"]), |
| 489 |
maximum_message_size=dict(type="int"), |
| 490 |
message_retention_period=dict(type="int"), |
| 491 |
policy=dict(type="dict"), |
| 492 |
receive_message_wait_time_seconds=dict(type="int", aliases=["receive_message_wait_time"]), |
| 493 |
redrive_policy=dict(type="dict"), |
| 494 |
visibility_timeout=dict(type="int", aliases=["default_visibility_timeout"]), |
| 495 |
kms_master_key_id=dict(type="str"), |
| 496 |
fifo_throughput_limit=dict(type="str", choices=["perQueue", "perMessageGroupId"]), |
| 497 |
deduplication_scope=dict(type="str", choices=["queue", "messageGroup"]), |
| 498 |
kms_data_key_reuse_period_seconds=dict(type="int", aliases=["kms_data_key_reuse_period"], no_log=False), |
| 499 |
content_based_deduplication=dict(type="bool"), |
| 500 |
tags=dict(type="dict", aliases=["resource_tags"]), |
| 501 |
purge_tags=dict(type="bool", default=True), |
| 502 |
) |
| 503 |
module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True) |
| 504 |
|
| 505 |
state = module.params.get("state") |
| 506 |
retry_decorator = AWSRetry.jittered_backoff(catch_extra_error_codes=["AWS.SimpleQueueService.NonExistentQueue"]) |
| 507 |
try: |
| 508 |
client = module.client("sqs", retry_decorator=retry_decorator) |
| 509 |
if state == "present": |
| 510 |
result = create_or_update_sqs_queue(client, module) |
| 511 |
elif state == "absent": |
| 512 |
result = delete_sqs_queue(client, module) |
| 513 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 514 |
module.fail_json_aws(e, msg="Failed to control sqs queue") |
| 515 |
else: |
| 516 |
module.exit_json(**result) |
| 517 |
|
| 518 |
|
| 519 |
if __name__ == "__main__": |
| 520 |
main() |