| 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: elb_classic_lb |
| 10 |
version_added: 1.0.0 |
| 11 |
description: |
| 12 |
- Creates, updates or destroys an Amazon Elastic Load Balancer (ELB). |
| 13 |
- This module was renamed from M(amazon.aws.ec2_elb_lb) to M(amazon.aws.elb_classic_lb) in version |
| 14 |
2.1.0 of the amazon.aws collection. |
| 15 |
short_description: Creates, updates or destroys an Amazon ELB |
| 16 |
author: |
| 17 |
- "Jim Dalton (@jsdalton)" |
| 18 |
- "Mark Chappell (@tremble)" |
| 19 |
options: |
| 20 |
state: |
| 21 |
description: |
| 22 |
- Create or destroy the ELB. |
| 23 |
type: str |
| 24 |
choices: [ absent, present ] |
| 25 |
required: true |
| 26 |
name: |
| 27 |
description: |
| 28 |
- The name of the ELB. |
| 29 |
- The name of an ELB must be less than 32 characters and unique per-region per-account. |
| 30 |
type: str |
| 31 |
required: true |
| 32 |
listeners: |
| 33 |
description: |
| 34 |
- List of ports/protocols for this ELB to listen on (see examples). |
| 35 |
- Required when O(state=present) and the ELB doesn't exist. |
| 36 |
type: list |
| 37 |
elements: dict |
| 38 |
suboptions: |
| 39 |
load_balancer_port: |
| 40 |
description: |
| 41 |
- The port on which the load balancer will listen. |
| 42 |
type: int |
| 43 |
required: True |
| 44 |
instance_port: |
| 45 |
description: |
| 46 |
- The port on which the instance is listening. |
| 47 |
type: int |
| 48 |
required: True |
| 49 |
ssl_certificate_id: |
| 50 |
description: |
| 51 |
- The Amazon Resource Name (ARN) of the SSL certificate. |
| 52 |
type: str |
| 53 |
protocol: |
| 54 |
description: |
| 55 |
- The transport protocol to use for routing. |
| 56 |
- Valid values are V(HTTP), V(HTTPS), V(TCP), or V(SSL). |
| 57 |
type: str |
| 58 |
required: True |
| 59 |
instance_protocol: |
| 60 |
description: |
| 61 |
- The protocol to use for routing traffic to instances. |
| 62 |
- Valid values are V(HTTP), V(HTTPS), V(TCP), or V(SSL), |
| 63 |
type: str |
| 64 |
proxy_protocol: |
| 65 |
description: |
| 66 |
- Enable proxy protocol for the listener. |
| 67 |
- Beware, ELB controls for the proxy protocol are based on the |
| 68 |
O(listeners.instance_port). If you have multiple listeners talking to |
| 69 |
the same O(listeners.instance_port), this will affect all of them. |
| 70 |
type: bool |
| 71 |
purge_listeners: |
| 72 |
description: |
| 73 |
- Purge existing listeners on ELB that are not found in listeners. |
| 74 |
type: bool |
| 75 |
default: true |
| 76 |
instance_ids: |
| 77 |
description: |
| 78 |
- List of instance ids to attach to this ELB. |
| 79 |
type: list |
| 80 |
elements: str |
| 81 |
purge_instance_ids: |
| 82 |
description: |
| 83 |
- Purge existing instance ids on ELB that are not found in O(instance_ids). |
| 84 |
type: bool |
| 85 |
default: false |
| 86 |
zones: |
| 87 |
description: |
| 88 |
- List of availability zones to enable on this ELB. |
| 89 |
- Mutually exclusive with O(subnets). |
| 90 |
type: list |
| 91 |
elements: str |
| 92 |
purge_zones: |
| 93 |
description: |
| 94 |
- Purge existing availability zones on ELB that are not found in O(zones). |
| 95 |
type: bool |
| 96 |
default: false |
| 97 |
security_group_ids: |
| 98 |
description: |
| 99 |
- A list of security groups to apply to the ELB. |
| 100 |
type: list |
| 101 |
elements: str |
| 102 |
security_group_names: |
| 103 |
description: |
| 104 |
- A list of security group names to apply to the ELB. |
| 105 |
type: list |
| 106 |
elements: str |
| 107 |
health_check: |
| 108 |
description: |
| 109 |
- A dictionary of health check configuration settings (see examples). |
| 110 |
type: dict |
| 111 |
suboptions: |
| 112 |
ping_protocol: |
| 113 |
description: |
| 114 |
- The protocol which the ELB health check will use when performing a |
| 115 |
health check. |
| 116 |
- Valid values are V('HTTP'), V('HTTPS'), V('TCP') and V('SSL'). |
| 117 |
required: true |
| 118 |
type: str |
| 119 |
ping_path: |
| 120 |
description: |
| 121 |
- The URI path which the ELB health check will query when performing a |
| 122 |
health check. |
| 123 |
- Required when O(health_check.ping_protocol=HTTP) or O(health_check.ping_protocol=HTTPS). |
| 124 |
required: false |
| 125 |
type: str |
| 126 |
ping_port: |
| 127 |
description: |
| 128 |
- The TCP port to which the ELB will connect when performing a |
| 129 |
health check. |
| 130 |
required: true |
| 131 |
type: int |
| 132 |
interval: |
| 133 |
description: |
| 134 |
- The approximate interval, in seconds, between health checks of an individual instance. |
| 135 |
required: true |
| 136 |
type: int |
| 137 |
timeout: |
| 138 |
description: |
| 139 |
- The amount of time, in seconds, after which no response means a failed health check. |
| 140 |
aliases: ['response_timeout'] |
| 141 |
required: true |
| 142 |
type: int |
| 143 |
unhealthy_threshold: |
| 144 |
description: |
| 145 |
- The number of consecutive health check failures required before moving |
| 146 |
the instance to the Unhealthy state. |
| 147 |
required: true |
| 148 |
type: int |
| 149 |
healthy_threshold: |
| 150 |
description: |
| 151 |
- The number of consecutive health checks successes required before moving |
| 152 |
the instance to the Healthy state. |
| 153 |
required: true |
| 154 |
type: int |
| 155 |
access_logs: |
| 156 |
description: |
| 157 |
- A dictionary of access logs configuration settings (see examples). |
| 158 |
type: dict |
| 159 |
suboptions: |
| 160 |
enabled: |
| 161 |
description: |
| 162 |
- When set to V(true) will configure delivery of access logs to an S3 |
| 163 |
bucket. |
| 164 |
- When set to V(false) will disable delivery of access logs. |
| 165 |
required: false |
| 166 |
type: bool |
| 167 |
default: true |
| 168 |
s3_location: |
| 169 |
description: |
| 170 |
- The S3 bucket to deliver access logs to. |
| 171 |
- See U(https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/enable-access-logs.html) |
| 172 |
for more information about the necessary S3 bucket policies. |
| 173 |
- Required when O(access_logs.enabled=true). |
| 174 |
required: false |
| 175 |
type: str |
| 176 |
s3_prefix: |
| 177 |
description: |
| 178 |
- Where in the S3 bucket to deliver the logs. |
| 179 |
- If the prefix is not provided or set to V(""), the log is placed at the root level of the bucket. |
| 180 |
required: false |
| 181 |
type: str |
| 182 |
default: "" |
| 183 |
interval: |
| 184 |
description: |
| 185 |
- The interval for publishing the access logs to S3. |
| 186 |
required: false |
| 187 |
type: int |
| 188 |
default: 60 |
| 189 |
choices: [ 5, 60 ] |
| 190 |
subnets: |
| 191 |
description: |
| 192 |
- A list of VPC subnets to use when creating the ELB. |
| 193 |
- Mutually exclusive with O(zones). |
| 194 |
type: list |
| 195 |
elements: str |
| 196 |
purge_subnets: |
| 197 |
description: |
| 198 |
- Purge existing subnets on the ELB that are not found in O(subnets). |
| 199 |
- Because it is not permitted to add multiple subnets from the same |
| 200 |
availability zone, subnets to be purged will be removed before new |
| 201 |
subnets are added. This may cause a brief outage if you try to replace |
| 202 |
all subnets at once. |
| 203 |
type: bool |
| 204 |
default: false |
| 205 |
scheme: |
| 206 |
description: |
| 207 |
- The scheme to use when creating the ELB. |
| 208 |
- For a private VPC-visible ELB use C(internal). |
| 209 |
- If you choose to update your scheme with a different value the ELB will be destroyed and |
| 210 |
a new ELB created. |
| 211 |
- Defaults to O(scheme=internet-facing). |
| 212 |
type: str |
| 213 |
choices: ["internal", "internet-facing"] |
| 214 |
connection_draining_timeout: |
| 215 |
description: |
| 216 |
- Wait a specified timeout allowing connections to drain before terminating an instance. |
| 217 |
- Set to V(0) to disable connection draining. |
| 218 |
type: int |
| 219 |
idle_timeout: |
| 220 |
description: |
| 221 |
- ELB connections from clients and to servers are timed out after this amount of time. |
| 222 |
type: int |
| 223 |
cross_az_load_balancing: |
| 224 |
description: |
| 225 |
- Distribute load across all configured Availability Zones. |
| 226 |
- Defaults to V(false). |
| 227 |
type: bool |
| 228 |
stickiness: |
| 229 |
description: |
| 230 |
- A dictionary of stickiness policy settings. |
| 231 |
- Policy will be applied to all listeners (see examples). |
| 232 |
type: dict |
| 233 |
suboptions: |
| 234 |
type: |
| 235 |
description: |
| 236 |
- The type of stickiness policy to apply. |
| 237 |
- Required if O(stickiness.enabled=true). |
| 238 |
- Ignored if O(stickiness.enabled=false). |
| 239 |
required: false |
| 240 |
type: 'str' |
| 241 |
choices: ['application','loadbalancer'] |
| 242 |
enabled: |
| 243 |
description: |
| 244 |
- When O(stickiness.enabled=false) session stickiness will be disabled for all listeners. |
| 245 |
required: false |
| 246 |
type: bool |
| 247 |
default: true |
| 248 |
cookie: |
| 249 |
description: |
| 250 |
- The name of the application cookie used for stickiness. |
| 251 |
- Required if O(stickiness.enabled=true) and O(stickiness.type=application). |
| 252 |
- Ignored if O(stickiness.enabled=false). |
| 253 |
required: false |
| 254 |
type: str |
| 255 |
expiration: |
| 256 |
description: |
| 257 |
- The time period, in seconds, after which the cookie should be considered stale. |
| 258 |
- If this parameter is not specified, the stickiness session lasts for the duration of the browser session. |
| 259 |
- Ignored if O(stickiness.enabled=false). |
| 260 |
required: false |
| 261 |
type: int |
| 262 |
wait: |
| 263 |
description: |
| 264 |
- When creating, deleting, or adding instances to an ELB, if I(wait=true) |
| 265 |
Ansible will wait for both the load balancer and related network interfaces |
| 266 |
to finish creating/deleting. |
| 267 |
- Support for waiting when adding instances was added in release 2.1.0. |
| 268 |
type: bool |
| 269 |
default: false |
| 270 |
wait_timeout: |
| 271 |
description: |
| 272 |
- Used in conjunction with wait. Number of seconds to wait for the ELB to be terminated. |
| 273 |
- A maximum of 600 seconds (10 minutes) is allowed. |
| 274 |
type: int |
| 275 |
default: 180 |
| 276 |
|
| 277 |
notes: |
| 278 |
- The I(ec2_elb) fact previously set by this module was deprecated in release 2.1.0 and since release |
| 279 |
4.0.0 is no longer set. |
| 280 |
- Support for O(purge_tags) was added in release 2.1.0. |
| 281 |
|
| 282 |
extends_documentation_fragment: |
| 283 |
- amazon.aws.common.modules |
| 284 |
- amazon.aws.region.modules |
| 285 |
- amazon.aws.tags |
| 286 |
- amazon.aws.boto3 |
| 287 |
""" |
| 288 |
|
| 289 |
EXAMPLES = r""" |
| 290 |
# Note: None of these examples set aws_access_key, aws_secret_key, or region. |
| 291 |
# It is assumed that their matching environment variables are set. |
| 292 |
|
| 293 |
# Basic provisioning example (non-VPC) |
| 294 |
|
| 295 |
- amazon.aws.elb_classic_lb: |
| 296 |
name: "test-please-delete" |
| 297 |
state: present |
| 298 |
zones: |
| 299 |
- us-east-1a |
| 300 |
- us-east-1d |
| 301 |
listeners: |
| 302 |
- protocol: http # options are http, https, ssl, tcp |
| 303 |
load_balancer_port: 80 |
| 304 |
instance_port: 80 |
| 305 |
proxy_protocol: true |
| 306 |
- protocol: https |
| 307 |
load_balancer_port: 443 |
| 308 |
instance_protocol: http # optional, defaults to value of protocol setting |
| 309 |
instance_port: 80 |
| 310 |
# ssl certificate required for https or ssl |
| 311 |
ssl_certificate_id: "arn:aws:iam::123456789012:server-certificate/company/servercerts/ProdServerCert" |
| 312 |
|
| 313 |
# Internal ELB example |
| 314 |
|
| 315 |
- amazon.aws.elb_classic_lb: |
| 316 |
name: "test-vpc" |
| 317 |
scheme: internal |
| 318 |
state: present |
| 319 |
instance_ids: |
| 320 |
- i-abcd1234 |
| 321 |
purge_instance_ids: true |
| 322 |
subnets: |
| 323 |
- subnet-abcd1234 |
| 324 |
- subnet-1a2b3c4d |
| 325 |
listeners: |
| 326 |
- protocol: http # options are http, https, ssl, tcp |
| 327 |
load_balancer_port: 80 |
| 328 |
instance_port: 80 |
| 329 |
|
| 330 |
# Configure a health check and the access logs |
| 331 |
- amazon.aws.elb_classic_lb: |
| 332 |
name: "test-please-delete" |
| 333 |
state: present |
| 334 |
zones: |
| 335 |
- us-east-1d |
| 336 |
listeners: |
| 337 |
- protocol: http |
| 338 |
load_balancer_port: 80 |
| 339 |
instance_port: 80 |
| 340 |
health_check: |
| 341 |
ping_protocol: http # options are http, https, ssl, tcp |
| 342 |
ping_port: 80 |
| 343 |
ping_path: "/index.html" # not required for tcp or ssl |
| 344 |
response_timeout: 5 # seconds |
| 345 |
interval: 30 # seconds |
| 346 |
unhealthy_threshold: 2 |
| 347 |
healthy_threshold: 10 |
| 348 |
access_logs: |
| 349 |
interval: 5 # minutes (defaults to 60) |
| 350 |
s3_location: "my-bucket" # This value is required if access_logs is set |
| 351 |
s3_prefix: "logs" |
| 352 |
|
| 353 |
# Ensure ELB is gone |
| 354 |
- amazon.aws.elb_classic_lb: |
| 355 |
name: "test-please-delete" |
| 356 |
state: absent |
| 357 |
|
| 358 |
# Ensure ELB is gone and wait for check (for default timeout) |
| 359 |
- amazon.aws.elb_classic_lb: |
| 360 |
name: "test-please-delete" |
| 361 |
state: absent |
| 362 |
wait: true |
| 363 |
|
| 364 |
# Ensure ELB is gone and wait for check with timeout value |
| 365 |
- amazon.aws.elb_classic_lb: |
| 366 |
name: "test-please-delete" |
| 367 |
state: absent |
| 368 |
wait: true |
| 369 |
wait_timeout: 600 |
| 370 |
|
| 371 |
# Normally, this module will purge any listeners that exist on the ELB |
| 372 |
# but aren't specified in the listeners parameter. If purge_listeners is |
| 373 |
# false it leaves them alone |
| 374 |
- amazon.aws.elb_classic_lb: |
| 375 |
name: "test-please-delete" |
| 376 |
state: present |
| 377 |
zones: |
| 378 |
- us-east-1a |
| 379 |
- us-east-1d |
| 380 |
listeners: |
| 381 |
- protocol: http |
| 382 |
load_balancer_port: 80 |
| 383 |
instance_port: 80 |
| 384 |
purge_listeners: false |
| 385 |
|
| 386 |
# Normally, this module will leave availability zones that are enabled |
| 387 |
# on the ELB alone. If purge_zones is true, then any extraneous zones |
| 388 |
# will be removed |
| 389 |
- amazon.aws.elb_classic_lb: |
| 390 |
name: "test-please-delete" |
| 391 |
state: present |
| 392 |
zones: |
| 393 |
- us-east-1a |
| 394 |
- us-east-1d |
| 395 |
listeners: |
| 396 |
- protocol: http |
| 397 |
load_balancer_port: 80 |
| 398 |
instance_port: 80 |
| 399 |
purge_zones: true |
| 400 |
|
| 401 |
# Creates a ELB and assigns a list of subnets to it. |
| 402 |
- amazon.aws.elb_classic_lb: |
| 403 |
state: present |
| 404 |
name: 'New ELB' |
| 405 |
security_group_ids: 'sg-123456, sg-67890' |
| 406 |
subnets: 'subnet-123456,subnet-67890' |
| 407 |
purge_subnets: true |
| 408 |
listeners: |
| 409 |
- protocol: http |
| 410 |
load_balancer_port: 80 |
| 411 |
instance_port: 80 |
| 412 |
|
| 413 |
# Create an ELB with connection draining, increased idle timeout and cross availability |
| 414 |
# zone load balancing |
| 415 |
- amazon.aws.elb_classic_lb: |
| 416 |
name: "New ELB" |
| 417 |
state: present |
| 418 |
connection_draining_timeout: 60 |
| 419 |
idle_timeout: 300 |
| 420 |
cross_az_load_balancing: "yes" |
| 421 |
zones: |
| 422 |
- us-east-1a |
| 423 |
- us-east-1d |
| 424 |
listeners: |
| 425 |
- protocol: http |
| 426 |
load_balancer_port: 80 |
| 427 |
instance_port: 80 |
| 428 |
|
| 429 |
# Create an ELB with load balancer stickiness enabled |
| 430 |
- amazon.aws.elb_classic_lb: |
| 431 |
name: "New ELB" |
| 432 |
state: present |
| 433 |
zones: |
| 434 |
- us-east-1a |
| 435 |
- us-east-1d |
| 436 |
listeners: |
| 437 |
- protocol: http |
| 438 |
load_balancer_port: 80 |
| 439 |
instance_port: 80 |
| 440 |
stickiness: |
| 441 |
type: loadbalancer |
| 442 |
enabled: true |
| 443 |
expiration: 300 |
| 444 |
|
| 445 |
# Create an ELB with application stickiness enabled |
| 446 |
- amazon.aws.elb_classic_lb: |
| 447 |
name: "New ELB" |
| 448 |
state: present |
| 449 |
zones: |
| 450 |
- us-east-1a |
| 451 |
- us-east-1d |
| 452 |
listeners: |
| 453 |
- protocol: http |
| 454 |
load_balancer_port: 80 |
| 455 |
instance_port: 80 |
| 456 |
stickiness: |
| 457 |
type: application |
| 458 |
enabled: true |
| 459 |
cookie: SESSIONID |
| 460 |
|
| 461 |
# Create an ELB and add tags |
| 462 |
- amazon.aws.elb_classic_lb: |
| 463 |
name: "New ELB" |
| 464 |
state: present |
| 465 |
zones: |
| 466 |
- us-east-1a |
| 467 |
- us-east-1d |
| 468 |
listeners: |
| 469 |
- protocol: http |
| 470 |
load_balancer_port: 80 |
| 471 |
instance_port: 80 |
| 472 |
tags: |
| 473 |
Name: "New ELB" |
| 474 |
stack: "production" |
| 475 |
client: "Bob" |
| 476 |
|
| 477 |
# Delete all tags from an ELB |
| 478 |
- amazon.aws.elb_classic_lb: |
| 479 |
name: "New ELB" |
| 480 |
state: present |
| 481 |
zones: |
| 482 |
- us-east-1a |
| 483 |
- us-east-1d |
| 484 |
listeners: |
| 485 |
- protocol: http |
| 486 |
load_balancer_port: 80 |
| 487 |
instance_port: 80 |
| 488 |
tags: {} |
| 489 |
""" |
| 490 |
|
| 491 |
RETURN = r""" |
| 492 |
elb: |
| 493 |
description: Original boto-style Load Balancer attributes. |
| 494 |
returned: always |
| 495 |
type: dict |
| 496 |
contains: |
| 497 |
app_cookie_policy: |
| 498 |
description: The name of the policy used to control if the ELB is using a application cookie stickiness policy. |
| 499 |
type: str |
| 500 |
sample: "ec2-elb-lb-AppCookieStickinessPolicyType" |
| 501 |
returned: when O(state=present) |
| 502 |
backends: |
| 503 |
description: A description of the backend policy applied to the ELB (instance-port:policy-name). |
| 504 |
type: str |
| 505 |
sample: "8181:ProxyProtocol-policy" |
| 506 |
returned: when O(state=present) |
| 507 |
connection_draining_timeout: |
| 508 |
description: The maximum time, in seconds, to keep the existing connections open before deregistering the instances. |
| 509 |
type: int |
| 510 |
sample: 25 |
| 511 |
returned: when O(state=present) |
| 512 |
cross_az_load_balancing: |
| 513 |
description: Either V("yes") if cross-AZ load balancing is enabled, or V("no") if cross-AZ load balancing is disabled. |
| 514 |
type: str |
| 515 |
sample: "yes" |
| 516 |
returned: when O(state=present) |
| 517 |
dns_name: |
| 518 |
description: The DNS name of the ELB. |
| 519 |
type: str |
| 520 |
sample: "internal-ansible-test-935c585850ac-1516306744.us-east-1.elb.amazonaws.com" |
| 521 |
returned: when O(state=present) |
| 522 |
health_check: |
| 523 |
description: A dictionary describing the health check used for the ELB. |
| 524 |
type: dict |
| 525 |
returned: when O(state=present) |
| 526 |
contains: |
| 527 |
healthy_threshold: |
| 528 |
description: The number of consecutive successful health checks before marking an instance as healthy. |
| 529 |
type: int |
| 530 |
sample: 2 |
| 531 |
interval: |
| 532 |
description: The time, in seconds, between each health check. |
| 533 |
type: int |
| 534 |
sample: 10 |
| 535 |
target: |
| 536 |
description: The Protocol, Port, and for HTTP(S) health checks the path tested by the health check. |
| 537 |
type: str |
| 538 |
sample: "TCP:22" |
| 539 |
timeout: |
| 540 |
description: The time, in seconds, after which an in progress health check is considered failed due to a timeout. |
| 541 |
type: int |
| 542 |
sample: 5 |
| 543 |
unhealthy_threshold: |
| 544 |
description: The number of consecutive failed health checks before marking an instance as unhealthy. |
| 545 |
type: int |
| 546 |
sample: 2 |
| 547 |
hosted_zone_id: |
| 548 |
description: The ID of the Amazon Route 53 hosted zone for the load balancer. |
| 549 |
type: str |
| 550 |
sample: "Z35SXDOTRQ7X7K" |
| 551 |
returned: when O(state=present) |
| 552 |
hosted_zone_name: |
| 553 |
description: The DNS name of the load balancer when using a custom hostname. |
| 554 |
type: str |
| 555 |
sample: "ansible-module.example" |
| 556 |
returned: when O(state=present) |
| 557 |
idle_timeout: |
| 558 |
description: The length of of time before an idle connection is dropped by the ELB. |
| 559 |
type: int |
| 560 |
sample: 50 |
| 561 |
returned: when O(state=present) |
| 562 |
in_service_count: |
| 563 |
description: The number of instances attached to the ELB in an in-service state. |
| 564 |
type: int |
| 565 |
sample: 1 |
| 566 |
returned: when O(state=present) |
| 567 |
instance_health: |
| 568 |
description: A list of dictionaries describing the health of each instance attached to the ELB. |
| 569 |
type: list |
| 570 |
elements: dict |
| 571 |
returned: when O(state=present) |
| 572 |
contains: |
| 573 |
description: |
| 574 |
description: A human readable description of why the instance is not in service. |
| 575 |
type: str |
| 576 |
sample: N/A |
| 577 |
returned: when O(state=present) |
| 578 |
instance_id: |
| 579 |
description: The ID of the instance. |
| 580 |
type: str |
| 581 |
sample: "i-03dcc8953a03d6435" |
| 582 |
returned: when O(state=present) |
| 583 |
reason_code: |
| 584 |
description: A code describing why the instance is not in service. |
| 585 |
type: str |
| 586 |
sample: N/A |
| 587 |
returned: when O(state=present) |
| 588 |
state: |
| 589 |
description: The current service state of the instance. |
| 590 |
type: str |
| 591 |
sample: InService |
| 592 |
returned: when O(state=present) |
| 593 |
instances: |
| 594 |
description: A list of the IDs of instances attached to the ELB. |
| 595 |
type: list |
| 596 |
elements: str |
| 597 |
sample: ["i-03dcc8953a03d6435"] |
| 598 |
returned: when O(state=present) |
| 599 |
lb_cookie_policy: |
| 600 |
description: The name of the policy used to control if the ELB is using a cookie stickiness policy. |
| 601 |
type: str |
| 602 |
sample: "ec2-elb-lb-LBCookieStickinessPolicyType" |
| 603 |
returned: when O(state=present) |
| 604 |
listeners: |
| 605 |
description: |
| 606 |
- A list of lists describing the listeners attached to the ELB. |
| 607 |
- The nested list contains the listener port, the instance port, the listener protoco, the instance port, |
| 608 |
and where appropriate the ID of the SSL certificate for the port. |
| 609 |
type: list |
| 610 |
elements: list |
| 611 |
sample: [[22, 22, 'TCP', 'TCP'], [80, 8181, 'HTTP', 'HTTP']] |
| 612 |
returned: when O(state=present) |
| 613 |
name: |
| 614 |
description: The name of the ELB. This name is unique per-region, per-account. |
| 615 |
type: str |
| 616 |
sample: "ansible-test-935c585850ac" |
| 617 |
returned: when O(state=present) |
| 618 |
out_of_service_count: |
| 619 |
description: The number of instances attached to the ELB in an out-of-service state. |
| 620 |
type: int |
| 621 |
sample: 0 |
| 622 |
returned: when O(state=present) |
| 623 |
proxy_policy: |
| 624 |
description: The name of the policy used to control if the ELB operates using the Proxy protocol. |
| 625 |
type: str |
| 626 |
sample: "ProxyProtocol-policy" |
| 627 |
returned: when the proxy protocol policy exists. |
| 628 |
region: |
| 629 |
description: The AWS region in which the ELB is running. |
| 630 |
type: str |
| 631 |
sample: "us-east-1" |
| 632 |
returned: always |
| 633 |
scheme: |
| 634 |
description: Whether the ELB is an C('internal') or a C('internet-facing') load balancer. |
| 635 |
type: str |
| 636 |
sample: "internal" |
| 637 |
returned: when O(state=present) |
| 638 |
security_group_ids: |
| 639 |
description: A list of the IDs of the Security Groups attached to the ELB. |
| 640 |
type: list |
| 641 |
elements: str |
| 642 |
sample: ["sg-0c12ebd82f2fb97dc", "sg-01ec7378d0c7342e6"] |
| 643 |
returned: when O(state=present) |
| 644 |
status: |
| 645 |
description: A minimal description of the current state of the ELB. Valid values are C('exists'), C('gone'), C('deleted'), C('created'). |
| 646 |
type: str |
| 647 |
sample: exists |
| 648 |
returned: always |
| 649 |
subnets: |
| 650 |
description: A list of the subnet IDs attached to the ELB. |
| 651 |
type: list |
| 652 |
elements: str |
| 653 |
sample: ["subnet-00d9d0f70c7e5f63c", "subnet-03fa5253586b2d2d5"] |
| 654 |
returned: when O(state=present) |
| 655 |
tags: |
| 656 |
description: A dictionary describing the tags attached to the ELB. |
| 657 |
type: dict |
| 658 |
sample: {"Name": "ansible-test-935c585850ac", "ExampleTag": "Example Value"} |
| 659 |
returned: when O(state=present) |
| 660 |
unknown_instance_state_count: |
| 661 |
description: The number of instances attached to the ELB in an unknown state. |
| 662 |
type: int |
| 663 |
sample: 0 |
| 664 |
returned: when O(state=present) |
| 665 |
zones: |
| 666 |
description: A list of the AWS regions in which the ELB is running. |
| 667 |
type: list |
| 668 |
elements: str |
| 669 |
sample: ["us-east-1b", "us-east-1a"] |
| 670 |
returned: when O(state=present) |
| 671 |
load_balancer: |
| 672 |
description: Boto3-style Load Balancer attributes. |
| 673 |
returned: always |
| 674 |
type: dict |
| 675 |
contains: |
| 676 |
availability_zone: |
| 677 |
description: A list of the AWS regions in which the ELB is running. |
| 678 |
type: list |
| 679 |
elements: str |
| 680 |
sample: ["us-east-1b", "us-east-1a"] |
| 681 |
returned: when O(state=present) |
| 682 |
backend_server_descriptions: |
| 683 |
description: Information about your EC2 instances. |
| 684 |
returned: when O(state=present) |
| 685 |
type: list |
| 686 |
elements: dict |
| 687 |
sample: [] |
| 688 |
contains: |
| 689 |
instance_port: |
| 690 |
description: The port on which the EC2 instance is listening. |
| 691 |
returned: when O(state=present) |
| 692 |
type: int |
| 693 |
policy_names: |
| 694 |
description: The names of the policies enabled for the EC2 instance. |
| 695 |
returned: when O(state=present) |
| 696 |
type: list |
| 697 |
elements: str |
| 698 |
canonical_hosted_zone_id: |
| 699 |
description: The ID of the Amazon Route 53 hosted zone for the load balancer. |
| 700 |
type: str |
| 701 |
sample: "Z35SXDOTRQ7X7K" |
| 702 |
returned: when O(state=present) |
| 703 |
created_time: |
| 704 |
description: The date and time the load balancer was created. |
| 705 |
type: str |
| 706 |
sample: "2024-06-27T10:18:48.390000+00:00" |
| 707 |
returned: when O(state=present) |
| 708 |
dns_name: |
| 709 |
description: The DNS name of the ELB. |
| 710 |
type: str |
| 711 |
sample: "internal-ansible-test-935c585850ac-1516306744.us-east-1.elb.amazonaws.com" |
| 712 |
returned: when O(state=present) |
| 713 |
health_check: |
| 714 |
description: Information about the health checks conducted on the load balancer. |
| 715 |
type: dict |
| 716 |
returned: when O(state=present) |
| 717 |
contains: |
| 718 |
healthy_threshold: |
| 719 |
description: The number of consecutive successful health checks before marking an instance as healthy. |
| 720 |
type: int |
| 721 |
sample: 2 |
| 722 |
interval: |
| 723 |
description: The time, in seconds, between each health check. |
| 724 |
type: int |
| 725 |
sample: 10 |
| 726 |
target: |
| 727 |
description: The Protocol, Port, and for HTTP(S) health checks the path tested by the health check. |
| 728 |
type: str |
| 729 |
sample: "TCP:22" |
| 730 |
timeout: |
| 731 |
description: The time, in seconds, after which an in progress health check is considered failed due to a timeout. |
| 732 |
type: int |
| 733 |
sample: 5 |
| 734 |
unhealthy_threshold: |
| 735 |
description: The number of consecutive failed health checks before marking an instance as unhealthy. |
| 736 |
type: int |
| 737 |
sample: 2 |
| 738 |
instances: |
| 739 |
description: The IDs of the instances for the load balancer. |
| 740 |
type: list |
| 741 |
elements: dict |
| 742 |
returned: when O(state=present) |
| 743 |
contains: |
| 744 |
instance_id: |
| 745 |
description: The instance ID. |
| 746 |
type: str |
| 747 |
sample: [] |
| 748 |
listener_descriptions: |
| 749 |
description: The listeners for the load balancer. |
| 750 |
returned: when O(state=present) |
| 751 |
type: list |
| 752 |
elements: dict |
| 753 |
contains: |
| 754 |
listener: |
| 755 |
description: The listener. |
| 756 |
returned: when O(state=present) |
| 757 |
type: dict |
| 758 |
contains: |
| 759 |
protocol: |
| 760 |
description: 'The load balancer transport protocol to use for routing: HTTP, HTTPS, TCP, or SSL.' |
| 761 |
returned: when O(state=present) |
| 762 |
type: str |
| 763 |
load_balancer_port: |
| 764 |
description: The port on which the load balancer is listening. |
| 765 |
returned: when O(state=present) |
| 766 |
type: int |
| 767 |
instance_protocol: |
| 768 |
description: The protocol to use for routing traffic to instances. |
| 769 |
returned: when O(state=present) |
| 770 |
type: str |
| 771 |
instance_port: |
| 772 |
description: The port on which the instance is listening. |
| 773 |
returned: when O(state=present) |
| 774 |
type: int |
| 775 |
policy_names: |
| 776 |
description: The policies. If there are no policies enabled, the list is empty. |
| 777 |
returned: when O(state=present) |
| 778 |
type: list |
| 779 |
elements: str |
| 780 |
sample: [ |
| 781 |
{ |
| 782 |
"listener": { |
| 783 |
"instance_port": 8080, |
| 784 |
"instance_protocol": "HTTP", |
| 785 |
"load_balancer_port": 8080, |
| 786 |
"protocol": "HTTP" |
| 787 |
}, |
| 788 |
"policy_names": [] |
| 789 |
} |
| 790 |
] |
| 791 |
load_balancer_attributes: |
| 792 |
description: The listeners for the load balancer. |
| 793 |
returned: when O(state=present) |
| 794 |
type: list |
| 795 |
elements: dict |
| 796 |
contains: |
| 797 |
access_log: |
| 798 |
description: |
| 799 |
- If enabled, the load balancer captures detailed information of all requests and delivers the information to the |
| 800 |
Amazon S3 bucket that you specify. |
| 801 |
returned: when O(state=present) |
| 802 |
type: dict |
| 803 |
contains: |
| 804 |
enabled: |
| 805 |
description: Specifies whether access logs are enabled for the load balancer. |
| 806 |
type: bool |
| 807 |
sample: false |
| 808 |
s3_bucket_name: |
| 809 |
description: The name of the Amazon S3 bucket where the access logs are stored. |
| 810 |
type: str |
| 811 |
sample: "" |
| 812 |
emit_interval: |
| 813 |
description: The interval for publishing the access logs. |
| 814 |
type: int |
| 815 |
sample: 60 |
| 816 |
s3_bucket_prefix: |
| 817 |
description: The logical hierarchy you created for your Amazon S3 bucket. |
| 818 |
type: str |
| 819 |
sample: "" |
| 820 |
addtional_attributes: |
| 821 |
description: Any additional attributes. |
| 822 |
returned: when O(state=present) |
| 823 |
type: list |
| 824 |
elements: dict |
| 825 |
sample: [ |
| 826 |
{ |
| 827 |
"key": "elb.http.desyncmitigationmode", |
| 828 |
"value": "defensive" |
| 829 |
} |
| 830 |
] |
| 831 |
connection_draining: |
| 832 |
description: |
| 833 |
- If enabled, the load balancer allows existing requests to complete before the load balancer shifts traffic away |
| 834 |
from a deregistered or unhealthy instance. |
| 835 |
returned: when O(state=present) |
| 836 |
type: dict |
| 837 |
contains: |
| 838 |
enabled: |
| 839 |
description: Specifies whether connection draining is enabled for the load balancer. |
| 840 |
type: bool |
| 841 |
timeout: |
| 842 |
description: The maximum time, in seconds, to keep the existing connections open before deregistering the instances. |
| 843 |
type: int |
| 844 |
sample: { |
| 845 |
"enabled": false, |
| 846 |
"timeout": 300 |
| 847 |
} |
| 848 |
connection_settings: |
| 849 |
description: |
| 850 |
- If enabled, the load balancer allows the connections to remain idle (no data is sent over the connection) for the |
| 851 |
specified duration |
| 852 |
returned: when O(state=present) |
| 853 |
type: dict |
| 854 |
contains: |
| 855 |
idle_timeout: |
| 856 |
description: |
| 857 |
- The time, in seconds, that the connection is allowed to be idle (no data has been sent over the connection) |
| 858 |
before it is closed by the load balancer. |
| 859 |
type: int |
| 860 |
sample: { |
| 861 |
"idle_timeout": 60 |
| 862 |
} |
| 863 |
cross_zone_load_balancing: |
| 864 |
description: If enabled, the load balancer routes the request traffic evenly across all instances regardless of the Availability Zones. |
| 865 |
returned: when O(state=present) |
| 866 |
type: dict |
| 867 |
contains: |
| 868 |
enabled: |
| 869 |
description: Specifies whether cross-zone load balancing is enabled for the load balancer. |
| 870 |
returned: when O(state=present) |
| 871 |
type: bool |
| 872 |
sample: { |
| 873 |
"enabled": false |
| 874 |
} |
| 875 |
load_balancer_name: |
| 876 |
description: The name of the ELB. |
| 877 |
type: str |
| 878 |
sample: "ansible-test-935c585850ac" |
| 879 |
returned: when O(state=present) |
| 880 |
load_balancer_policies: |
| 881 |
description: Information about the policies. |
| 882 |
type: list |
| 883 |
sample: [] |
| 884 |
elements: dict |
| 885 |
returned: when O(state=present) |
| 886 |
contains: |
| 887 |
policy_name: |
| 888 |
description: The name of the policy. |
| 889 |
returned: when O(state=present) |
| 890 |
type: str |
| 891 |
policy_type_name: |
| 892 |
description: The name of the policy type. |
| 893 |
returned: when O(state=present) |
| 894 |
type: str |
| 895 |
policy_attributes_description: |
| 896 |
description: Information about a policy attribute. |
| 897 |
returned: when O(state=present) |
| 898 |
type: dict |
| 899 |
contains: |
| 900 |
attribute_name: |
| 901 |
description: The name of the attribute. |
| 902 |
returned: when O(state=present) |
| 903 |
type: str |
| 904 |
attribute_value: |
| 905 |
description: The value of the attribute. |
| 906 |
returned: when O(state=present) |
| 907 |
type: str |
| 908 |
policies: |
| 909 |
description: The policies defined for the load balancer. |
| 910 |
returned: when O(state=present) |
| 911 |
type: dict |
| 912 |
contains: |
| 913 |
app_cookie_stickiness_policies: |
| 914 |
description: The stickiness policies created using CreateAppCookieStickinessPolicy. |
| 915 |
returned: when O(state=present) |
| 916 |
type: list |
| 917 |
elements: dict |
| 918 |
contains: |
| 919 |
policy_name: |
| 920 |
description: The mnemonic name for the policy being created. |
| 921 |
returned: when O(state=present) |
| 922 |
type: str |
| 923 |
sample: "" |
| 924 |
cookie_name: |
| 925 |
description: The name of the application cookie used for stickiness. |
| 926 |
returned: when O(state=present) |
| 927 |
type: str |
| 928 |
sample: "" |
| 929 |
lb_cookie_stickiness_policies : |
| 930 |
description: The stickiness policies created using CreateLBCookieStickinessPolicy. |
| 931 |
returned: when O(state=present) |
| 932 |
type: list |
| 933 |
elements: dict |
| 934 |
contains: |
| 935 |
policy_name: |
| 936 |
description: The mnemonic name for the policy being created. |
| 937 |
returned: when O(state=present) |
| 938 |
type: str |
| 939 |
sample: "" |
| 940 |
cookie_expiration_period: |
| 941 |
description: The time period, in seconds, after which the cookie should be considered stale. |
| 942 |
returned: when O(state=present) |
| 943 |
type: str |
| 944 |
sample: "" |
| 945 |
other_policies : |
| 946 |
description: The policies other than the stickiness policies. |
| 947 |
returned: when O(state=present) |
| 948 |
type: list |
| 949 |
elements: str |
| 950 |
sample: [] |
| 951 |
scheme: |
| 952 |
description: The type of load balancer. |
| 953 |
type: str |
| 954 |
sample: "internal" |
| 955 |
returned: when O(state=present) |
| 956 |
security_groups: |
| 957 |
description: The security groups for the load balancer. |
| 958 |
type: list |
| 959 |
elements: str |
| 960 |
sample: ["sg-0c12ebd82f2fb97dc", "sg-01ec7378d0c7342e6"] |
| 961 |
returned: when O(state=present) |
| 962 |
source_security_groups: |
| 963 |
description: The security group for the load balancer, which you can use as part of your inbound rules for your registered instances. |
| 964 |
type: dict |
| 965 |
returned: when O(state=present) |
| 966 |
contains: |
| 967 |
owner_alias: |
| 968 |
description: The owner of the security group. |
| 969 |
type: str |
| 970 |
group_name: |
| 971 |
description: The name of the security group.. |
| 972 |
type: str |
| 973 |
sample: { |
| 974 |
"group_name": "default", |
| 975 |
"owner_alias": "721066863947" |
| 976 |
} |
| 977 |
subnets: |
| 978 |
description: A list of the subnet IDs attached to the ELB. |
| 979 |
type: list |
| 980 |
elements: str |
| 981 |
sample: ["subnet-00d9d0f70c7e5f63c", "subnet-03fa5253586b2d2d5"] |
| 982 |
returned: when O(state=present) |
| 983 |
tags: |
| 984 |
description: A dictionary describing the tags attached to the ELB. |
| 985 |
type: dict |
| 986 |
sample: {"Name": "ansible-test-935c585850ac", "ExampleTag": "Example Value"} |
| 987 |
returned: when O(state=present) |
| 988 |
vpc_id: |
| 989 |
description: The ID of the VPC for the load balancer. |
| 990 |
type: str |
| 991 |
sample: "vpc-0c112c24b41d89c34" |
| 992 |
returned: when O(state=present) |
| 993 |
""" |
| 994 |
|
| 995 |
try: |
| 996 |
import botocore |
| 997 |
except ImportError: |
| 998 |
pass # Taken care of by AnsibleAWSModule |
| 999 |
|
| 1000 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 1001 |
from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict |
| 1002 |
|
| 1003 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code |
| 1004 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import get_ec2_security_group_ids_from_names |
| 1005 |
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule |
| 1006 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 1007 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list |
| 1008 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict |
| 1009 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags |
| 1010 |
from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list |
| 1011 |
from ansible_collections.amazon.aws.plugins.module_utils.transformation import scrub_none_parameters |
| 1012 |
from ansible_collections.amazon.aws.plugins.module_utils.waiters import get_waiter |
| 1013 |
|
| 1014 |
|
| 1015 |
class ElbManager: |
| 1016 |
"""Handles ELB creation and destruction""" |
| 1017 |
|
| 1018 |
def __init__(self, module): |
| 1019 |
self.module = module |
| 1020 |
|
| 1021 |
self.name = module.params["name"] |
| 1022 |
self.listeners = module.params["listeners"] |
| 1023 |
self.purge_listeners = module.params["purge_listeners"] |
| 1024 |
self.instance_ids = module.params["instance_ids"] |
| 1025 |
self.purge_instance_ids = module.params["purge_instance_ids"] |
| 1026 |
self.zones = module.params["zones"] |
| 1027 |
self.purge_zones = module.params["purge_zones"] |
| 1028 |
self.health_check = module.params["health_check"] |
| 1029 |
self.access_logs = module.params["access_logs"] |
| 1030 |
self.subnets = module.params["subnets"] |
| 1031 |
self.purge_subnets = module.params["purge_subnets"] |
| 1032 |
self.scheme = module.params["scheme"] |
| 1033 |
self.connection_draining_timeout = module.params["connection_draining_timeout"] |
| 1034 |
self.idle_timeout = module.params["idle_timeout"] |
| 1035 |
self.cross_az_load_balancing = module.params["cross_az_load_balancing"] |
| 1036 |
self.stickiness = module.params["stickiness"] |
| 1037 |
self.wait = module.params["wait"] |
| 1038 |
self.wait_timeout = module.params["wait_timeout"] |
| 1039 |
self.tags = module.params["tags"] |
| 1040 |
self.purge_tags = module.params["purge_tags"] |
| 1041 |
|
| 1042 |
self.changed = False |
| 1043 |
self.status = "gone" |
| 1044 |
|
| 1045 |
retry_decorator = AWSRetry.jittered_backoff() |
| 1046 |
self.client = self.module.client("elb", retry_decorator=retry_decorator) |
| 1047 |
self.ec2_client = self.module.client("ec2", retry_decorator=retry_decorator) |
| 1048 |
|
| 1049 |
security_group_names = module.params["security_group_names"] |
| 1050 |
self.security_group_ids = module.params["security_group_ids"] |
| 1051 |
|
| 1052 |
self._update_descriptions() |
| 1053 |
|
| 1054 |
if security_group_names: |
| 1055 |
# Use the subnets attached to the VPC to find which VPC we're in and |
| 1056 |
# limit the search |
| 1057 |
if self.elb and self.elb.get("Subnets", None): |
| 1058 |
subnets = set(self.elb.get("Subnets") + list(self.subnets or [])) |
| 1059 |
else: |
| 1060 |
subnets = set(self.subnets) |
| 1061 |
if subnets: |
| 1062 |
vpc_id = self._get_vpc_from_subnets(subnets) |
| 1063 |
else: |
| 1064 |
vpc_id = None |
| 1065 |
try: |
| 1066 |
self.security_group_ids = self._get_ec2_security_group_ids_from_names( |
| 1067 |
sec_group_list=security_group_names, vpc_id=vpc_id |
| 1068 |
) |
| 1069 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1070 |
module.fail_json_aws( |
| 1071 |
e, |
| 1072 |
msg="Failed to convert security group names to IDs, try using security group IDs rather than names", |
| 1073 |
) |
| 1074 |
|
| 1075 |
def _update_descriptions(self): |
| 1076 |
try: |
| 1077 |
self.elb = self._get_elb() |
| 1078 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1079 |
self.module.fail_json_aws(e, msg="Unable to describe load balancer") |
| 1080 |
try: |
| 1081 |
self.elb_attributes = self._get_elb_attributes() |
| 1082 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1083 |
self.module.fail_json_aws(e, msg="Unable to describe load balancer attributes") |
| 1084 |
try: |
| 1085 |
self.elb_policies = self._get_elb_policies() |
| 1086 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1087 |
self.module.fail_json_aws(e, msg="Unable to describe load balancer policies") |
| 1088 |
try: |
| 1089 |
self.elb_health = self._get_elb_instance_health() |
| 1090 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1091 |
self.module.fail_json_aws(e, msg="Unable to describe load balancer instance health") |
| 1092 |
|
| 1093 |
# We have a number of complex parameters which can't be validated by |
| 1094 |
# AnsibleModule or are only required if the ELB doesn't exist. |
| 1095 |
def validate_params(self, state=None): |
| 1096 |
problem_found = False |
| 1097 |
# Validate that protocol is one of the permitted values |
| 1098 |
problem_found |= self._validate_listeners(self.listeners) |
| 1099 |
problem_found |= self._validate_health_check(self.health_check) |
| 1100 |
problem_found |= self._validate_stickiness(self.stickiness) |
| 1101 |
if state == "present": |
| 1102 |
# When creating a new ELB |
| 1103 |
problem_found |= self._validate_creation_requirements() |
| 1104 |
problem_found |= self._validate_access_logs(self.access_logs) |
| 1105 |
|
| 1106 |
# Pass check_mode down through to the module |
| 1107 |
@property |
| 1108 |
def check_mode(self): |
| 1109 |
return self.module.check_mode |
| 1110 |
|
| 1111 |
def _get_elb_policies(self): |
| 1112 |
try: |
| 1113 |
attributes = self.client.describe_load_balancer_policies(LoadBalancerName=self.name) |
| 1114 |
except is_boto3_error_code(["LoadBalancerNotFound", "LoadBalancerAttributeNotFoundException"]): |
| 1115 |
return {} |
| 1116 |
except is_boto3_error_code("AccessDenied"): # pylint: disable=duplicate-except |
| 1117 |
# Be forgiving if we can't see the attributes |
| 1118 |
# Note: This will break idempotency if someone has set but not describe |
| 1119 |
self.module.warn("Access Denied trying to describe load balancer policies") |
| 1120 |
return {} |
| 1121 |
return attributes["PolicyDescriptions"] |
| 1122 |
|
| 1123 |
def _get_elb_instance_health(self): |
| 1124 |
try: |
| 1125 |
instance_health = self.client.describe_instance_health(LoadBalancerName=self.name) |
| 1126 |
except is_boto3_error_code(["LoadBalancerNotFound", "LoadBalancerAttributeNotFoundException"]): |
| 1127 |
return [] |
| 1128 |
except is_boto3_error_code("AccessDenied"): # pylint: disable=duplicate-except |
| 1129 |
# Be forgiving if we can't see the attributes |
| 1130 |
# Note: This will break idempotency if someone has set but not describe |
| 1131 |
self.module.warn("Access Denied trying to describe instance health") |
| 1132 |
return [] |
| 1133 |
return instance_health["InstanceStates"] |
| 1134 |
|
| 1135 |
def _get_elb_attributes(self): |
| 1136 |
try: |
| 1137 |
attributes = self.client.describe_load_balancer_attributes(LoadBalancerName=self.name) |
| 1138 |
except is_boto3_error_code(["LoadBalancerNotFound", "LoadBalancerAttributeNotFoundException"]): |
| 1139 |
return {} |
| 1140 |
except is_boto3_error_code("AccessDenied"): # pylint: disable=duplicate-except |
| 1141 |
# Be forgiving if we can't see the attributes |
| 1142 |
# Note: This will break idempotency if someone has set but not describe |
| 1143 |
self.module.warn("Access Denied trying to describe load balancer attributes") |
| 1144 |
return {} |
| 1145 |
return attributes["LoadBalancerAttributes"] |
| 1146 |
|
| 1147 |
def _get_elb(self): |
| 1148 |
try: |
| 1149 |
elbs = self._describe_loadbalancer(self.name) |
| 1150 |
except is_boto3_error_code("LoadBalancerNotFound"): |
| 1151 |
return None |
| 1152 |
|
| 1153 |
# Shouldn't happen, but Amazon could change the rules on us... |
| 1154 |
if len(elbs) > 1: |
| 1155 |
self.module.fail_json(f"Found multiple ELBs with name {self.name}") |
| 1156 |
|
| 1157 |
self.status = "exists" if self.status == "gone" else self.status |
| 1158 |
|
| 1159 |
return elbs[0] |
| 1160 |
|
| 1161 |
def _delete_elb(self): |
| 1162 |
# True if succeeds, exception raised if not |
| 1163 |
try: |
| 1164 |
if not self.check_mode: |
| 1165 |
self.client.delete_load_balancer(aws_retry=True, LoadBalancerName=self.name) |
| 1166 |
self.changed = True |
| 1167 |
self.status = "deleted" |
| 1168 |
except is_boto3_error_code("LoadBalancerNotFound"): |
| 1169 |
return False |
| 1170 |
return True |
| 1171 |
|
| 1172 |
def _create_elb(self): |
| 1173 |
listeners = list(self._format_listener(listener) for listener in self.listeners) |
| 1174 |
if not self.scheme: |
| 1175 |
self.scheme = "internet-facing" |
| 1176 |
params = dict( |
| 1177 |
LoadBalancerName=self.name, |
| 1178 |
AvailabilityZones=self.zones, |
| 1179 |
SecurityGroups=self.security_group_ids, |
| 1180 |
Subnets=self.subnets, |
| 1181 |
Listeners=listeners, |
| 1182 |
Scheme=self.scheme, |
| 1183 |
) |
| 1184 |
params = scrub_none_parameters(params) |
| 1185 |
if self.tags: |
| 1186 |
params["Tags"] = ansible_dict_to_boto3_tag_list(self.tags) |
| 1187 |
|
| 1188 |
if not self.check_mode: |
| 1189 |
self.client.create_load_balancer(aws_retry=True, **params) |
| 1190 |
# create_load_balancer only returns the DNS name |
| 1191 |
self.elb = self._get_elb() |
| 1192 |
self.changed = True |
| 1193 |
self.status = "created" |
| 1194 |
return True |
| 1195 |
|
| 1196 |
def _format_listener(self, listener, inject_protocol=False): |
| 1197 |
"""Formats listener into the format needed by the |
| 1198 |
ELB API""" |
| 1199 |
|
| 1200 |
listener = scrub_none_parameters(listener) |
| 1201 |
|
| 1202 |
for protocol in ["protocol", "instance_protocol"]: |
| 1203 |
if protocol in listener: |
| 1204 |
listener[protocol] = listener[protocol].upper() |
| 1205 |
|
| 1206 |
if inject_protocol and "instance_protocol" not in listener: |
| 1207 |
listener["instance_protocol"] = listener["protocol"] |
| 1208 |
|
| 1209 |
# Remove proxy_protocol, it has to be handled as a policy |
| 1210 |
listener.pop("proxy_protocol", None) |
| 1211 |
|
| 1212 |
ssl_id = listener.pop("ssl_certificate_id", None) |
| 1213 |
|
| 1214 |
formatted_listener = snake_dict_to_camel_dict(listener, True) |
| 1215 |
if ssl_id: |
| 1216 |
formatted_listener["SSLCertificateId"] = ssl_id |
| 1217 |
|
| 1218 |
return formatted_listener |
| 1219 |
|
| 1220 |
def _format_healthcheck_target(self): |
| 1221 |
"""Compose target string from healthcheck parameters""" |
| 1222 |
protocol = self.health_check["ping_protocol"].upper() |
| 1223 |
path = "" |
| 1224 |
|
| 1225 |
if protocol in ["HTTP", "HTTPS"] and "ping_path" in self.health_check: |
| 1226 |
path = self.health_check["ping_path"] |
| 1227 |
|
| 1228 |
return f"{protocol}:{self.health_check['ping_port']}{path}" |
| 1229 |
|
| 1230 |
def _format_healthcheck(self): |
| 1231 |
return dict( |
| 1232 |
Target=self._format_healthcheck_target(), |
| 1233 |
Timeout=self.health_check["timeout"], |
| 1234 |
Interval=self.health_check["interval"], |
| 1235 |
UnhealthyThreshold=self.health_check["unhealthy_threshold"], |
| 1236 |
HealthyThreshold=self.health_check["healthy_threshold"], |
| 1237 |
) |
| 1238 |
|
| 1239 |
def ensure_ok(self): |
| 1240 |
"""Create the ELB""" |
| 1241 |
if not self.elb: |
| 1242 |
try: |
| 1243 |
self._create_elb() |
| 1244 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1245 |
self.module.fail_json_aws(e, msg="Failed to create load balancer") |
| 1246 |
try: |
| 1247 |
self.elb_attributes = self._get_elb_attributes() |
| 1248 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1249 |
self.module.fail_json_aws(e, msg="Unable to describe load balancer attributes") |
| 1250 |
self._wait_created() |
| 1251 |
|
| 1252 |
# Some attributes are configured on creation, others need to be updated |
| 1253 |
# after creation. Skip updates for those set on creation |
| 1254 |
else: |
| 1255 |
if self._check_scheme(): |
| 1256 |
# XXX We should probably set 'None' parameters based on the |
| 1257 |
# current state prior to deletion |
| 1258 |
|
| 1259 |
# the only way to change the scheme is by recreating the resource |
| 1260 |
self.ensure_gone() |
| 1261 |
# We need to wait for it to be gone-gone |
| 1262 |
self._wait_gone(True) |
| 1263 |
try: |
| 1264 |
self._create_elb() |
| 1265 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1266 |
self.module.fail_json_aws(e, msg="Failed to recreate load balancer") |
| 1267 |
try: |
| 1268 |
self.elb_attributes = self._get_elb_attributes() |
| 1269 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1270 |
self.module.fail_json_aws(e, msg="Unable to describe load balancer attributes") |
| 1271 |
else: |
| 1272 |
self._set_subnets() |
| 1273 |
self._set_zones() |
| 1274 |
self._set_security_groups() |
| 1275 |
self._set_elb_listeners() |
| 1276 |
self._set_tags() |
| 1277 |
|
| 1278 |
self._set_health_check() |
| 1279 |
self._set_elb_attributes() |
| 1280 |
self._set_backend_policies() |
| 1281 |
self._set_stickiness_policies() |
| 1282 |
self._set_instance_ids() |
| 1283 |
|
| 1284 |
# if self._check_attribute_support('access_log'): |
| 1285 |
# self._set_access_log() |
| 1286 |
|
| 1287 |
def ensure_gone(self): |
| 1288 |
"""Destroy the ELB""" |
| 1289 |
if self.elb: |
| 1290 |
try: |
| 1291 |
self._delete_elb() |
| 1292 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1293 |
self.module.fail_json_aws(e, msg="Failed to delete load balancer") |
| 1294 |
self._wait_gone() |
| 1295 |
|
| 1296 |
def _wait_gone(self, wait=None): |
| 1297 |
if not wait and not self.wait: |
| 1298 |
return |
| 1299 |
try: |
| 1300 |
self._wait_for_elb_removed() |
| 1301 |
# Unfortunately even though the ELB itself is removed quickly |
| 1302 |
# the interfaces take longer so reliant security groups cannot |
| 1303 |
# be deleted until the interface has registered as removed. |
| 1304 |
self._wait_for_elb_interface_removed() |
| 1305 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1306 |
self.module.fail_json_aws(e, msg="Failed while waiting for load balancer deletion") |
| 1307 |
|
| 1308 |
def _wait_created(self, wait=False): |
| 1309 |
if not wait and not self.wait: |
| 1310 |
return |
| 1311 |
try: |
| 1312 |
self._wait_for_elb_created() |
| 1313 |
# Can take longer than creation |
| 1314 |
self._wait_for_elb_interface_created() |
| 1315 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1316 |
self.module.fail_json_aws(e, msg="Failed while waiting for load balancer deletion") |
| 1317 |
|
| 1318 |
def get_load_balancer(self): |
| 1319 |
self._update_descriptions() |
| 1320 |
elb = dict(self.elb or {}) |
| 1321 |
if not elb: |
| 1322 |
return {} |
| 1323 |
|
| 1324 |
elb["LoadBalancerAttributes"] = self.elb_attributes |
| 1325 |
elb["LoadBalancerPolicies"] = self.elb_policies |
| 1326 |
load_balancer = camel_dict_to_snake_dict(elb) |
| 1327 |
try: |
| 1328 |
load_balancer["tags"] = self._get_tags() |
| 1329 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1330 |
self.module.fail_json_aws(e, msg="Failed to get load balancer tags") |
| 1331 |
|
| 1332 |
return load_balancer |
| 1333 |
|
| 1334 |
def get_info(self): |
| 1335 |
self._update_descriptions() |
| 1336 |
|
| 1337 |
if not self.elb: |
| 1338 |
return dict(name=self.name, status=self.status, region=self.module.region) |
| 1339 |
check_elb = dict(self.elb) |
| 1340 |
check_elb_attrs = dict(self.elb_attributes or {}) |
| 1341 |
check_policies = check_elb.get("Policies", {}) |
| 1342 |
try: |
| 1343 |
lb_cookie_policy = check_policies["LBCookieStickinessPolicies"][0]["PolicyName"] |
| 1344 |
except (KeyError, IndexError): |
| 1345 |
lb_cookie_policy = None |
| 1346 |
try: |
| 1347 |
app_cookie_policy = check_policies["AppCookieStickinessPolicies"][0]["PolicyName"] |
| 1348 |
except (KeyError, IndexError): |
| 1349 |
app_cookie_policy = None |
| 1350 |
|
| 1351 |
health_check = camel_dict_to_snake_dict(check_elb.get("HealthCheck", {})) |
| 1352 |
|
| 1353 |
backend_policies = list() |
| 1354 |
for port, policies in self._get_backend_policies().items(): |
| 1355 |
for policy in policies: |
| 1356 |
backend_policies.append(f"{port}:{policy}") |
| 1357 |
|
| 1358 |
info = dict( |
| 1359 |
name=check_elb.get("LoadBalancerName"), |
| 1360 |
dns_name=check_elb.get("DNSName"), |
| 1361 |
zones=check_elb.get("AvailabilityZones"), |
| 1362 |
security_group_ids=check_elb.get("SecurityGroups"), |
| 1363 |
status=self.status, |
| 1364 |
subnets=check_elb.get("Subnets"), |
| 1365 |
scheme=check_elb.get("Scheme"), |
| 1366 |
hosted_zone_name=check_elb.get("CanonicalHostedZoneName"), |
| 1367 |
hosted_zone_id=check_elb.get("CanonicalHostedZoneNameID"), |
| 1368 |
lb_cookie_policy=lb_cookie_policy, |
| 1369 |
app_cookie_policy=app_cookie_policy, |
| 1370 |
proxy_policy=self._get_proxy_protocol_policy(), |
| 1371 |
backends=backend_policies, |
| 1372 |
instances=self._get_instance_ids(), |
| 1373 |
out_of_service_count=0, |
| 1374 |
in_service_count=0, |
| 1375 |
unknown_instance_state_count=0, |
| 1376 |
region=self.module.region, |
| 1377 |
health_check=health_check, |
| 1378 |
) |
| 1379 |
|
| 1380 |
instance_health = camel_dict_to_snake_dict(dict(InstanceHealth=self.elb_health)) |
| 1381 |
info.update(instance_health) |
| 1382 |
|
| 1383 |
# instance state counts: InService or OutOfService |
| 1384 |
if info["instance_health"]: |
| 1385 |
for instance_state in info["instance_health"]: |
| 1386 |
if instance_state["state"] == "InService": |
| 1387 |
info["in_service_count"] += 1 |
| 1388 |
elif instance_state["state"] == "OutOfService": |
| 1389 |
info["out_of_service_count"] += 1 |
| 1390 |
else: |
| 1391 |
info["unknown_instance_state_count"] += 1 |
| 1392 |
|
| 1393 |
listeners = check_elb.get("ListenerDescriptions", []) |
| 1394 |
if listeners: |
| 1395 |
info["listeners"] = list(self._api_listener_as_tuple(listener["Listener"]) for listener in listeners) |
| 1396 |
else: |
| 1397 |
info["listeners"] = [] |
| 1398 |
|
| 1399 |
try: |
| 1400 |
info["connection_draining_timeout"] = check_elb_attrs["ConnectionDraining"]["Timeout"] |
| 1401 |
except KeyError: |
| 1402 |
pass |
| 1403 |
try: |
| 1404 |
info["idle_timeout"] = check_elb_attrs["ConnectionSettings"]["IdleTimeout"] |
| 1405 |
except KeyError: |
| 1406 |
pass |
| 1407 |
try: |
| 1408 |
is_enabled = check_elb_attrs["CrossZoneLoadBalancing"]["Enabled"] |
| 1409 |
info["cross_az_load_balancing"] = "yes" if is_enabled else "no" |
| 1410 |
except KeyError: |
| 1411 |
pass |
| 1412 |
|
| 1413 |
# # return stickiness info? |
| 1414 |
|
| 1415 |
try: |
| 1416 |
info["tags"] = self._get_tags() |
| 1417 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1418 |
self.module.fail_json_aws(e, msg="Failed to get load balancer tags") |
| 1419 |
|
| 1420 |
return info |
| 1421 |
|
| 1422 |
@property |
| 1423 |
def _waiter_config(self): |
| 1424 |
delay = min(10, self.wait_timeout) |
| 1425 |
max_attempts = self.wait_timeout // delay |
| 1426 |
return {"Delay": delay, "MaxAttempts": max_attempts} |
| 1427 |
|
| 1428 |
def _wait_for_elb_created(self): |
| 1429 |
if self.check_mode: |
| 1430 |
return True |
| 1431 |
|
| 1432 |
waiter = get_waiter(self.client, "load_balancer_created") |
| 1433 |
|
| 1434 |
try: |
| 1435 |
waiter.wait( |
| 1436 |
WaiterConfig=self._waiter_config, |
| 1437 |
LoadBalancerNames=[self.name], |
| 1438 |
) |
| 1439 |
except botocore.exceptions.WaiterError as e: |
| 1440 |
self.module.fail_json_aws(e, "Timeout waiting for ELB removal") |
| 1441 |
|
| 1442 |
return True |
| 1443 |
|
| 1444 |
def _wait_for_elb_interface_created(self): |
| 1445 |
if self.check_mode: |
| 1446 |
return True |
| 1447 |
waiter = get_waiter(self.ec2_client, "network_interface_available") |
| 1448 |
|
| 1449 |
filters = ansible_dict_to_boto3_filter_list({"requester-id": "amazon-elb", "description": f"ELB {self.name}"}) |
| 1450 |
|
| 1451 |
try: |
| 1452 |
waiter.wait( |
| 1453 |
WaiterConfig=self._waiter_config, |
| 1454 |
Filters=filters, |
| 1455 |
) |
| 1456 |
except botocore.exceptions.WaiterError as e: |
| 1457 |
self.module.fail_json_aws(e, "Timeout waiting for ELB Interface removal") |
| 1458 |
|
| 1459 |
return True |
| 1460 |
|
| 1461 |
def _wait_for_elb_removed(self): |
| 1462 |
if self.check_mode: |
| 1463 |
return True |
| 1464 |
|
| 1465 |
waiter = get_waiter(self.client, "load_balancer_deleted") |
| 1466 |
|
| 1467 |
try: |
| 1468 |
waiter.wait( |
| 1469 |
WaiterConfig=self._waiter_config, |
| 1470 |
LoadBalancerNames=[self.name], |
| 1471 |
) |
| 1472 |
except botocore.exceptions.WaiterError as e: |
| 1473 |
self.module.fail_json_aws(e, "Timeout waiting for ELB removal") |
| 1474 |
|
| 1475 |
return True |
| 1476 |
|
| 1477 |
def _wait_for_elb_interface_removed(self): |
| 1478 |
if self.check_mode: |
| 1479 |
return True |
| 1480 |
|
| 1481 |
waiter = get_waiter(self.ec2_client, "network_interface_deleted") |
| 1482 |
|
| 1483 |
filters = ansible_dict_to_boto3_filter_list({"requester-id": "amazon-elb", "description": f"ELB {self.name}"}) |
| 1484 |
|
| 1485 |
try: |
| 1486 |
waiter.wait( |
| 1487 |
WaiterConfig=self._waiter_config, |
| 1488 |
Filters=filters, |
| 1489 |
) |
| 1490 |
except botocore.exceptions.WaiterError as e: |
| 1491 |
self.module.fail_json_aws(e, "Timeout waiting for ELB Interface removal") |
| 1492 |
|
| 1493 |
return True |
| 1494 |
|
| 1495 |
def _wait_for_instance_state(self, waiter_name, instances): |
| 1496 |
if not instances: |
| 1497 |
return False |
| 1498 |
|
| 1499 |
if self.check_mode: |
| 1500 |
return True |
| 1501 |
|
| 1502 |
waiter = get_waiter(self.client, waiter_name) |
| 1503 |
|
| 1504 |
instance_list = list(dict(InstanceId=instance) for instance in instances) |
| 1505 |
|
| 1506 |
try: |
| 1507 |
waiter.wait( |
| 1508 |
WaiterConfig=self._waiter_config, |
| 1509 |
LoadBalancerName=self.name, |
| 1510 |
Instances=instance_list, |
| 1511 |
) |
| 1512 |
except botocore.exceptions.WaiterError as e: |
| 1513 |
self.module.fail_json_aws(e, "Timeout waiting for ELB Instance State") |
| 1514 |
|
| 1515 |
return True |
| 1516 |
|
| 1517 |
def _create_elb_listeners(self, listeners): |
| 1518 |
"""Takes a list of listener definitions and creates them""" |
| 1519 |
if not listeners: |
| 1520 |
return False |
| 1521 |
self.changed = True |
| 1522 |
if self.check_mode: |
| 1523 |
return True |
| 1524 |
|
| 1525 |
self.client.create_load_balancer_listeners( |
| 1526 |
aws_retry=True, |
| 1527 |
LoadBalancerName=self.name, |
| 1528 |
Listeners=listeners, |
| 1529 |
) |
| 1530 |
return True |
| 1531 |
|
| 1532 |
def _delete_elb_listeners(self, ports): |
| 1533 |
"""Takes a list of listener ports and deletes them from the ELB""" |
| 1534 |
if not ports: |
| 1535 |
return False |
| 1536 |
self.changed = True |
| 1537 |
if self.check_mode: |
| 1538 |
return True |
| 1539 |
|
| 1540 |
self.client.delete_load_balancer_listeners( |
| 1541 |
aws_retry=True, |
| 1542 |
LoadBalancerName=self.name, |
| 1543 |
LoadBalancerPorts=ports, |
| 1544 |
) |
| 1545 |
return True |
| 1546 |
|
| 1547 |
def _set_elb_listeners(self): |
| 1548 |
""" |
| 1549 |
Creates listeners specified by self.listeners; overwrites existing |
| 1550 |
listeners on these ports; removes extraneous listeners |
| 1551 |
""" |
| 1552 |
|
| 1553 |
if not self.listeners: |
| 1554 |
return False |
| 1555 |
|
| 1556 |
# We can't use sets here: dicts aren't hashable, so convert to the boto3 |
| 1557 |
# format and use a generator to filter |
| 1558 |
new_listeners = list(self._format_listener(listener, True) for listener in self.listeners) |
| 1559 |
existing_listeners = list(listener["Listener"] for listener in self.elb["ListenerDescriptions"]) |
| 1560 |
listeners_to_remove = list(listener for listener in existing_listeners if listener not in new_listeners) |
| 1561 |
listeners_to_add = list(listener for listener in new_listeners if listener not in existing_listeners) |
| 1562 |
|
| 1563 |
changed = False |
| 1564 |
|
| 1565 |
if self.purge_listeners: |
| 1566 |
ports_to_remove = list(listener["LoadBalancerPort"] for listener in listeners_to_remove) |
| 1567 |
else: |
| 1568 |
old_ports = set(listener["LoadBalancerPort"] for listener in listeners_to_remove) |
| 1569 |
new_ports = set(listener["LoadBalancerPort"] for listener in listeners_to_add) |
| 1570 |
# If we're not purging, then we need to remove Listeners |
| 1571 |
# where the full definition doesn't match, but the port does |
| 1572 |
ports_to_remove = list(old_ports & new_ports) |
| 1573 |
|
| 1574 |
# Update is a delete then add, so do the deletion first |
| 1575 |
try: |
| 1576 |
changed |= self._delete_elb_listeners(ports_to_remove) |
| 1577 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1578 |
self.module.fail_json_aws(e, msg="Failed to remove listeners from load balancer") |
| 1579 |
try: |
| 1580 |
changed |= self._create_elb_listeners(listeners_to_add) |
| 1581 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1582 |
self.module.fail_json_aws(e, msg="Failed to remove listeners from load balancer") |
| 1583 |
|
| 1584 |
return changed |
| 1585 |
|
| 1586 |
def _api_listener_as_tuple(self, listener): |
| 1587 |
"""Adds ssl_certificate_id to ELB API tuple if present""" |
| 1588 |
base_tuple = [ |
| 1589 |
listener.get("LoadBalancerPort"), |
| 1590 |
listener.get("InstancePort"), |
| 1591 |
listener.get("Protocol"), |
| 1592 |
listener.get("InstanceProtocol"), |
| 1593 |
] |
| 1594 |
if listener.get("SSLCertificateId", False): |
| 1595 |
base_tuple.append(listener.get("SSLCertificateId")) |
| 1596 |
return tuple(base_tuple) |
| 1597 |
|
| 1598 |
def _attach_subnets(self, subnets): |
| 1599 |
if not subnets: |
| 1600 |
return False |
| 1601 |
self.changed = True |
| 1602 |
if self.check_mode: |
| 1603 |
return True |
| 1604 |
self.client.attach_load_balancer_to_subnets(aws_retry=True, LoadBalancerName=self.name, Subnets=subnets) |
| 1605 |
return True |
| 1606 |
|
| 1607 |
def _detach_subnets(self, subnets): |
| 1608 |
if not subnets: |
| 1609 |
return False |
| 1610 |
self.changed = True |
| 1611 |
if self.check_mode: |
| 1612 |
return True |
| 1613 |
self.client.detach_load_balancer_from_subnets(aws_retry=True, LoadBalancerName=self.name, Subnets=subnets) |
| 1614 |
return True |
| 1615 |
|
| 1616 |
def _set_subnets(self): |
| 1617 |
"""Determine which subnets need to be attached or detached on the ELB""" |
| 1618 |
# Subnets parameter not set, nothing to change |
| 1619 |
if self.subnets is None: |
| 1620 |
return False |
| 1621 |
|
| 1622 |
changed = False |
| 1623 |
|
| 1624 |
if self.purge_subnets: |
| 1625 |
subnets_to_detach = list(set(self.elb["Subnets"]) - set(self.subnets)) |
| 1626 |
else: |
| 1627 |
subnets_to_detach = list() |
| 1628 |
subnets_to_attach = list(set(self.subnets) - set(self.elb["Subnets"])) |
| 1629 |
|
| 1630 |
# You can't add multiple subnets from the same AZ. Remove first, then |
| 1631 |
# add. |
| 1632 |
try: |
| 1633 |
changed |= self._detach_subnets(subnets_to_detach) |
| 1634 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1635 |
self.module.fail_json_aws(e, msg="Failed to detach subnets from load balancer") |
| 1636 |
try: |
| 1637 |
changed |= self._attach_subnets(subnets_to_attach) |
| 1638 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1639 |
self.module.fail_json_aws(e, msg="Failed to attach subnets to load balancer") |
| 1640 |
|
| 1641 |
return changed |
| 1642 |
|
| 1643 |
def _check_scheme(self): |
| 1644 |
"""Determine if the current scheme is different than the scheme of the ELB""" |
| 1645 |
if self.scheme: |
| 1646 |
if self.elb["Scheme"] != self.scheme: |
| 1647 |
return True |
| 1648 |
return False |
| 1649 |
|
| 1650 |
def _enable_zones(self, zones): |
| 1651 |
if not zones: |
| 1652 |
return False |
| 1653 |
self.changed = True |
| 1654 |
if self.check_mode: |
| 1655 |
return True |
| 1656 |
|
| 1657 |
try: |
| 1658 |
self.client.enable_availability_zones_for_load_balancer( |
| 1659 |
aws_retry=True, |
| 1660 |
LoadBalancerName=self.name, |
| 1661 |
AvailabilityZones=zones, |
| 1662 |
) |
| 1663 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1664 |
self.module.fail_json_aws(e, msg="Failed to enable zones for load balancer") |
| 1665 |
return True |
| 1666 |
|
| 1667 |
def _disable_zones(self, zones): |
| 1668 |
if not zones: |
| 1669 |
return False |
| 1670 |
self.changed = True |
| 1671 |
if self.check_mode: |
| 1672 |
return True |
| 1673 |
|
| 1674 |
try: |
| 1675 |
self.client.disable_availability_zones_for_load_balancer( |
| 1676 |
aws_retry=True, |
| 1677 |
LoadBalancerName=self.name, |
| 1678 |
AvailabilityZones=zones, |
| 1679 |
) |
| 1680 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1681 |
self.module.fail_json_aws(e, msg="Failed to disable zones for load balancer") |
| 1682 |
return True |
| 1683 |
|
| 1684 |
def _set_zones(self): |
| 1685 |
"""Determine which zones need to be enabled or disabled on the ELB""" |
| 1686 |
# zones parameter not set, nothing to changeA |
| 1687 |
if self.zones is None: |
| 1688 |
return False |
| 1689 |
|
| 1690 |
changed = False |
| 1691 |
|
| 1692 |
if self.purge_zones: |
| 1693 |
zones_to_disable = list(set(self.elb["AvailabilityZones"]) - set(self.zones)) |
| 1694 |
else: |
| 1695 |
zones_to_disable = list() |
| 1696 |
zones_to_enable = list(set(self.zones) - set(self.elb["AvailabilityZones"])) |
| 1697 |
|
| 1698 |
# Add before we remove to reduce the chance of an outage if someone |
| 1699 |
# replaces all zones at once |
| 1700 |
try: |
| 1701 |
changed |= self._enable_zones(zones_to_enable) |
| 1702 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1703 |
self.module.fail_json_aws(e, msg="Failed to enable zone on load balancer") |
| 1704 |
try: |
| 1705 |
changed |= self._disable_zones(zones_to_disable) |
| 1706 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1707 |
self.module.fail_json_aws(e, msg="Failed to attach zone to load balancer") |
| 1708 |
|
| 1709 |
return changed |
| 1710 |
|
| 1711 |
def _set_security_groups(self): |
| 1712 |
if not self.security_group_ids: |
| 1713 |
return False |
| 1714 |
# Security Group Names should already by converted to IDs by this point. |
| 1715 |
if set(self.elb["SecurityGroups"]) == set(self.security_group_ids): |
| 1716 |
return False |
| 1717 |
|
| 1718 |
self.changed = True |
| 1719 |
|
| 1720 |
if self.check_mode: |
| 1721 |
return True |
| 1722 |
|
| 1723 |
try: |
| 1724 |
self.client.apply_security_groups_to_load_balancer( |
| 1725 |
aws_retry=True, |
| 1726 |
LoadBalancerName=self.name, |
| 1727 |
SecurityGroups=self.security_group_ids, |
| 1728 |
) |
| 1729 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1730 |
self.module.fail_json_aws(e, msg="Failed to apply security groups to load balancer") |
| 1731 |
return True |
| 1732 |
|
| 1733 |
def _set_health_check(self): |
| 1734 |
if not self.health_check: |
| 1735 |
return False |
| 1736 |
|
| 1737 |
# Set health check values on ELB as needed |
| 1738 |
health_check_config = self._format_healthcheck() |
| 1739 |
|
| 1740 |
if self.elb and health_check_config == self.elb["HealthCheck"]: |
| 1741 |
return False |
| 1742 |
|
| 1743 |
self.changed = True |
| 1744 |
if self.check_mode: |
| 1745 |
return True |
| 1746 |
try: |
| 1747 |
self.client.configure_health_check( |
| 1748 |
aws_retry=True, |
| 1749 |
LoadBalancerName=self.name, |
| 1750 |
HealthCheck=health_check_config, |
| 1751 |
) |
| 1752 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1753 |
self.module.fail_json_aws(e, msg="Failed to apply healthcheck to load balancer") |
| 1754 |
|
| 1755 |
return True |
| 1756 |
|
| 1757 |
def _set_elb_attributes(self): |
| 1758 |
attributes = {} |
| 1759 |
if self.cross_az_load_balancing is not None: |
| 1760 |
attr = dict(Enabled=self.cross_az_load_balancing) |
| 1761 |
if not self.elb_attributes.get("CrossZoneLoadBalancing", None) == attr: |
| 1762 |
attributes["CrossZoneLoadBalancing"] = attr |
| 1763 |
|
| 1764 |
if self.idle_timeout is not None: |
| 1765 |
attr = dict(IdleTimeout=self.idle_timeout) |
| 1766 |
if not self.elb_attributes.get("ConnectionSettings", None) == attr: |
| 1767 |
attributes["ConnectionSettings"] = attr |
| 1768 |
|
| 1769 |
if self.connection_draining_timeout is not None: |
| 1770 |
curr_attr = dict(self.elb_attributes.get("ConnectionDraining", {})) |
| 1771 |
if self.connection_draining_timeout == 0: |
| 1772 |
attr = dict(Enabled=False) |
| 1773 |
curr_attr.pop("Timeout", None) |
| 1774 |
else: |
| 1775 |
attr = dict(Enabled=True, Timeout=self.connection_draining_timeout) |
| 1776 |
if not curr_attr == attr: |
| 1777 |
attributes["ConnectionDraining"] = attr |
| 1778 |
|
| 1779 |
if self.access_logs is not None: |
| 1780 |
curr_attr = dict(self.elb_attributes.get("AccessLog", {})) |
| 1781 |
# For disabling we only need to compare and pass 'Enabled' |
| 1782 |
if not self.access_logs.get("enabled"): |
| 1783 |
curr_attr = dict(Enabled=curr_attr.get("Enabled", False)) |
| 1784 |
attr = dict(Enabled=self.access_logs.get("enabled")) |
| 1785 |
else: |
| 1786 |
attr = dict( |
| 1787 |
Enabled=True, |
| 1788 |
S3BucketName=self.access_logs["s3_location"], |
| 1789 |
S3BucketPrefix=self.access_logs.get("s3_prefix", ""), |
| 1790 |
EmitInterval=self.access_logs.get("interval", 60), |
| 1791 |
) |
| 1792 |
if not curr_attr == attr: |
| 1793 |
attributes["AccessLog"] = attr |
| 1794 |
|
| 1795 |
if not attributes: |
| 1796 |
return False |
| 1797 |
|
| 1798 |
self.changed = True |
| 1799 |
if self.check_mode: |
| 1800 |
return True |
| 1801 |
|
| 1802 |
try: |
| 1803 |
self.client.modify_load_balancer_attributes( |
| 1804 |
aws_retry=True, LoadBalancerName=self.name, LoadBalancerAttributes=attributes |
| 1805 |
) |
| 1806 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1807 |
self.module.fail_json_aws(e, msg="Failed to apply load balancer attributes") |
| 1808 |
|
| 1809 |
def _proxy_policy_name(self): |
| 1810 |
return "ProxyProtocol-policy" |
| 1811 |
|
| 1812 |
def _policy_name(self, policy_type): |
| 1813 |
return f"ec2-elb-lb-{policy_type}" |
| 1814 |
|
| 1815 |
def _set_listener_policies(self, port, policies): |
| 1816 |
self.changed = True |
| 1817 |
if self.check_mode: |
| 1818 |
return True |
| 1819 |
|
| 1820 |
try: |
| 1821 |
self.client.set_load_balancer_policies_of_listener( |
| 1822 |
aws_retry=True, |
| 1823 |
LoadBalancerName=self.name, |
| 1824 |
LoadBalancerPort=port, |
| 1825 |
PolicyNames=list(policies), |
| 1826 |
) |
| 1827 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1828 |
self.module.fail_json_aws( |
| 1829 |
e, msg="Failed to set load balancer listener policies", port=port, policies=policies |
| 1830 |
) |
| 1831 |
|
| 1832 |
return True |
| 1833 |
|
| 1834 |
def _get_stickiness_policies(self): |
| 1835 |
"""Get a list of AppCookieStickinessPolicyType and LBCookieStickinessPolicyType policies""" |
| 1836 |
return list( |
| 1837 |
p["PolicyName"] |
| 1838 |
for p in self.elb_policies |
| 1839 |
if p["PolicyTypeName"] in ["AppCookieStickinessPolicyType", "LBCookieStickinessPolicyType"] |
| 1840 |
) |
| 1841 |
|
| 1842 |
def _get_app_stickness_policy_map(self): |
| 1843 |
"""Get a mapping of App Cookie Stickiness policy names to their definitions""" |
| 1844 |
policies = self.elb.get("Policies", {}).get("AppCookieStickinessPolicies", []) |
| 1845 |
return {p["PolicyName"]: p for p in policies} |
| 1846 |
|
| 1847 |
def _get_lb_stickness_policy_map(self): |
| 1848 |
"""Get a mapping of LB Cookie Stickiness policy names to their definitions""" |
| 1849 |
policies = self.elb.get("Policies", {}).get("LBCookieStickinessPolicies", []) |
| 1850 |
return {p["PolicyName"]: p for p in policies} |
| 1851 |
|
| 1852 |
def _purge_stickiness_policies(self): |
| 1853 |
"""Removes all stickiness policies from all Load Balancers""" |
| 1854 |
# Used when purging stickiness policies or updating a policy (you can't |
| 1855 |
# update a policy while it's connected to a Listener) |
| 1856 |
stickiness_policies = set(self._get_stickiness_policies()) |
| 1857 |
listeners = self.elb["ListenerDescriptions"] |
| 1858 |
changed = False |
| 1859 |
for listener in listeners: |
| 1860 |
port = listener["Listener"]["LoadBalancerPort"] |
| 1861 |
policies = set(listener["PolicyNames"]) |
| 1862 |
new_policies = set(policies - stickiness_policies) |
| 1863 |
if policies != new_policies: |
| 1864 |
changed |= self._set_listener_policies(port, new_policies) |
| 1865 |
|
| 1866 |
return changed |
| 1867 |
|
| 1868 |
def _set_stickiness_policies(self): |
| 1869 |
if self.stickiness is None: |
| 1870 |
return False |
| 1871 |
|
| 1872 |
# Make sure that the list of policies and listeners is up to date, we're |
| 1873 |
# going to make changes to all listeners |
| 1874 |
self._update_descriptions() |
| 1875 |
|
| 1876 |
if not self.stickiness["enabled"]: |
| 1877 |
return self._purge_stickiness_policies() |
| 1878 |
|
| 1879 |
if self.stickiness["type"] == "loadbalancer": |
| 1880 |
policy_name = self._policy_name("LBCookieStickinessPolicyType") |
| 1881 |
expiration = self.stickiness.get("expiration") |
| 1882 |
if not expiration: |
| 1883 |
expiration = 0 |
| 1884 |
policy_description = dict( |
| 1885 |
PolicyName=policy_name, |
| 1886 |
CookieExpirationPeriod=expiration, |
| 1887 |
) |
| 1888 |
existing_policies = self._get_lb_stickness_policy_map() |
| 1889 |
add_method = self.client.create_lb_cookie_stickiness_policy |
| 1890 |
elif self.stickiness["type"] == "application": |
| 1891 |
policy_name = self._policy_name("AppCookieStickinessPolicyType") |
| 1892 |
policy_description = dict(PolicyName=policy_name, CookieName=self.stickiness.get("cookie", 0)) |
| 1893 |
existing_policies = self._get_app_stickness_policy_map() |
| 1894 |
add_method = self.client.create_app_cookie_stickiness_policy |
| 1895 |
else: |
| 1896 |
# We shouldn't get here... |
| 1897 |
self.module.fail_json(msg=f"Unknown stickiness policy {self.stickiness['type']}") |
| 1898 |
|
| 1899 |
changed = False |
| 1900 |
# To update a policy we need to delete then re-add, and we can only |
| 1901 |
# delete if the policy isn't attached to a listener |
| 1902 |
if policy_name in existing_policies: |
| 1903 |
if existing_policies[policy_name] != policy_description: |
| 1904 |
changed |= self._purge_stickiness_policies() |
| 1905 |
|
| 1906 |
if changed: |
| 1907 |
self._update_descriptions() |
| 1908 |
|
| 1909 |
changed |= self._set_stickiness_policy( |
| 1910 |
method=add_method, |
| 1911 |
description=policy_description, |
| 1912 |
existing_policies=existing_policies, |
| 1913 |
) |
| 1914 |
|
| 1915 |
listeners = self.elb["ListenerDescriptions"] |
| 1916 |
for listener in listeners: |
| 1917 |
changed |= self._set_lb_stickiness_policy(listener=listener, policy=policy_name) |
| 1918 |
return changed |
| 1919 |
|
| 1920 |
def _delete_loadbalancer_policy(self, policy_name): |
| 1921 |
self.changed = True |
| 1922 |
if self.check_mode: |
| 1923 |
return True |
| 1924 |
|
| 1925 |
try: |
| 1926 |
self.client.delete_load_balancer_policy( |
| 1927 |
LoadBalancerName=self.name, |
| 1928 |
PolicyName=policy_name, |
| 1929 |
) |
| 1930 |
except is_boto3_error_code("InvalidConfigurationRequest"): |
| 1931 |
# Already deleted |
| 1932 |
return False |
| 1933 |
except ( |
| 1934 |
botocore.exceptions.BotoCoreError, |
| 1935 |
botocore.exceptions.ClientError, |
| 1936 |
) as e: # pylint: disable=duplicate-except |
| 1937 |
self.module.fail_json_aws(e, msg=f"Failed to load balancer policy {policy_name}") |
| 1938 |
return True |
| 1939 |
|
| 1940 |
def _set_stickiness_policy(self, method, description, existing_policies=None): |
| 1941 |
changed = False |
| 1942 |
if existing_policies: |
| 1943 |
policy_name = description["PolicyName"] |
| 1944 |
if policy_name in existing_policies: |
| 1945 |
if existing_policies[policy_name] == description: |
| 1946 |
return False |
| 1947 |
if existing_policies[policy_name] != description: |
| 1948 |
changed |= self._delete_loadbalancer_policy(policy_name) |
| 1949 |
|
| 1950 |
self.changed = True |
| 1951 |
changed = True |
| 1952 |
|
| 1953 |
if self.check_mode: |
| 1954 |
return changed |
| 1955 |
|
| 1956 |
# This needs to be in place for comparisons, but not passed to the |
| 1957 |
# method. |
| 1958 |
if not description.get("CookieExpirationPeriod", None): |
| 1959 |
description.pop("CookieExpirationPeriod", None) |
| 1960 |
|
| 1961 |
try: |
| 1962 |
method(aws_retry=True, LoadBalancerName=self.name, **description) |
| 1963 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 1964 |
self.module.fail_json_aws( |
| 1965 |
e, msg="Failed to create load balancer stickiness policy", description=description |
| 1966 |
) |
| 1967 |
return changed |
| 1968 |
|
| 1969 |
def _set_lb_stickiness_policy(self, listener, policy): |
| 1970 |
port = listener["Listener"]["LoadBalancerPort"] |
| 1971 |
stickiness_policies = set(self._get_stickiness_policies()) |
| 1972 |
changed = False |
| 1973 |
|
| 1974 |
policies = set(listener["PolicyNames"]) |
| 1975 |
new_policies = list(policies - stickiness_policies) |
| 1976 |
new_policies.append(policy) |
| 1977 |
|
| 1978 |
if policies != set(new_policies): |
| 1979 |
changed |= self._set_listener_policies(port, new_policies) |
| 1980 |
|
| 1981 |
return changed |
| 1982 |
|
| 1983 |
def _get_backend_policies(self): |
| 1984 |
"""Get a list of backend policies mapped to the InstancePort""" |
| 1985 |
if not self.elb: |
| 1986 |
return {} |
| 1987 |
server_descriptions = self.elb.get("BackendServerDescriptions", []) |
| 1988 |
policies = {b["InstancePort"]: b["PolicyNames"] for b in server_descriptions} |
| 1989 |
return policies |
| 1990 |
|
| 1991 |
def _get_proxy_protocol_policy(self): |
| 1992 |
"""Returns the name of the name of the ProxyPolicy if created""" |
| 1993 |
all_proxy_policies = self._get_proxy_policies() |
| 1994 |
if not all_proxy_policies: |
| 1995 |
return None |
| 1996 |
if len(all_proxy_policies) == 1: |
| 1997 |
return all_proxy_policies[0] |
| 1998 |
return all_proxy_policies |
| 1999 |
|
| 2000 |
def _get_proxy_policies(self): |
| 2001 |
"""Get a list of ProxyProtocolPolicyType policies""" |
| 2002 |
return list(p["PolicyName"] for p in self.elb_policies if p["PolicyTypeName"] == "ProxyProtocolPolicyType") |
| 2003 |
|
| 2004 |
def _get_policy_map(self): |
| 2005 |
"""Get a mapping of Policy names to their definitions""" |
| 2006 |
return {p["PolicyName"]: p for p in self.elb_policies} |
| 2007 |
|
| 2008 |
def _set_backend_policies(self): |
| 2009 |
"""Sets policies for all backends""" |
| 2010 |
# Currently only supports setting ProxyProtocol policies |
| 2011 |
if not self.listeners: |
| 2012 |
return False |
| 2013 |
|
| 2014 |
backend_policies = self._get_backend_policies() |
| 2015 |
proxy_policies = set(self._get_proxy_policies()) |
| 2016 |
|
| 2017 |
proxy_ports = dict() |
| 2018 |
for listener in self.listeners: |
| 2019 |
proxy_protocol = listener.get("proxy_protocol", None) |
| 2020 |
# Only look at the listeners for which proxy_protocol is defined |
| 2021 |
if proxy_protocol is None: |
| 2022 |
continue |
| 2023 |
instance_port = listener.get("instance_port") |
| 2024 |
if proxy_ports.get(instance_port, None) is not None: |
| 2025 |
if proxy_ports[instance_port] != proxy_protocol: |
| 2026 |
self.module.fail_json_aws( |
| 2027 |
f"proxy_protocol set to conflicting values for listeners on port {instance_port}" |
| 2028 |
) |
| 2029 |
proxy_ports[instance_port] = proxy_protocol |
| 2030 |
|
| 2031 |
if not proxy_ports: |
| 2032 |
return False |
| 2033 |
|
| 2034 |
changed = False |
| 2035 |
|
| 2036 |
# If anyone's set proxy_protocol to true, make sure we have our policy |
| 2037 |
# in place. |
| 2038 |
proxy_policy_name = self._proxy_policy_name() |
| 2039 |
if any(proxy_ports.values()): |
| 2040 |
changed |= self._set_proxy_protocol_policy(proxy_policy_name) |
| 2041 |
|
| 2042 |
for port, port_policy in proxy_ports.items(): |
| 2043 |
current_policies = set(backend_policies.get(port, [])) |
| 2044 |
new_policies = list(current_policies - proxy_policies) |
| 2045 |
if port_policy: |
| 2046 |
new_policies.append(proxy_policy_name) |
| 2047 |
|
| 2048 |
changed |= self._set_backend_policy(port, new_policies) |
| 2049 |
|
| 2050 |
return changed |
| 2051 |
|
| 2052 |
def _set_backend_policy(self, port, policies): |
| 2053 |
backend_policies = self._get_backend_policies() |
| 2054 |
current_policies = set(backend_policies.get(port, [])) |
| 2055 |
|
| 2056 |
if current_policies == set(policies): |
| 2057 |
return False |
| 2058 |
|
| 2059 |
self.changed = True |
| 2060 |
|
| 2061 |
if self.check_mode: |
| 2062 |
return True |
| 2063 |
|
| 2064 |
try: |
| 2065 |
self.client.set_load_balancer_policies_for_backend_server( |
| 2066 |
aws_retry=True, |
| 2067 |
LoadBalancerName=self.name, |
| 2068 |
InstancePort=port, |
| 2069 |
PolicyNames=policies, |
| 2070 |
) |
| 2071 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 2072 |
self.module.fail_json_aws( |
| 2073 |
e, msg="Failed to set load balancer backend policies", port=port, policies=policies |
| 2074 |
) |
| 2075 |
|
| 2076 |
return True |
| 2077 |
|
| 2078 |
def _set_proxy_protocol_policy(self, policy_name): |
| 2079 |
"""Install a proxy protocol policy if needed""" |
| 2080 |
policy_map = self._get_policy_map() |
| 2081 |
|
| 2082 |
policy_attributes = [dict(AttributeName="ProxyProtocol", AttributeValue="true")] |
| 2083 |
|
| 2084 |
proxy_policy = dict( |
| 2085 |
PolicyName=policy_name, |
| 2086 |
PolicyTypeName="ProxyProtocolPolicyType", |
| 2087 |
PolicyAttributeDescriptions=policy_attributes, |
| 2088 |
) |
| 2089 |
|
| 2090 |
existing_policy = policy_map.get(policy_name) |
| 2091 |
if proxy_policy == existing_policy: |
| 2092 |
return False |
| 2093 |
|
| 2094 |
if existing_policy is not None: |
| 2095 |
self.module.fail_json( |
| 2096 |
msg=f"Unable to configure ProxyProtocol policy. Policy with name {policy_name} already exists and doesn't match.", |
| 2097 |
policy=proxy_policy, |
| 2098 |
existing_policy=existing_policy, |
| 2099 |
) |
| 2100 |
|
| 2101 |
proxy_policy["PolicyAttributes"] = proxy_policy.pop("PolicyAttributeDescriptions") |
| 2102 |
proxy_policy["LoadBalancerName"] = self.name |
| 2103 |
self.changed = True |
| 2104 |
|
| 2105 |
if self.check_mode: |
| 2106 |
return True |
| 2107 |
|
| 2108 |
try: |
| 2109 |
self.client.create_load_balancer_policy(aws_retry=True, **proxy_policy) |
| 2110 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 2111 |
self.module.fail_json_aws(e, msg="Failed to create load balancer policy", policy=proxy_policy) |
| 2112 |
|
| 2113 |
return True |
| 2114 |
|
| 2115 |
def _get_instance_ids(self): |
| 2116 |
"""Get the current list of instance ids installed in the elb""" |
| 2117 |
elb = self.elb or {} |
| 2118 |
return list(i["InstanceId"] for i in elb.get("Instances", [])) |
| 2119 |
|
| 2120 |
def _change_instances(self, method, instances): |
| 2121 |
if not instances: |
| 2122 |
return False |
| 2123 |
|
| 2124 |
self.changed = True |
| 2125 |
if self.check_mode: |
| 2126 |
return True |
| 2127 |
|
| 2128 |
instance_id_list = list({"InstanceId": i} for i in instances) |
| 2129 |
try: |
| 2130 |
method( |
| 2131 |
aws_retry=True, |
| 2132 |
LoadBalancerName=self.name, |
| 2133 |
Instances=instance_id_list, |
| 2134 |
) |
| 2135 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 2136 |
self.module.fail_json_aws( |
| 2137 |
e, msg="Failed to change instance registration", instances=instance_id_list, name=self.name |
| 2138 |
) |
| 2139 |
return True |
| 2140 |
|
| 2141 |
def _set_instance_ids(self): |
| 2142 |
"""Register or deregister instances from an lb instance""" |
| 2143 |
new_instances = self.instance_ids or [] |
| 2144 |
existing_instances = self._get_instance_ids() |
| 2145 |
|
| 2146 |
instances_to_add = set(new_instances) - set(existing_instances) |
| 2147 |
if self.purge_instance_ids: |
| 2148 |
instances_to_remove = set(existing_instances) - set(new_instances) |
| 2149 |
else: |
| 2150 |
instances_to_remove = [] |
| 2151 |
|
| 2152 |
changed = False |
| 2153 |
|
| 2154 |
changed |= self._change_instances(self.client.register_instances_with_load_balancer, instances_to_add) |
| 2155 |
if self.wait: |
| 2156 |
self._wait_for_instance_state("instance_in_service", list(instances_to_add)) |
| 2157 |
changed |= self._change_instances(self.client.deregister_instances_from_load_balancer, instances_to_remove) |
| 2158 |
if self.wait: |
| 2159 |
self._wait_for_instance_state("instance_deregistered", list(instances_to_remove)) |
| 2160 |
|
| 2161 |
return changed |
| 2162 |
|
| 2163 |
def _get_tags(self): |
| 2164 |
tags = self.client.describe_tags(aws_retry=True, LoadBalancerNames=[self.name]) |
| 2165 |
if not tags: |
| 2166 |
return {} |
| 2167 |
try: |
| 2168 |
tags = tags["TagDescriptions"][0]["Tags"] |
| 2169 |
except (KeyError, TypeError): |
| 2170 |
return {} |
| 2171 |
return boto3_tag_list_to_ansible_dict(tags) |
| 2172 |
|
| 2173 |
def _add_tags(self, tags_to_set): |
| 2174 |
if not tags_to_set: |
| 2175 |
return False |
| 2176 |
self.changed = True |
| 2177 |
if self.check_mode: |
| 2178 |
return True |
| 2179 |
tags_to_add = ansible_dict_to_boto3_tag_list(tags_to_set) |
| 2180 |
self.client.add_tags(LoadBalancerNames=[self.name], Tags=tags_to_add) |
| 2181 |
return True |
| 2182 |
|
| 2183 |
def _remove_tags(self, tags_to_unset): |
| 2184 |
if not tags_to_unset: |
| 2185 |
return False |
| 2186 |
self.changed = True |
| 2187 |
if self.check_mode: |
| 2188 |
return True |
| 2189 |
tags_to_remove = [dict(Key=tagkey) for tagkey in tags_to_unset] |
| 2190 |
self.client.remove_tags(LoadBalancerNames=[self.name], Tags=tags_to_remove) |
| 2191 |
return True |
| 2192 |
|
| 2193 |
def _set_tags(self): |
| 2194 |
"""Add/Delete tags""" |
| 2195 |
if self.tags is None: |
| 2196 |
return False |
| 2197 |
|
| 2198 |
try: |
| 2199 |
current_tags = self._get_tags() |
| 2200 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 2201 |
self.module.fail_json_aws(e, msg="Failed to get load balancer tags") |
| 2202 |
|
| 2203 |
tags_to_set, tags_to_unset = compare_aws_tags(current_tags, self.tags, self.purge_tags) |
| 2204 |
|
| 2205 |
changed = False |
| 2206 |
try: |
| 2207 |
changed |= self._remove_tags(tags_to_unset) |
| 2208 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 2209 |
self.module.fail_json_aws(e, msg="Failed to remove load balancer tags") |
| 2210 |
try: |
| 2211 |
changed |= self._add_tags(tags_to_set) |
| 2212 |
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: |
| 2213 |
self.module.fail_json_aws(e, msg="Failed to add load balancer tags") |
| 2214 |
|
| 2215 |
return changed |
| 2216 |
|
| 2217 |
def _validate_stickiness(self, stickiness): |
| 2218 |
problem_found = False |
| 2219 |
if not stickiness: |
| 2220 |
return problem_found |
| 2221 |
if not stickiness["enabled"]: |
| 2222 |
return problem_found |
| 2223 |
if stickiness["type"] == "application": |
| 2224 |
if not stickiness.get("cookie"): |
| 2225 |
problem_found = True |
| 2226 |
self.module.fail_json( |
| 2227 |
msg='cookie must be specified when stickiness type is "application"', |
| 2228 |
stickiness=stickiness, |
| 2229 |
) |
| 2230 |
if stickiness.get("expiration"): |
| 2231 |
self.warn( |
| 2232 |
msg='expiration is ignored when stickiness type is "application"', |
| 2233 |
) |
| 2234 |
if stickiness["type"] == "loadbalancer": |
| 2235 |
if stickiness.get("cookie"): |
| 2236 |
self.warn( |
| 2237 |
msg='cookie is ignored when stickiness type is "loadbalancer"', |
| 2238 |
) |
| 2239 |
return problem_found |
| 2240 |
|
| 2241 |
def _validate_access_logs(self, access_logs): |
| 2242 |
problem_found = False |
| 2243 |
if not access_logs: |
| 2244 |
return problem_found |
| 2245 |
if not access_logs["enabled"]: |
| 2246 |
return problem_found |
| 2247 |
if not access_logs.get("s3_location", None): |
| 2248 |
problem_found = True |
| 2249 |
self.module.fail_json(msg='s3_location must be provided when access_logs.state is "present"') |
| 2250 |
return problem_found |
| 2251 |
|
| 2252 |
def _validate_creation_requirements(self): |
| 2253 |
if self.elb: |
| 2254 |
return False |
| 2255 |
problem_found = False |
| 2256 |
if not self.subnets and not self.zones: |
| 2257 |
problem_found = True |
| 2258 |
self.module.fail_json(msg="One of subnets or zones must be provided when creating an ELB") |
| 2259 |
if not self.listeners: |
| 2260 |
problem_found = True |
| 2261 |
self.module.fail_json(msg="listeners must be provided when creating an ELB") |
| 2262 |
return problem_found |
| 2263 |
|
| 2264 |
def _validate_listeners(self, listeners): |
| 2265 |
if not listeners: |
| 2266 |
return False |
| 2267 |
return any(self._validate_listener(listener) for listener in listeners) |
| 2268 |
|
| 2269 |
def _validate_listener(self, listener): |
| 2270 |
problem_found = False |
| 2271 |
if not listener: |
| 2272 |
return problem_found |
| 2273 |
for protocol in ["instance_protocol", "protocol"]: |
| 2274 |
value = listener.get(protocol, None) |
| 2275 |
problem = self._validate_protocol(value) |
| 2276 |
problem_found |= problem |
| 2277 |
if problem: |
| 2278 |
self.module.fail_json(msg=f"Invalid protocol ({value}) in listener", listener=listener) |
| 2279 |
return problem_found |
| 2280 |
|
| 2281 |
def _validate_health_check(self, health_check): |
| 2282 |
if not health_check: |
| 2283 |
return False |
| 2284 |
protocol = health_check["ping_protocol"] |
| 2285 |
if self._validate_protocol(protocol): |
| 2286 |
self.module.fail_json( |
| 2287 |
msg=f"Invalid protocol ({protocol}) defined in health check", |
| 2288 |
health_check=health_check, |
| 2289 |
) |
| 2290 |
if protocol.upper() in ["HTTP", "HTTPS"]: |
| 2291 |
if not health_check["ping_path"]: |
| 2292 |
self.module.fail_json( |
| 2293 |
msg="For HTTP and HTTPS health checks a ping_path must be provided", |
| 2294 |
health_check=health_check, |
| 2295 |
) |
| 2296 |
return False |
| 2297 |
|
| 2298 |
def _validate_protocol(self, protocol): |
| 2299 |
if not protocol: |
| 2300 |
return False |
| 2301 |
return protocol.upper() not in ["HTTP", "HTTPS", "TCP", "SSL"] |
| 2302 |
|
| 2303 |
@AWSRetry.jittered_backoff() |
| 2304 |
def _describe_loadbalancer(self, lb_name): |
| 2305 |
paginator = self.client.get_paginator("describe_load_balancers") |
| 2306 |
return paginator.paginate(LoadBalancerNames=[lb_name]).build_full_result()["LoadBalancerDescriptions"] |
| 2307 |
|
| 2308 |
def _get_vpc_from_subnets(self, subnets): |
| 2309 |
if not subnets: |
| 2310 |
return None |
| 2311 |
|
| 2312 |
subnet_details = self._describe_subnets(list(subnets)) |
| 2313 |
vpc_ids = set(subnet["VpcId"] for subnet in subnet_details) |
| 2314 |
|
| 2315 |
if not vpc_ids: |
| 2316 |
return None |
| 2317 |
if len(vpc_ids) > 1: |
| 2318 |
self.module.fail_json( |
| 2319 |
"Subnets for an ELB may not span multiple VPCs", subnets=subnet_details, vpc_ids=vpc_ids |
| 2320 |
) |
| 2321 |
return vpc_ids.pop() |
| 2322 |
|
| 2323 |
@AWSRetry.jittered_backoff() |
| 2324 |
def _describe_subnets(self, subnet_ids): |
| 2325 |
paginator = self.ec2_client.get_paginator("describe_subnets") |
| 2326 |
return paginator.paginate(SubnetIds=subnet_ids).build_full_result()["Subnets"] |
| 2327 |
|
| 2328 |
# Wrap it so we get the backoff |
| 2329 |
@AWSRetry.jittered_backoff() |
| 2330 |
def _get_ec2_security_group_ids_from_names(self, **params): |
| 2331 |
return get_ec2_security_group_ids_from_names(ec2_connection=self.ec2_client, **params) |
| 2332 |
|
| 2333 |
|
| 2334 |
def main(): |
| 2335 |
access_log_spec = dict( |
| 2336 |
enabled=dict(required=False, type="bool", default=True), |
| 2337 |
s3_location=dict(required=False, type="str"), |
| 2338 |
s3_prefix=dict(required=False, type="str", default=""), |
| 2339 |
interval=dict(required=False, type="int", default=60, choices=[5, 60]), |
| 2340 |
) |
| 2341 |
|
| 2342 |
stickiness_spec = dict( |
| 2343 |
type=dict(required=False, type="str", choices=["application", "loadbalancer"]), |
| 2344 |
enabled=dict(required=False, type="bool", default=True), |
| 2345 |
cookie=dict(required=False, type="str"), |
| 2346 |
expiration=dict(required=False, type="int"), |
| 2347 |
) |
| 2348 |
|
| 2349 |
healthcheck_spec = dict( |
| 2350 |
ping_protocol=dict(required=True, type="str"), |
| 2351 |
ping_path=dict(required=False, type="str"), |
| 2352 |
ping_port=dict(required=True, type="int"), |
| 2353 |
interval=dict(required=True, type="int"), |
| 2354 |
timeout=dict(aliases=["response_timeout"], required=True, type="int"), |
| 2355 |
unhealthy_threshold=dict(required=True, type="int"), |
| 2356 |
healthy_threshold=dict(required=True, type="int"), |
| 2357 |
) |
| 2358 |
|
| 2359 |
listeners_spec = dict( |
| 2360 |
load_balancer_port=dict(required=True, type="int"), |
| 2361 |
instance_port=dict(required=True, type="int"), |
| 2362 |
ssl_certificate_id=dict(required=False, type="str"), |
| 2363 |
protocol=dict(required=True, type="str"), |
| 2364 |
instance_protocol=dict(required=False, type="str"), |
| 2365 |
proxy_protocol=dict(required=False, type="bool"), |
| 2366 |
) |
| 2367 |
|
| 2368 |
argument_spec = dict( |
| 2369 |
state=dict(required=True, choices=["present", "absent"]), |
| 2370 |
name=dict(required=True), |
| 2371 |
listeners=dict(type="list", elements="dict", options=listeners_spec), |
| 2372 |
purge_listeners=dict(default=True, type="bool"), |
| 2373 |
instance_ids=dict(type="list", elements="str"), |
| 2374 |
purge_instance_ids=dict(default=False, type="bool"), |
| 2375 |
zones=dict(type="list", elements="str"), |
| 2376 |
purge_zones=dict(default=False, type="bool"), |
| 2377 |
security_group_ids=dict(type="list", elements="str"), |
| 2378 |
security_group_names=dict(type="list", elements="str"), |
| 2379 |
health_check=dict(type="dict", options=healthcheck_spec), |
| 2380 |
subnets=dict(type="list", elements="str"), |
| 2381 |
purge_subnets=dict(default=False, type="bool"), |
| 2382 |
scheme=dict(choices=["internal", "internet-facing"]), |
| 2383 |
connection_draining_timeout=dict(type="int"), |
| 2384 |
idle_timeout=dict(type="int"), |
| 2385 |
cross_az_load_balancing=dict(type="bool"), |
| 2386 |
stickiness=dict(type="dict", options=stickiness_spec), |
| 2387 |
access_logs=dict(type="dict", options=access_log_spec), |
| 2388 |
wait=dict(default=False, type="bool"), |
| 2389 |
wait_timeout=dict(default=180, type="int"), |
| 2390 |
tags=dict(type="dict", aliases=["resource_tags"]), |
| 2391 |
purge_tags=dict(default=True, type="bool"), |
| 2392 |
) |
| 2393 |
|
| 2394 |
module = AnsibleAWSModule( |
| 2395 |
argument_spec=argument_spec, |
| 2396 |
mutually_exclusive=[ |
| 2397 |
["security_group_ids", "security_group_names"], |
| 2398 |
["zones", "subnets"], |
| 2399 |
], |
| 2400 |
supports_check_mode=True, |
| 2401 |
) |
| 2402 |
|
| 2403 |
wait_timeout = module.params["wait_timeout"] |
| 2404 |
state = module.params["state"] |
| 2405 |
|
| 2406 |
if wait_timeout > 600: |
| 2407 |
module.fail_json(msg="wait_timeout maximum is 600 seconds") |
| 2408 |
|
| 2409 |
elb_man = ElbManager(module) |
| 2410 |
elb_man.validate_params(state) |
| 2411 |
|
| 2412 |
if state == "present": |
| 2413 |
elb_man.ensure_ok() |
| 2414 |
# original boto style |
| 2415 |
elb = elb_man.get_info() |
| 2416 |
# boto3 style |
| 2417 |
lb = elb_man.get_load_balancer() |
| 2418 |
ec2_result = dict(elb=elb, load_balancer=lb) |
| 2419 |
elif state == "absent": |
| 2420 |
elb_man.ensure_gone() |
| 2421 |
# original boto style |
| 2422 |
elb = elb_man.get_info() |
| 2423 |
ec2_result = dict(elb=elb) |
| 2424 |
|
| 2425 |
module.exit_json( |
| 2426 |
changed=elb_man.changed, |
| 2427 |
**ec2_result, |
| 2428 |
) |
| 2429 |
|
| 2430 |
|
| 2431 |
if __name__ == "__main__": |
| 2432 |
main() |