How to use Boto3 to remove tags in specified AWS secrets

Problem Statement: Use boto3 library in Python to remove tags in AWS secret.

Approach/Algorithm to solve this problem

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

  • Step 2: secret_location and tags_list are the required parameters in this function. tags_list should be the list of keys to be untaged.

  • 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 secretmanager.

  • Step 5: Now use the untag_resource function and pass the parameter secret_location as SecretId and tags_list as TagKeys.

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

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

Example Code

Use the following code to remove tags −

import boto3
from botocore.exceptions import ClientError

def remove_tags_in_resource(secret_location, tags_list)
   session = boto3.session.Session()
   client = session.client('secretmanager')
      response = client.untag_resource(SecretId= secret_location,TagKeys=tags_list)
   return response
   except ClientError as e:
      raise Exception("boto3 client error in remove_tags_in_resource: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in remove_tags_in_resource: " + e.__str__())

tags_dict = ["secret-test"]


{'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}}

Updated on: 16-Apr-2021


Kickstart Your Career

Get certified by completing the course

Get Started