| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright (c) 2017 Ansible Project |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
--- |
| 9 |
module: elb_target |
| 10 |
version_added: 1.0.0 |
| 11 |
short_description: Manage a target in a target group |
| 12 |
description: |
| 13 |
- Used to register or deregister a target in a target group. |
| 14 |
author: |
| 15 |
- "Rob White (@wimnat)" |
| 16 |
options: |
| 17 |
deregister_unused: |
| 18 |
description: |
| 19 |
- The default behaviour for targets that are unused is to leave them registered. |
| 20 |
- If instead you would like to remove them set I(deregister_unused=true). |
| 21 |
default: false |
| 22 |
type: bool |
| 23 |
target_az: |
| 24 |
description: |
| 25 |
- An Availability Zone or C(all). This determines whether the target receives traffic from the load balancer nodes in the specified |
| 26 |
Availability Zone or from all enabled Availability Zones for the load balancer. This parameter is not supported if the target |
| 27 |
type of the target group is instance. |
| 28 |
type: str |
| 29 |
target_group_arn: |
| 30 |
description: |
| 31 |
- The Amazon Resource Name (ARN) of the target group. |
| 32 |
- Mutually exclusive of I(target_group_name). |
| 33 |
type: str |
| 34 |
target_group_name: |
| 35 |
description: |
| 36 |
- The name of the target group. |
| 37 |
- Mutually exclusive of I(target_group_arn). |
| 38 |
type: str |
| 39 |
target_id: |
| 40 |
description: |
| 41 |
- The ID of the target. |
| 42 |
required: true |
| 43 |
type: str |
| 44 |
target_port: |
| 45 |
description: |
| 46 |
- The port on which the target is listening. You can specify a port override. If a target is already registered, |
| 47 |
you can register it again using a different port. |
| 48 |
- The default port for a target is the port for the target group. |
| 49 |
required: false |
| 50 |
type: int |
| 51 |
target_status: |
| 52 |
description: |
| 53 |
- Blocks and waits for the target status to equal given value. For more detail on target status see |
| 54 |
U(https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-health-checks.html#target-health-states) |
| 55 |
required: false |
| 56 |
choices: [ 'initial', 'healthy', 'unhealthy', 'unused', 'draining', 'unavailable' ] |
| 57 |
type: str |
| 58 |
target_status_timeout: |
| 59 |
description: |
| 60 |
- Maximum time in seconds to wait for I(target_status) change. |
| 61 |
required: false |
| 62 |
default: 60 |
| 63 |
type: int |
| 64 |
state: |
| 65 |
description: |
| 66 |
- Register or deregister the target. |
| 67 |
required: true |
| 68 |
choices: [ 'present', 'absent' ] |
| 69 |
type: str |
| 70 |
|
| 71 |
notes: |
| 72 |
- If you specified a port override when you registered a target, you must specify both the target ID and the port when you deregister it. |
| 73 |
|
| 74 |
extends_documentation_fragment: |
| 75 |
- amazon.aws.common.modules |
| 76 |
- amazon.aws.region.modules |
| 77 |
- amazon.aws.boto3 |
| 78 |
""" |
| 79 |
|
| 80 |
EXAMPLES = r""" |
| 81 |
# Note: These examples do not set authentication details, see the AWS Guide for details. |
| 82 |
|
| 83 |
- name: Register an IP address target to a target group |
| 84 |
community.aws.elb_target: |
| 85 |
target_group_name: myiptargetgroup |
| 86 |
target_id: i-1234567 |
| 87 |
state: present |
| 88 |
|
| 89 |
- name: Register an instance target to a target group |
| 90 |
community.aws.elb_target: |
| 91 |
target_group_name: mytargetgroup |
| 92 |
target_id: i-1234567 |
| 93 |
state: present |
| 94 |
|
| 95 |
- name: Deregister a target from a target group |
| 96 |
community.aws.elb_target: |
| 97 |
target_group_name: mytargetgroup |
| 98 |
target_id: i-1234567 |
| 99 |
state: absent |
| 100 |
|
| 101 |
# Modify a target to use a different port |
| 102 |
- name: Register a target to a target group |
| 103 |
community.aws.elb_target: |
| 104 |
target_group_name: mytargetgroup |
| 105 |
target_id: i-1234567 |
| 106 |
target_port: 8080 |
| 107 |
state: present |
| 108 |
""" |
| 109 |
|
| 110 |
RETURN = r""" |
| 111 |
""" |
| 112 |
|
| 113 |
from time import sleep |
| 114 |
from time import time |
| 115 |
|
| 116 |
try: |
| 117 |
import botocore |
| 118 |
except ImportError: |
| 119 |
pass # Handled by AnsibleAWSModule |
| 120 |
|
| 121 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 122 |
|
| 123 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 124 |
|
| 125 |
from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule |
| 126 |
|
| 127 |
|
| 128 |
@AWSRetry.jittered_backoff(retries=10, delay=10, catch_extra_error_codes=["TargetGroupNotFound"]) |
| 129 |
def describe_target_groups_with_backoff(connection, tg_name): |
| 130 |
return connection.describe_target_groups(Names=[tg_name]) |
| 131 |
|
| 132 |
|
| 133 |
def convert_tg_name_to_arn(connection, module, tg_name): |
| 134 |
try: |
| 135 |
response = describe_target_groups_with_backoff(connection, tg_name) |
| 136 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 137 |
module.fail_json_aws(e, msg=f"Unable to describe target group {tg_name}") |
| 138 |
|
| 139 |
tg_arn = response["TargetGroups"][0]["TargetGroupArn"] |
| 140 |
|
| 141 |
return tg_arn |
| 142 |
|
| 143 |
|
| 144 |
@AWSRetry.jittered_backoff(retries=10, delay=10, catch_extra_error_codes=["TargetGroupNotFound"]) |
| 145 |
def describe_targets_with_backoff(connection, tg_arn, target): |
| 146 |
if target is None: |
| 147 |
tg = [] |
| 148 |
else: |
| 149 |
tg = [target] |
| 150 |
|
| 151 |
return connection.describe_target_health(TargetGroupArn=tg_arn, Targets=tg) |
| 152 |
|
| 153 |
|
| 154 |
def describe_targets(connection, module, tg_arn, target=None): |
| 155 |
""" |
| 156 |
Describe targets in a target group |
| 157 |
|
| 158 |
:param module: ansible module object |
| 159 |
:param connection: boto3 connection |
| 160 |
:param tg_arn: target group arn |
| 161 |
:param target: dictionary containing target id and port |
| 162 |
:return: |
| 163 |
""" |
| 164 |
|
| 165 |
try: |
| 166 |
targets = describe_targets_with_backoff(connection, tg_arn, target)["TargetHealthDescriptions"] |
| 167 |
if not targets: |
| 168 |
return {} |
| 169 |
return targets[0] |
| 170 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 171 |
module.fail_json_aws(e, msg=f"Unable to describe target health for target {target}") |
| 172 |
|
| 173 |
|
| 174 |
@AWSRetry.jittered_backoff(retries=10, delay=10) |
| 175 |
def register_target_with_backoff(connection, target_group_arn, target): |
| 176 |
connection.register_targets(TargetGroupArn=target_group_arn, Targets=[target]) |
| 177 |
|
| 178 |
|
| 179 |
def register_target(connection, module): |
| 180 |
""" |
| 181 |
Registers a target to a target group |
| 182 |
|
| 183 |
:param module: ansible module object |
| 184 |
:param connection: boto3 connection |
| 185 |
:return: |
| 186 |
""" |
| 187 |
|
| 188 |
target_az = module.params.get("target_az") |
| 189 |
target_group_arn = module.params.get("target_group_arn") |
| 190 |
target_id = module.params.get("target_id") |
| 191 |
target_port = module.params.get("target_port") |
| 192 |
target_status = module.params.get("target_status") |
| 193 |
target_status_timeout = module.params.get("target_status_timeout") |
| 194 |
changed = False |
| 195 |
|
| 196 |
if not target_group_arn: |
| 197 |
target_group_arn = convert_tg_name_to_arn(connection, module, module.params.get("target_group_name")) |
| 198 |
|
| 199 |
target = dict(Id=target_id) |
| 200 |
if target_az: |
| 201 |
target["AvailabilityZone"] = target_az |
| 202 |
if target_port: |
| 203 |
target["Port"] = target_port |
| 204 |
|
| 205 |
target_description = describe_targets(connection, module, target_group_arn, target) |
| 206 |
|
| 207 |
if "Reason" in target_description["TargetHealth"]: |
| 208 |
if target_description["TargetHealth"]["Reason"] == "Target.NotRegistered": |
| 209 |
try: |
| 210 |
register_target_with_backoff(connection, target_group_arn, target) |
| 211 |
changed = True |
| 212 |
if target_status: |
| 213 |
target_status_check( |
| 214 |
connection, module, target_group_arn, target, target_status, target_status_timeout |
| 215 |
) |
| 216 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 217 |
module.fail_json_aws(e, msg=f"Unable to deregister target {target}") |
| 218 |
|
| 219 |
# Get all targets for the target group |
| 220 |
target_descriptions = describe_targets(connection, module, target_group_arn) |
| 221 |
|
| 222 |
module.exit_json( |
| 223 |
changed=changed, |
| 224 |
target_health_descriptions=camel_dict_to_snake_dict(target_descriptions), |
| 225 |
target_group_arn=target_group_arn, |
| 226 |
) |
| 227 |
|
| 228 |
|
| 229 |
@AWSRetry.jittered_backoff(retries=10, delay=10) |
| 230 |
def deregister_target_with_backoff(connection, target_group_arn, target): |
| 231 |
connection.deregister_targets(TargetGroupArn=target_group_arn, Targets=[target]) |
| 232 |
|
| 233 |
|
| 234 |
def deregister_target(connection, module): |
| 235 |
""" |
| 236 |
Deregisters a target to a target group |
| 237 |
|
| 238 |
:param module: ansible module object |
| 239 |
:param connection: boto3 connection |
| 240 |
:return: |
| 241 |
""" |
| 242 |
|
| 243 |
deregister_unused = module.params.get("deregister_unused") |
| 244 |
target_group_arn = module.params.get("target_group_arn") |
| 245 |
target_id = module.params.get("target_id") |
| 246 |
target_port = module.params.get("target_port") |
| 247 |
target_status = module.params.get("target_status") |
| 248 |
target_status_timeout = module.params.get("target_status_timeout") |
| 249 |
changed = False |
| 250 |
|
| 251 |
if not target_group_arn: |
| 252 |
target_group_arn = convert_tg_name_to_arn(connection, module, module.params.get("target_group_name")) |
| 253 |
|
| 254 |
target = dict(Id=target_id) |
| 255 |
if target_port: |
| 256 |
target["Port"] = target_port |
| 257 |
|
| 258 |
target_description = describe_targets(connection, module, target_group_arn, target) |
| 259 |
current_target_state = target_description["TargetHealth"]["State"] |
| 260 |
current_target_reason = target_description["TargetHealth"].get("Reason") |
| 261 |
|
| 262 |
needs_deregister = False |
| 263 |
|
| 264 |
if deregister_unused and current_target_state == "unused": |
| 265 |
if current_target_reason != "Target.NotRegistered": |
| 266 |
needs_deregister = True |
| 267 |
elif current_target_state not in ["unused", "draining"]: |
| 268 |
needs_deregister = True |
| 269 |
|
| 270 |
if needs_deregister: |
| 271 |
try: |
| 272 |
deregister_target_with_backoff(connection, target_group_arn, target) |
| 273 |
changed = True |
| 274 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError): |
| 275 |
module.fail_json(msg=f"Unable to deregister target {target}") |
| 276 |
else: |
| 277 |
if current_target_reason != "Target.NotRegistered" and current_target_state != "draining": |
| 278 |
module.warn( |
| 279 |
warning="Your specified target has an 'unused' state but is still registered to the target group. " |
| 280 |
+ "To force deregistration use the 'deregister_unused' option." |
| 281 |
) |
| 282 |
|
| 283 |
if target_status: |
| 284 |
target_status_check(connection, module, target_group_arn, target, target_status, target_status_timeout) |
| 285 |
|
| 286 |
# Get all targets for the target group |
| 287 |
target_descriptions = describe_targets(connection, module, target_group_arn) |
| 288 |
|
| 289 |
module.exit_json( |
| 290 |
changed=changed, |
| 291 |
target_health_descriptions=camel_dict_to_snake_dict(target_descriptions), |
| 292 |
target_group_arn=target_group_arn, |
| 293 |
) |
| 294 |
|
| 295 |
|
| 296 |
def target_status_check(connection, module, target_group_arn, target, target_status, target_status_timeout): |
| 297 |
reached_state = False |
| 298 |
timeout = target_status_timeout + time() |
| 299 |
while time() < timeout: |
| 300 |
health_state = describe_targets(connection, module, target_group_arn, target)["TargetHealth"]["State"] |
| 301 |
if health_state == target_status: |
| 302 |
reached_state = True |
| 303 |
break |
| 304 |
sleep(1) |
| 305 |
if not reached_state: |
| 306 |
module.fail_json( |
| 307 |
msg=f"Status check timeout of {target_status_timeout} exceeded, last status was {health_state}: " |
| 308 |
) |
| 309 |
|
| 310 |
|
| 311 |
def main(): |
| 312 |
argument_spec = dict( |
| 313 |
deregister_unused=dict(type="bool", default=False), |
| 314 |
target_az=dict(type="str"), |
| 315 |
target_group_arn=dict(type="str"), |
| 316 |
target_group_name=dict(type="str"), |
| 317 |
target_id=dict(type="str", required=True), |
| 318 |
target_port=dict(type="int"), |
| 319 |
target_status=dict( |
| 320 |
choices=["initial", "healthy", "unhealthy", "unused", "draining", "unavailable"], type="str" |
| 321 |
), |
| 322 |
target_status_timeout=dict(type="int", default=60), |
| 323 |
state=dict(required=True, choices=["present", "absent"], type="str"), |
| 324 |
) |
| 325 |
|
| 326 |
module = AnsibleAWSModule( |
| 327 |
argument_spec=argument_spec, |
| 328 |
mutually_exclusive=[["target_group_arn", "target_group_name"]], |
| 329 |
) |
| 330 |
|
| 331 |
try: |
| 332 |
connection = module.client("elbv2") |
| 333 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 334 |
module.fail_json_aws(e, msg="Failed to connect to AWS") |
| 335 |
|
| 336 |
state = module.params.get("state") |
| 337 |
|
| 338 |
if state == "present": |
| 339 |
register_target(connection, module) |
| 340 |
else: |
| 341 |
deregister_target(connection, module) |
| 342 |
|
| 343 |
|
| 344 |
if __name__ == "__main__": |
| 345 |
main() |