|
4 | 4 | import requests |
5 | 5 | from .logger import logger |
6 | 6 | from eksrollup.config import app_config |
| 7 | +from .k8s import get_k8s_nodes, get_node_by_instance_id |
7 | 8 |
|
8 | 9 | client = boto3.client('autoscaling') |
9 | 10 | ec2_client = boto3.client('ec2') |
@@ -420,16 +421,28 @@ def get_asg_tag(tags, tag_name): |
420 | 421 | return result |
421 | 422 |
|
422 | 423 |
|
423 | | -def count_all_cluster_instances(cluster_name, predictive=False): |
| 424 | +def count_all_cluster_instances(cluster_name, predictive=False, exclude_node_label_keys=app_config["EXCLUDE_NODE_LABEL_KEYS"]): |
424 | 425 | """ |
425 | 426 | Returns the total number of ec2 instances in a k8s cluster |
426 | 427 | """ |
| 428 | + |
| 429 | + # Get the K8s nodes on the cluster, while excluding nodes with certain label keys |
| 430 | + k8s_nodes = get_k8s_nodes(exclude_node_label_keys) |
| 431 | + |
427 | 432 | count = 0 |
428 | 433 | asgs = get_all_asgs(cluster_name) |
429 | 434 | for asg in asgs: |
| 435 | + instances = asg['Instances'] |
430 | 436 | if predictive: |
431 | 437 | count += asg['DesiredCapacity'] |
432 | 438 | else: |
433 | | - count += len(asg['Instances']) |
| 439 | + # Use the get_node_by_instance_id() function as it only returns the node if it is not excluded by K8s labels |
| 440 | + for instance in instances: |
| 441 | + instance_id = instance['InstanceId'] |
| 442 | + try: |
| 443 | + get_node_by_instance_id(k8s_nodes, instance_id) |
| 444 | + count += 1 |
| 445 | + except: |
| 446 | + logger.info("Skipping instance {}".format(instance_id)) |
434 | 447 | logger.info("{} asg instance count in cluster is: {}. K8s node count should match this number".format("*** Predicted" if predictive else "Current", count)) |
435 | 448 | return count |
0 commit comments