How to use Boto3 to add tags in AWS Glue Resources

AWSBoto3PythonServer Side ProgrammingProgramming

In this article, we will see how a user can add tags in AWS Glue Resources.

Example

Add tags “glue-db: tests” in AWS glue database.

 Problem Statement: Use boto3 library in Python to add tags in AWS Glue Resources.

Approach/Algorithm to solve this problem

  • Step 1: Import boto3 and botocore exceptions to handle exceptions.

  • Step 2: resource_arn and tags_dict are the required parameters in this function.

The format of resource_arn should be as following −

Catalogarn:aws:glue:region:account-id:catalog
Databasearn:aws:glue:region:account-id:database/database name
Tablearn:aws:glue:region:account-id:table/database name/table name
Connectionarn:aws:glue:region:account-id:connection/connection name
Crawlerarn:aws:glue:region:account-id:crawler/crawler-name
Jobarn:aws:glue:region:account-id:job/job-name
Triggerarn:aws:glue:region:account-id:trigger/trigger-name
Development endpointarn:aws:glue:region:account-id:devEndpoint/development-endpoint-name
Machine learning transformarn:aws:glue:region:account-id:mlTransform/transform-id

tags_dict should be as {“key”:”value”,..}

  • Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.

  • Step 4: Create an AWS client for glue.

  • Step 5: Now use the tag_resource function and pass the parameter resource_arn as ResourceArn and tags_dict as TagsToAdd.

  • Step 6: It returns the response metadata and adds tags in the resources.

  • Step 7: Handle the generic exception if something went wrong while adding tags.

Example Code

Use the following code to add tag −

import boto3
from botocore.exceptions import ClientError

def add_tags_in_resource(resource_arn, tags_dict)
   session = boto3.session.Session()
   glue_client = session.client('glue')
   try:
      response = glue_client.tag_resource(ResourceArn= resource_arn,TagsToAdd=tags_dict)
      return response
   except ClientError as e:
      raise Exception("boto3 client error in add_tags_in_resource: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in add_tags_in_resource: " + e.__str__())
tags_dict = {"glue-db":"test"}
print(add_tags_in_resource("arn:aws:glue:us-east-1:1122225*****88:database/test- db",tags_dict))

Output

{'ResponseMetadata': {'RequestId': 'c9f418b0-***************-fb96', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Fri, 02 Apr 2021 08:04:54 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '27', 'connection': 'keep-alive', 'x-amzn-requestid': 'c9f418b0-******************-fb96'}, 'RetryAttempts': 0}}
raja
Published on 15-Apr-2021 13:04:13
Advertisements