Skip to content

Instantly share code, notes, and snippets.

@sean-smith
Created April 12, 2023 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sean-smith/939a5f096048aa630a8fb2acc9a96e05 to your computer and use it in GitHub Desktop.
Save sean-smith/939a5f096048aa630a8fb2acc9a96e05 to your computer and use it in GitHub Desktop.
Activate cost allocation tags and check on the status of them programatically

Activate AWS Tags in Cost Explorer

CLI

aws ce update-cost-allocation-tags-status —cost-allocation-tags-status="TagKey='parallelcluster:cluster-name',Status='activate'"
aws ce list-cost-allocation-tags --tag-keys='parallelcluster:cluster-name'
{
    "CostAllocationTags": [
        {
            "TagKey": "parallelcluster:cluster-name",
            "Type": "UserDefined",
            "Status": "Active"
        }
    ]
}

Python

#!/usr/bin/python3
import boto3

PCLUSTER_COST_TAGS = ['parallelcluster:attributes', 
    'parallelcluster:cluster-name', 'parallelcluster:compute-resource-name', 'parallelcluster:filesystem', 
    'parallelcluster:networking', 'parallelcluster:node-type', 'parallelcluster:queue-name', 
    'parallelcluster:resource', 'parallelcluster:version']
    
def check_tags():
    cost_explorer = boto3.client('ce')
    inactive_tags = cost_explorer.list_cost_allocation_tags(Status='Inactive',TagKeys=PCLUSTER_COST_TAGS)
    try:
        return {'TagStatus': not (len(inactive_tags['CostAllocationTags']) > 0)}
    except Exception as e:
        return {"message": str(e)}, 500

def activate_tags():
    try:
        cost_explorer = boto3.client('ce')
        newlist = [{'TagKey': tag, 'Status': 'Active'} for tag in PCLUSTER_COST_TAGS]
        cost_explorer.update_cost_allocation_tags_status(CostAllocationTagsStatus=newlist)
        return {"message": "Activated Tags"}
    except Exception as e:
        return {"message": str(e)}, 500
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment