1

I have a python script to get the cost of each service for the last month, but I want the cost for each resource using the tag mentioned for that resource. For example, I have got the cost for RDS service, am using two database instances, So I want to get the separate cost for two database instances . I have different tags for two database instances

TAGS:

First database instance --> Key: Name Value:rds1

Second database instance --> Key: Name Value:rds2

My output should be like , the tag of the resource and its cost

Example --> rds1 - 15$

         rds2 - 10$

Can anyone help me to achieve this ?

I have attached the ouput I got for cost based on the service

Output for cost based on service

Bhavesh R
  • 23
  • 5
  • 2
    Any reason not to use [AWS cost allocation tags](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) that's already part of AWS Billing? – jarmod Oct 21 '22 at 11:10
  • Yeah , I was trying to do that , but I don't know how to do that using python , my end goal is to get a tsv file mentioning the tag name and the cost associated with it. Can you help me out with a script – Bhavesh R Oct 22 '22 at 07:27

1 Answers1

1

Similar work you can find here Boto3 get_cost_and_usage filter Getting zero cost based on tag

Make sure that the tags that you are listing are correct.

On top of this,

import boto3

start_date = '2022-07-01'
end_date = '2022-08-30'


client = boto3.client('ce')

tags_response = None

try:
    tags_response = client.list_cost_allocation_tags(
        Status='Inactive',  # 'Active'|'Inactive',
        # TagKeys=[
        #     'Key',
        # ],
        Type='UserDefined',  # 'AWSGenerated'|'UserDefined',
        # NextToken='string',
        # MaxResults=100,
    )
except Exception as e:
    print(e)

cost_allocation_tags = tags_response['CostAllocationTags']
print(cost_allocation_tags)

print("-"*5+' Input TagValues with comma separation '+"-"*5)

for cost_allocation_tag in cost_allocation_tags:

    tag_key = cost_allocation_tag['TagKey']
    tag_type = cost_allocation_tag['Type']
    tag_status = cost_allocation_tag['Status']

    tag_values = str(input(
        f'TagKey: {tag_key}, Type: {tag_type}, Status: {tag_status} -> '))

    if tag_values == "":
        continue
    tag_values_parsed = tag_values.strip().split(',')
    if tag_values_parsed == []:
        continue

    cost_usage_response = None
    try:
        cost_usage_response = client.get_cost_and_usage(
            TimePeriod={
                'Start': start_date,
                'End': end_date
            },
            Metrics=['AmortizedCost'],
            Granularity='MONTHLY',  # 'DAILY'|'MONTHLY'|'HOURLY',
            Filter={
                'Tags': {
                    'Key': tag_key,
                    'Values': tag_values_parsed,
                    'MatchOptions': [
                        'EQUALS'  # 'EQUALS'|'ABSENT'|'STARTS_WITH'|'ENDS_WITH'|'CONTAINS'|'CASE_SENSITIVE'|'CASE_INSENSITIVE',
                    ]
                },
            },
            # GroupBy=[
            #     {
            #         'Type': 'SERVICE',  # 'DIMENSION'|'TAG'|'COST_CATEGORY',  # AZ, INSTANCE_TYPE, LEGAL_ENTITY_NAME, INVOICING_ENTITY, LINKED_ACCOUNT, OPERATION, PLATFORM, PURCHASE_TYPE, SERVICE, TENANCY, RECORD_TYPE , and USAGE_TYPE
            #         'Key': 'string',
            #     },
            # ],
        )
        print(cost_usage_response)
    except Exception as e:
        print(e)
Zeeshan
  • 357
  • 1
  • 8
  • Yeah I tried this way , But I want to be this in a dynamic way , so that I don't want to hardcode my tags . Like I have to get all tags so that I will pass all the tags dynamically and get my output – Bhavesh R Oct 22 '22 at 07:36
  • Solved , thank you . I used get_tags api to get the tags. Then got the cost using the tag name ,like the code bef you updated – Bhavesh R Oct 22 '22 at 13:35