| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2018, Yaakov Kuperman <[email protected]> |
| 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_info |
| 10 |
version_added: 1.0.0 |
| 11 |
short_description: Gathers which target groups a target is associated with. |
| 12 |
description: |
| 13 |
- This module will search through every target group in a region to find |
| 14 |
which ones have registered a given instance ID or IP. |
| 15 |
author: |
| 16 |
- "Yaakov Kuperman (@yaakov-github)" |
| 17 |
options: |
| 18 |
instance_id: |
| 19 |
description: |
| 20 |
- What instance ID to get information for. |
| 21 |
type: str |
| 22 |
required: true |
| 23 |
get_unused_target_groups: |
| 24 |
description: |
| 25 |
- Whether or not to get target groups not used by any load balancers. |
| 26 |
type: bool |
| 27 |
default: true |
| 28 |
|
| 29 |
extends_documentation_fragment: |
| 30 |
- amazon.aws.common.modules |
| 31 |
- amazon.aws.region.modules |
| 32 |
- amazon.aws.boto3 |
| 33 |
""" |
| 34 |
|
| 35 |
EXAMPLES = r""" |
| 36 |
# practical use case - dynamically de-registering and re-registering nodes |
| 37 |
|
| 38 |
- name: Get EC2 Metadata |
| 39 |
amazon.aws.ec2_metadata_facts: |
| 40 |
|
| 41 |
- name: Get initial list of target groups |
| 42 |
delegate_to: localhost |
| 43 |
community.aws.elb_target_info: |
| 44 |
instance_id: "{{ ansible_ec2_instance_id }}" |
| 45 |
region: "{{ ansible_ec2_placement_region }}" |
| 46 |
register: target_info |
| 47 |
|
| 48 |
- name: save fact for later |
| 49 |
ansible.builtin.set_fact: |
| 50 |
original_tgs: "{{ target_info.instance_target_groups }}" |
| 51 |
|
| 52 |
- name: Deregister instance from all target groups |
| 53 |
delegate_to: localhost |
| 54 |
community.aws.elb_target: |
| 55 |
target_group_arn: "{{ item.0.target_group_arn }}" |
| 56 |
target_port: "{{ item.1.target_port }}" |
| 57 |
target_az: "{{ item.1.target_az }}" |
| 58 |
target_id: "{{ item.1.target_id }}" |
| 59 |
state: absent |
| 60 |
target_status: "draining" |
| 61 |
region: "{{ ansible_ec2_placement_region }}" |
| 62 |
with_subelements: |
| 63 |
- "{{ original_tgs }}" |
| 64 |
- "targets" |
| 65 |
|
| 66 |
# This avoids having to wait for 'elb_target' to serially deregister each |
| 67 |
# target group. An alternative would be to run all of the 'elb_target' |
| 68 |
# tasks async and wait for them to finish. |
| 69 |
|
| 70 |
- name: wait for all targets to deregister simultaneously |
| 71 |
delegate_to: localhost |
| 72 |
community.aws.elb_target_info: |
| 73 |
get_unused_target_groups: false |
| 74 |
instance_id: "{{ ansible_ec2_instance_id }}" |
| 75 |
region: "{{ ansible_ec2_placement_region }}" |
| 76 |
register: target_info |
| 77 |
until: (target_info.instance_target_groups | length) == 0 |
| 78 |
retries: 60 |
| 79 |
delay: 10 |
| 80 |
|
| 81 |
- name: reregister in elbv2s |
| 82 |
community.aws.elb_target: |
| 83 |
region: "{{ ansible_ec2_placement_region }}" |
| 84 |
target_group_arn: "{{ item.0.target_group_arn }}" |
| 85 |
target_port: "{{ item.1.target_port }}" |
| 86 |
target_az: "{{ item.1.target_az }}" |
| 87 |
target_id: "{{ item.1.target_id }}" |
| 88 |
state: present |
| 89 |
target_status: "initial" |
| 90 |
with_subelements: |
| 91 |
- "{{ original_tgs }}" |
| 92 |
- "targets" |
| 93 |
|
| 94 |
# wait until all groups associated with this instance are 'healthy' or |
| 95 |
# 'unused' |
| 96 |
- name: wait for registration |
| 97 |
community.aws.elb_target_info: |
| 98 |
get_unused_target_groups: false |
| 99 |
instance_id: "{{ ansible_ec2_instance_id }}" |
| 100 |
region: "{{ ansible_ec2_placement_region }}" |
| 101 |
register: target_info |
| 102 |
until: (target_info.instance_target_groups | |
| 103 |
map(attribute='targets') | |
| 104 |
flatten | |
| 105 |
map(attribute='target_health') | |
| 106 |
rejectattr('state', 'equalto', 'healthy') | |
| 107 |
rejectattr('state', 'equalto', 'unused') | |
| 108 |
list | |
| 109 |
length) == 0 |
| 110 |
retries: 61 |
| 111 |
delay: 10 |
| 112 |
|
| 113 |
# using the target groups to generate AWS CLI commands to reregister the |
| 114 |
# instance - useful in case the playbook fails mid-run and manual |
| 115 |
# rollback is required |
| 116 |
- name: "reregistration commands: ELBv2s" |
| 117 |
ansible.builtin.debug: |
| 118 |
msg: > |
| 119 |
aws --region {{ansible_ec2_placement_region}} elbv2 |
| 120 |
register-targets --target-group-arn {{item.target_group_arn}} |
| 121 |
--targets{%for target in item.targets%} |
| 122 |
Id={{target.target_id}}, |
| 123 |
Port={{target.target_port}}{%if target.target_az%},AvailabilityZone={{target.target_az}} |
| 124 |
{%endif%} |
| 125 |
{%endfor%} |
| 126 |
loop: "{{target_info.instance_target_groups}}" |
| 127 |
""" |
| 128 |
|
| 129 |
RETURN = r""" |
| 130 |
instance_target_groups: |
| 131 |
description: a list of target groups to which the instance is registered to |
| 132 |
returned: always |
| 133 |
type: complex |
| 134 |
contains: |
| 135 |
target_group_arn: |
| 136 |
description: The ARN of the target group |
| 137 |
type: str |
| 138 |
returned: always |
| 139 |
sample: |
| 140 |
- "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/target-group/deadbeefdeadbeef" |
| 141 |
target_group_type: |
| 142 |
description: Which target type is used for this group |
| 143 |
returned: always |
| 144 |
type: str |
| 145 |
sample: |
| 146 |
- ip |
| 147 |
- instance |
| 148 |
targets: |
| 149 |
description: A list of targets that point to this instance ID |
| 150 |
returned: always |
| 151 |
type: complex |
| 152 |
contains: |
| 153 |
target_id: |
| 154 |
description: the target ID referring to this instance |
| 155 |
type: str |
| 156 |
returned: always |
| 157 |
sample: |
| 158 |
- i-deadbeef |
| 159 |
- 1.2.3.4 |
| 160 |
target_port: |
| 161 |
description: which port this target is listening on |
| 162 |
type: str |
| 163 |
returned: always |
| 164 |
sample: |
| 165 |
- 80 |
| 166 |
target_az: |
| 167 |
description: which availability zone is explicitly |
| 168 |
associated with this target |
| 169 |
type: str |
| 170 |
returned: when an AZ is associated with this instance |
| 171 |
sample: |
| 172 |
- us-west-2a |
| 173 |
target_health: |
| 174 |
description: |
| 175 |
- The target health description. |
| 176 |
- See following link for all the possible values |
| 177 |
U(https://boto3.readthedocs.io/en/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.describe_target_health) |
| 178 |
returned: always |
| 179 |
type: complex |
| 180 |
contains: |
| 181 |
description: |
| 182 |
description: description of target health |
| 183 |
returned: if I(state!=present) |
| 184 |
sample: |
| 185 |
- "Target desregistration is in progress" |
| 186 |
type: str |
| 187 |
reason: |
| 188 |
description: reason code for target health |
| 189 |
returned: if I(state!=healthy) |
| 190 |
sample: |
| 191 |
- "Target.Deregistration in progress" |
| 192 |
type: str |
| 193 |
state: |
| 194 |
description: health state |
| 195 |
returned: always |
| 196 |
sample: |
| 197 |
- "healthy" |
| 198 |
- "draining" |
| 199 |
- "initial" |
| 200 |
- "unhealthy" |
| 201 |
- "unused" |
| 202 |
- "unavailable" |
| 203 |
type: str |
| 204 |
""" |
| 205 |
|
| 206 |
try: |
| 207 |
from botocore.exceptions import BotoCoreError |
| 208 |
from botocore.exceptions import ClientError |
| 209 |
except ImportError: |
| 210 |
# we can handle the lack of boto3 based on the ec2 module |
| 211 |
pass |
| 212 |
|
| 213 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 214 |
|
| 215 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 216 |
|
| 217 |
from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule |
| 218 |
|
| 219 |
|
| 220 |
class Target(object): |
| 221 |
"""Models a target in a target group""" |
| 222 |
|
| 223 |
def __init__(self, target_id, port, az, raw_target_health): |
| 224 |
self.target_port = port |
| 225 |
self.target_id = target_id |
| 226 |
self.target_az = az |
| 227 |
self.target_health = self.convert_target_health(raw_target_health) |
| 228 |
|
| 229 |
def convert_target_health(self, raw_target_health): |
| 230 |
return camel_dict_to_snake_dict(raw_target_health) |
| 231 |
|
| 232 |
|
| 233 |
class TargetGroup(object): |
| 234 |
"""Models an elbv2 target group""" |
| 235 |
|
| 236 |
def __init__(self, **kwargs): |
| 237 |
self.target_group_type = kwargs["target_group_type"] |
| 238 |
self.target_group_arn = kwargs["target_group_arn"] |
| 239 |
# the relevant targets associated with this group |
| 240 |
self.targets = [] |
| 241 |
|
| 242 |
def add_target(self, target_id, target_port, target_az, raw_target_health): |
| 243 |
self.targets.append(Target(target_id, target_port, target_az, raw_target_health)) |
| 244 |
|
| 245 |
def to_dict(self): |
| 246 |
object_dict = vars(self) |
| 247 |
object_dict["targets"] = [vars(each) for each in self.get_targets()] |
| 248 |
return object_dict |
| 249 |
|
| 250 |
def get_targets(self): |
| 251 |
return list(self.targets) |
| 252 |
|
| 253 |
|
| 254 |
class TargetInfoGatherer(object): |
| 255 |
def __init__(self, module, instance_id, get_unused_target_groups): |
| 256 |
self.module = module |
| 257 |
try: |
| 258 |
self.ec2 = self.module.client("ec2", retry_decorator=AWSRetry.jittered_backoff(retries=10)) |
| 259 |
except (ClientError, BotoCoreError) as e: |
| 260 |
self.module.fail_json_aws(e, msg="Couldn't connect to ec2") |
| 261 |
|
| 262 |
try: |
| 263 |
self.elbv2 = self.module.client("elbv2", retry_decorator=AWSRetry.jittered_backoff(retries=10)) |
| 264 |
except (BotoCoreError, ClientError) as e: |
| 265 |
self.module.fail_json_aws(e, msg="Could not connect to elbv2") |
| 266 |
|
| 267 |
self.instance_id = instance_id |
| 268 |
self.get_unused_target_groups = get_unused_target_groups |
| 269 |
self.tgs = self._get_target_groups() |
| 270 |
|
| 271 |
def _get_instance_ips(self): |
| 272 |
"""Fetch all IPs associated with this instance so that we can determine |
| 273 |
whether or not an instance is in an IP-based target group""" |
| 274 |
try: |
| 275 |
# get ahold of the instance in the API |
| 276 |
reservations = self.ec2.describe_instances(InstanceIds=[self.instance_id], aws_retry=True)["Reservations"] |
| 277 |
except (BotoCoreError, ClientError) as e: |
| 278 |
# typically this will happen if the instance doesn't exist |
| 279 |
self.module.fail_json_aws( |
| 280 |
e, |
| 281 |
msg=f"Could not get instance info for instance '{self.instance_id}'", |
| 282 |
) |
| 283 |
|
| 284 |
if len(reservations) < 1: |
| 285 |
self.module.fail_json(msg=f"Instance ID {self.instance_id} could not be found") |
| 286 |
|
| 287 |
instance = reservations[0]["Instances"][0] |
| 288 |
|
| 289 |
# IPs are represented in a few places in the API, this should |
| 290 |
# account for all of them |
| 291 |
ips = set() |
| 292 |
ips.add(instance["PrivateIpAddress"]) |
| 293 |
for nic in instance["NetworkInterfaces"]: |
| 294 |
ips.add(nic["PrivateIpAddress"]) |
| 295 |
for ip in nic["PrivateIpAddresses"]: |
| 296 |
ips.add(ip["PrivateIpAddress"]) |
| 297 |
|
| 298 |
return list(ips) |
| 299 |
|
| 300 |
def _get_target_group_objects(self): |
| 301 |
"""helper function to build a list of TargetGroup objects based on |
| 302 |
the AWS API""" |
| 303 |
try: |
| 304 |
paginator = self.elbv2.get_paginator("describe_target_groups") |
| 305 |
tg_response = paginator.paginate().build_full_result() |
| 306 |
except (BotoCoreError, ClientError) as e: |
| 307 |
self.module.fail_json_aws( |
| 308 |
e, |
| 309 |
msg="Could not describe target groups", |
| 310 |
) |
| 311 |
|
| 312 |
# build list of TargetGroup objects representing every target group in |
| 313 |
# the system |
| 314 |
target_groups = [] |
| 315 |
for each_tg in tg_response["TargetGroups"]: |
| 316 |
if not self.get_unused_target_groups and len(each_tg["LoadBalancerArns"]) < 1: |
| 317 |
# only collect target groups that actually are connected |
| 318 |
# to LBs |
| 319 |
continue |
| 320 |
|
| 321 |
target_groups.append( |
| 322 |
TargetGroup( |
| 323 |
target_group_arn=each_tg["TargetGroupArn"], |
| 324 |
target_group_type=each_tg["TargetType"], |
| 325 |
) |
| 326 |
) |
| 327 |
return target_groups |
| 328 |
|
| 329 |
def _get_target_descriptions(self, target_groups): |
| 330 |
"""Helper function to build a list of all the target descriptions |
| 331 |
for this target in a target group""" |
| 332 |
# Build a list of all the target groups pointing to this instance |
| 333 |
# based on the previous list |
| 334 |
tgs = set() |
| 335 |
# Loop through all the target groups |
| 336 |
for tg in target_groups: |
| 337 |
try: |
| 338 |
# Get the list of targets for that target group |
| 339 |
response = self.elbv2.describe_target_health(TargetGroupArn=tg.target_group_arn, aws_retry=True) |
| 340 |
except (BotoCoreError, ClientError) as e: |
| 341 |
self.module.fail_json_aws( |
| 342 |
e, msg="Could not describe target " + f"health for target group {tg.target_group_arn}" |
| 343 |
) |
| 344 |
|
| 345 |
for t in response["TargetHealthDescriptions"]: |
| 346 |
# If the target group has this instance as a target, add to |
| 347 |
# list. This logic also accounts for the possibility of a |
| 348 |
# target being in the target group multiple times with |
| 349 |
# overridden ports |
| 350 |
if t["Target"]["Id"] == self.instance_id or t["Target"]["Id"] in self.instance_ips: |
| 351 |
# The 'AvailabilityZone' parameter is a weird one, see the |
| 352 |
# API docs for more. Basically it's only supposed to be |
| 353 |
# there under very specific circumstances, so we need |
| 354 |
# to account for that |
| 355 |
az = t["Target"]["AvailabilityZone"] if "AvailabilityZone" in t["Target"] else None |
| 356 |
|
| 357 |
tg.add_target(t["Target"]["Id"], t["Target"]["Port"], az, t["TargetHealth"]) |
| 358 |
# since tgs is a set, each target group will be added only |
| 359 |
# once, even though we call add on each successful match |
| 360 |
tgs.add(tg) |
| 361 |
return list(tgs) |
| 362 |
|
| 363 |
def _get_target_groups(self): |
| 364 |
# do this first since we need the IPs later on in this function |
| 365 |
self.instance_ips = self._get_instance_ips() |
| 366 |
|
| 367 |
# build list of target groups |
| 368 |
target_groups = self._get_target_group_objects() |
| 369 |
return self._get_target_descriptions(target_groups) |
| 370 |
|
| 371 |
|
| 372 |
def main(): |
| 373 |
argument_spec = dict( |
| 374 |
instance_id={"required": True, "type": "str"}, |
| 375 |
get_unused_target_groups={"required": False, "default": True, "type": "bool"}, |
| 376 |
) |
| 377 |
|
| 378 |
module = AnsibleAWSModule( |
| 379 |
argument_spec=argument_spec, |
| 380 |
supports_check_mode=True, |
| 381 |
) |
| 382 |
|
| 383 |
instance_id = module.params["instance_id"] |
| 384 |
get_unused_target_groups = module.params["get_unused_target_groups"] |
| 385 |
|
| 386 |
tg_gatherer = TargetInfoGatherer(module, instance_id, get_unused_target_groups) |
| 387 |
|
| 388 |
instance_target_groups = [each.to_dict() for each in tg_gatherer.tgs] |
| 389 |
|
| 390 |
module.exit_json(instance_target_groups=instance_target_groups) |
| 391 |
|
| 392 |
|
| 393 |
if __name__ == "__main__": |
| 394 |
main() |