0

I have the following lambda function that add an expiryDate tag to untagged opensearch Domains

import boto3
import datetime

def lambda_handler(event, context):
    # Get a list of all AWS regions
    ec2_client = boto3.client('ec2', region_name='us-east-1')  # Choose a default region to get all regions
    regions = [region['RegionName'] for region in ec2_client.describe_regions()['Regions']]

    for region in regions:
        opensearch_client = boto3.client('opensearch', region_name=region)
        domains = opensearch_client.list_domain_names()['DomainNames']

        for domain in domains:
            domain_name = domain['DomainName']
            tags = boto3.client('resourcegroupstaggingapi').get_resources(
                TagFilters=[
                    {'Key': 'domainName', 'Values': [domain_name]},
                    {'Key': 'service', 'Values': ['es']}
                ],
                ResourcesPerPage=50
            )['ResourceTagMappingList']

            # Check if the 'expiryDate' tag already exists
            expiryDate_tag = next((tag for tag in tags if tag['Tags'].get('expiryDate')), None)
            if not expiryDate_tag:
                # Apply tags to the OpenSearch domain if the 'expiryDate' tag doesn't exist
                future_date = datetime.datetime.now() + datetime.timedelta(days=60)
                future_date_str = future_date.strftime('%d-%m-%Y')
                boto3.client('resourcegroupstaggingapi').tag_resources(
                    ResourceARNList=[f"arn:aws:es:{region}:{boto3.client('sts').get_caller_identity().get('Account')}:domain/{domain_name}"],
                    Tags={
                        'expiryDate': future_date_str
                    }
                )
                print(f"Tags applied successfully to OpenSearch domain {domain_name} in region {region}.")
            else:
                print(f"OpenSearch domain {domain_name} in region {region} already has the expiryDate tag.")

    return {
        'statusCode': 200,
        'body': 'Processing completed for all OpenSearch domains in all regions.'
    }

I'm working on a function that will validate the expiryDate and erase the Domain if the date is in the past.

Here's the function:

import boto3
import datetime

def lambda_handler(event, context):
    # Get a list of all AWS regions
    ec2_client = boto3.client('ec2', region_name='us-east-1')  # Choose a default region to get all regions
    regions = [region['RegionName'] for region in ec2_client.describe_regions()['Regions']]

    for region in regions:
        opensearch_client = boto3.client('opensearch', region_name=region)
        domains = opensearch_client.list_domain_names()['DomainNames']

        for domain in domains:
            domain_name = domain['DomainName']
            tags = boto3.client('resourcegroupstaggingapi').get_resources(
                TagFilters=[
                    {'Key': 'domainName', 'Values': [domain_name]},
                    {'Key': 'service', 'Values': ['es']}
                ],
                ResourcesPerPage=50
            )['ResourceTagMappingList']

            # Check if the 'expiryDate' tag exists
            expiry_date_tag = next((tag for tag in tags if tag['Tags'].get('expiryDate')), None)
            if expiry_date_tag:
                expiry_date_str = expiry_date_tag['Tags']['expiryDate']
                expiry_date = datetime.datetime.strptime(expiry_date_str, '%d-%m-%Y')
                current_date = datetime.datetime.now()
                print(f"Expiry date for domain {domain_name} in region {region}: {expiry_date_str}")
                print(f"Current date: {current_date}")

                if expiry_date < current_date:
                    # Delete the OpenSearch domain if the expiry date is in the past
                    opensearch_client.delete_domain(DomainName=domain_name)
                    print(f"OpenSearch domain {domain_name} in region {region} has expired and was deleted.")
                else:
                    print(f"OpenSearch domain {domain_name} in region {region} is still active.")
            else:
                print(f"OpenSearch domain {domain_name} in region {region} does not have the expiryDate tag.")

    return {
        'statusCode': 200,
        'body': 'Processing completed for all OpenSearch domains in all regions.'
    }

I'm not sure why, but my test domain is not being delete. I keep getting: OpenSearch domain {domain_name} in region {region} does not have the expiryDate tag.

Can anybody lend me a hand please? What am I doing wrong?

Thanks!

I'm trying to get the expired opensearch domain deleted. The role has FullAdmin

2
  • Does your code for addition of tags work? Have you checked manually if it has added the expirydate tag to your test domain?
    – Riz
    Commented Mar 16, 2024 at 1:11
  • Thank you for your reply! Yes, the tagging lambda is working! What I was able to find is it never manages to valide the first conditional: expiry_date_tag = next((tag for tag in tags if tag['Tags'].get('expiryDate')), None) if expiry_date_tag: Commented Mar 16, 2024 at 14:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.