Last active
February 16, 2024 01:38
-
-
Save atheiman/10aec47d76c11e13a736b440d5da7777 to your computer and use it in GitHub Desktop.
Tag AWS EC2 dedicated hosts allocated by a License Manager host resource group. This code can be run as a Lambda function or directly as a Python script.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import json | |
import boto3 | |
default_region = boto3.Session().region_name | |
if default_region.startswith("us-gov-"): | |
partition = "aws-us-gov" | |
regions = ["us-gov-west-1", "us-gov-east-1"] | |
else: | |
partition = "aws" | |
regions = ["us-east-1", "us-west-2"] | |
def handler(event, context): | |
print(boto3.client("sts").get_caller_identity()["Arn"]) | |
for region in regions: | |
process_region(boto3.Session(region_name=region)) | |
def process_region(session): | |
print(session.region_name) | |
rgs = session.client("resource-groups") | |
for pg in rgs.get_paginator("list_groups").paginate( | |
Filters=[{"Name": "configuration-type", "Values": ["AWS::EC2::HostManagement"]}] | |
): | |
for hrg_arn in [g["GroupArn"] for g in pg["GroupIdentifiers"]]: | |
process_hrg(session, hrg_arn) | |
def process_hrg(session, hrg_arn): | |
print(hrg_arn) | |
rgs = session.client("resource-groups") | |
ec2 = session.client("ec2") | |
dh_ids = [] | |
for pg in rgs.get_paginator("list_group_resources").paginate(Group=hrg_arn): | |
for resource in pg["Resources"]: | |
dh_ids.append(resource["Identifier"]["ResourceArn"].split("/")[-1]) | |
if not dh_ids: | |
return | |
print(dh_ids) | |
hrg_name = hrg_arn.split("/")[-1] | |
ec2.create_tags( | |
Resources=dh_ids, | |
Tags=[ | |
{"Key": "Name", "Value": hrg_name}, | |
{"Key": "host-resource-group-arn", "Value": hrg_arn}, | |
{"Key": "host-resource-group-name", "Value": hrg_name}, | |
], | |
) | |
if __name__ == "__main__": | |
handler(None, None) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment