Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python Boto3로 AWS Glue 리소스 태그 제거하는 방법 완벽 가이드

이 글에서는 Python의 boto3 라이브러리를 사용하여 AWS Glue 리소스에서 태그를 제거하는 방법을 단계별로 알아봅니다.

예제 시나리오

AWS Glue 데이터베이스에 설정된 태그 "glue-db: tests"를 제거하는 작업을 진행해 보겠습니다.

문제 정의: Python에서 boto3 라이브러리를 활용하여 AWS Glue 리소스의 태그를 제거합니다.

문제 해결 접근 방식

  • 1단계: 예외 처리를 위해 boto3botocore의 예외 모듈을 임포트합니다.

  • 2단계: 이 함수에는 resource_arn(리소스 ARN)과 tags_list(태그 목록) 두 가지 필수 파라미터가 필요합니다.

resource_arn은 리소스 종류에 따라 다음과 같은 형식을 따라야 합니다.

Catalog(카탈로그)arn:aws:glue:region:account-id:catalog
Database(데이터베이스)arn:aws:glue:region:account-id:database/database name
Table(테이블)arn:aws:glue:region:account-id:table/database name/table name
Connection(연결)arn:aws:glue:region:account-id:connection/connection name
Crawler(크롤러)arn:aws:glue:region:account-id:crawler/crawler-name
Job(작업)arn:aws:glue:region:account-id:job/job-name
Trigger(트리거)arn:aws:glue:region:account-id:trigger/trigger-name
Development endpoint(개발 엔드포인트)arn:aws:glue:region:account-id:devEndpoint/development-endpoint-name
Machine learning transform(ML 변환)arn:aws:glue:region:account-id:mlTransform/transform-id

tags_list는 ["key1", "key2"...] 형태의 키 문자열 배열로 전달합니다.

  • 3단계: boto3 라이브러리로 AWS 세션을 생성합니다. 기본 프로필에 region_name이 설정되어 있는지 확인하고, 설정되어 있지 않다면 세션 생성 시 명시적으로 리전 이름을 전달해야 합니다.

  • 4단계: glue 서비스를 위한 AWS 클라이언트를 생성합니다.

  • 5단계: untag_resource 함수를 호출하면서 resource_arn은 ResourceArn 파라미터에, tags_list는 TagsToRemove 파라미터에 각각 전달합니다.

  • 6단계: 함수는 응답 메타데이터를 반환하고 해당 리소스에서 지정된 태그를 제거합니다.

  • 7단계: 태그 제거 중 오류가 발생할 경우 일반 예외를 처리합니다.

예제 코드

아래 코드를 사용하여 태그를 제거할 수 있습니다.

import boto3
from botocore.exceptions import ClientError

def remove_tags_in_resource(resource_arn, tags_list):
    session = boto3.session.Session()
    glue_client = session.client('glue')
    try:
        response = glue_client.untag_resource(ResourceArn=resource_arn, TagsToRemove=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_list = ["glue-db"]
print(remove_tags_in_resource("arn:aws:glue:us-east-1:1122225*****88:database/test-db", tags_list))

실행 결과

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

HTTP 상태 코드 200이 반환되면 태그가 성공적으로 제거된 것입니다. 이처럼 boto3의 untag_resource 함수를 활용하면 Glue 데이터베이스, 테이블, 크롤러, 작업 등 다양한 리소스의 태그를 손쉽게 관리할 수 있습니다.