English

Share with friends

Note

In this blog, we will dive deep into AWS Resource tagging - top 21 best practices to follow and common mistakes to avoid with examples.

Top 21 AWS Resource Tagging Best Practices with Examples cover image

As an additional piece of information known as metadata, AWS tags are key-value pairs that are assigned to AWS resources. Each tag is a key and value that has been generated by the user or by AWS and is used as a label against a resource.

A tag is frequently used to identify, classify, organize, filter, or manage AWS resources. For instance, you can use tags to arrange resources according to their use, type of environment, owner, etc.

Each tag has a key (such as "Name," "Environment," or "Production") and a value.

For access control purposes, these key-value pairs can be assigned to resources, for instance by utilizing tags as condition keys in IAM policies.

In the AWS Console, tags can also be crucial for resource organization because they facilitate resource searching and filtering.

Tagging resources in AWS is a fundamental practice that can greatly improve the management and organization of your cloud infrastructure.

Think of tags like labels that you can attach to your AWS resources, making it easier for you to identify, search, and manage them.

In this article, we will delve into AWS resource tagging best practices, offering you practical insights and real-life examples to help you utilize the power of tags effectively.

TAG syntax

Each tag consists of two parts:

  1. A key associated with a tag, such as CostCenter, Environment, or Project. Keep in mind that case matters while using tag keys.
  2. A tag value, such as Production or 111122223333. Tag values are case-sensitive, just like tag keys are.

Additionally, resources could be categorized using tags according to their owner, environment, purpose, or other factors.

  • Use the service console, service API, or AWS CLI for each resource to add, modify, or remove tags one resource at a time.
  • There is a cap of 50 tags per resource.
  • Each tag key for a resource must be distinct and can only have one value.
  • A tag key can only be 128 Unicode characters long in UTF-8.
  • A tag value can only be 256 Unicode characters long in UTF-8.
  • The only permitted characters are letters, integers, spaces that can be represented in UTF-8, and the hyphen (.: + = @ _ / -).
  • Resources on Amazon EC2 accept any characters.
  • Case sensitivity applies to tag keys and values. Choose a method for capitalizing tags and use it consistently across all resource kinds as a best practice.
  • Decide whether to use costcenter, Costcenter, or CostCenter, for instance and adhere to this practice throughout all tags. Avoid using tags that are similar but treat cases differently.
  • The AWS prefix is reserved for usage by AWS and is not permitted for tags. This prefix prohibits the editing or deletion of tag keys or values. Your quota of tags per resource is not affected by tags with this prefix.

Allocation Tags can be of two different types.

  • User-defined Tags: Each resource can have up to 50 user-defined tags assigned to it, which the user can utilize to specify attributes ranging from cost centers to projects.

  • AWS-defined Tags: AWS generates these tags on its own. AWS-defined Tags can be distinguished because they adhere to the key-value definition aws:createdBy.

1. Choose Meaningful Tag Names and Values

Let's start with an easy one. When it comes to tagging AWS resources, clarity is key. Use tag names and values that are easy to understand and convey relevant information about the resource.

For example, if you have EC2 instances that serve different purposes, use tags like "Environment" with values such as "Development," "Staging," or "Production".

Meaningful Tag Names and Values:

Tag Name: Environment

Tag Value: Development | Staging | Production

2. Consistency Matters

Consistency simplifies everything, and in turn, resource management. Establish a consistent tagging strategy across all your AWS resources and stick to it.

Well, for instance, if you use a "Project" tag to identify resources belonging to specific projects, ensure that all relevant resources have this tag with the appropriate project name.

Example:

Tag Name: Project

Tag Vaue: ProjectA | ProjectB | ProjectC

  • aws:ec2spot:fleet-request-id: Identifies the Amazon EC2 Spot Instance Request that launched the instance

  • aws:cloudformation:stack-name: Identifies the AWS CloudFormation stack that created the resource

  • lambda-console:blueprint: Identifies blueprint used as a template for an AWS Lambda function

  • elasticbeanstalk:environment-name: Identifies the application that created the resource

Consider naming your tags using all lowercase letters, hyphens to separate words, and a prefix to indicate the name of the company or its abbreviation.

3. Automate Tagging Whenever Possible

Manual tagging can be error-prone and time-consuming. AWS provides various automation tools, such as AWS Lambda and AWS Config rules, to help you automate tagging processes.

You might want to consider using these tools for consistent tagging of all your resources.

Example: You can create a Lambda function that tags newly created EC2 instances with relevant information based on your predefined criteria.

Automation Rule: Automatically tag new EC2 instances with an "Owner" tag, using the instance creator's IAM username as the value. Simple enough?

4. Leverage Resource Groups

AWS Resource Groups can help you quickly manage and monitor tagged resources. Create resource groups based on tags, which allows you to view and manage resources together as a logical group.

Example: Create a resource group for all EC2 instances with the "Environment" tag set to "Production" to quickly assess and manage production resources.

  • Resource Group: "Production EC2 Instances"

  • Tag Filter: Environment equals Production

5. Use Cost Allocation Tags

Cost allocation tags can help you track and analyze your AWS costs. By tagging resources with cost allocation tags, you can gain insights into which resources are contributing to your AWS bill and kill those that you no longer need.

Example: Tagging resources with a "Cost Center" tag can help finance teams allocate costs to specific departments or teams.

Cost Allocation Tags:

  • Tag Name: Cost Center

  • Tag Value: Marketing | Engineering | Sales

6. Regularly Review and Cleanup Tags

Over time, your tagging strategy may evolve, and some tags may become obsolete, or a new version drops in. Regularly review your resource tags and remove or update tags that are no longer relevant.

Example: If you decommission an EC2 instance, make sure to remove any tags associated with it to keep your resource tags accurate, like Remove the "Department" tag from decommissioned resources”.

7. Educate Your Team

Making sure that your team understands the importance of tagging and follows the tagging conventions can be greatly helpful. Training and documentation can go a long way in maintaining a consistent tagging strategy.

Example: Ensure team members tag RDS databases with the appropriate "Application" tag, indicating which application the database supports. You can do this with other DBs and backend services.

8. Monitor Tag Compliance

Use AWS Config rules to monitor and enforce tagging compliance. This makes it easy for new resources to be tagged correctly and helps maintain consistency.

Example: Create a Config rule that checks whether all newly created resources have required tags, and if not, trigger an alert or an automated tagging process.

Config Rule: Enforce the presence of a "Compliance" tag on all AWS S3 buckets, with the tag value set to "Yes" or "No."

9. Tag Policies

AWS Organizations allows you to enforce tag policies across multiple AWS accounts within your organization. With these tag policies, you can make sure that specific tags are applied to resources or enforce restrictions on tag values.

Why? This is particularly useful for maintaining consistency and compliance across a large-scale AWS environment which can easily spiral out if not well tagged.

You can define tag policies using AWS Organizations' Service Control Policies (SCPs) in JSON format. For example, you can create an SCP that enforces the presence of a specific tag on resources.

Info

There are no YAML configuration files specifically for tag policies, but you may use AWS CloudFormation to manage SCPs through YAML templates.

Example: Suppose you want to enforce a tag policy that requires all EC2 instances to have a "Project" tag. You can create an SCP in JSON format within AWS Organizations.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "EnforceEC2ProjectTag",
            "Effect": "Deny",
            "Action": "ec2:CreateTags",
            "Resource": "*",
            "Condition": {
                "StringNotEqualsIfExists": {
                    "ec2:CreateAction": "RunInstances",
                    "aws:RequestTag/Project": "true"
                }
            }
        }
    ]
}

While SCPs are managed in JSON, you can use AWS CloudFormation YAML templates to automate and manage SCPs within your organization's accounts.

10. Resource-Level Permissions with Tags

AWS Identity and Access Management (IAM) policies can be tailored to grant or deny access to AWS resources based on their tags.

You can create fine-grained access controls, allowing or denying actions on resources with specific tags.

For example, you can restrict access to resources tagged as "Production" to only a select group of users or roles.

Example: Define IAM policies that incorporate conditionals based on resource tags. Here's an example policy in JSON that allows read access to EC2 instances tagged as "Environment" equals "Production":

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "ec2:DescribeInstances",
      "Resource": "*",
      "Condition": {
        "StringEquals": {
    "ec2:ResourceTag/Environment": "Production"
        }
      }
    }
  ]
}
Info

IAM policies are usually defined in JSON, but you can use AWS CloudFormation to manage IAM roles and policies with YAML templates.

Example 2: Define an IAM policy that allows read access to S3 buckets with a specific "Department" tag value.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:ListBucket",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
    "s3:ResourceTag/Department": "Engineering"
                }
            }
        }
    ]
}

Sample tag names for resource tagging.

Source: docs.aws.amazon.com

11. AWS Cost Explorer and Tagging Strategies

AWS Cost Explorer allows you to analyze your AWS spending based on resource tags. Advanced cost allocation and reporting can help you look into cost drivers and reduce your AWS spending to what is the need of the hour.

You can set up custom cost allocation tags and leverage them to create detailed cost reports.

Info

No code is involved in using AWS Cost Explorer directly. However, you can use AWS CLI or SDKs to retrieve cost and usage data based on specific tag values programmatically.

No YAML config files are involved in using AWS Cost Explorer, but you can use AWS CloudFormation to automate cost allocation tags and billing reports.

Here how:

Use AWS CLI to get the total cost of resources tagged with "Environment" equals "Production" for the last month.

aws ce get-cost-and-usage --time-period 'Start=2023-08-01,End=2023-08-31' --granularity MONTHLY --metrics "UnblendedCost" --filter 'Dimensions=[{"Type":"TAG","Key":"Environment","Values":["Production"]}]'

12. Using AWS Resource Groups for Advanced Operations

AWS Resource Groups not only help with resource organization but also facilitate advanced automation and operations.

You can use resource groups to create custom dashboards, set up automated actions, or trigger events based on resource tags.

For example, you could automatically scale EC2 instances up or down based on the "Environment" tag.

You can use AWS SDKs (e.g., Boto3 for Python) or AWS CLI to create, manage, and perform actions on resource groups programmatically.

Note

Resource groups can be referenced in AWS CloudFormation templates for dynamic management of resource groups based on tag criteria.

Example: Use AWS SDK (e.g., Boto3) in Python to create a resource group and perform actions on resources within that group.

import boto3            
client = boto3.client('resource-groups')
response = client.create_group(
    Name='MyResourceGroup',
    Description='A group of resources tagged for special actions',
    ResourceQuery={
        'Type': 'TAG_FILTERS_1_0',
        'Query': {
            'ResourceTypeFilters': ['AWS::AllSupported'],
            'TagFilters': [
                {
                    'Key': 'Environment',
                    'Values': ['Production']
                }
            ]
        }
    }
)

13. Tagging for Resource Lifecycle Management

Tags can be crucial for managing the entire lifecycle of AWS resources. You can set up automation to automatically terminate or archive resources with specific tags that are no longer needed, helping you save some penny and maintain a tidy environment.

Automation scripts using AWS Lambda and SDKs can be written to periodically scan resources with specific tags and trigger actions like termination or archival.

Info

AWS CloudFormation can be used to define CloudWatch Events rules that trigger Lambda functions based on resource tags for lifecycle management.

Example: Using AWS Lambda to periodically scan EC2 instances with a "Temporary" tag set to "true" and terminate those instances.

import boto3
ec2 = boto3.client('ec2')

def lambda_handler(event, context):
  instances = ec2.describe_instances(Filters=[{'Name': 'tag:Temporary', 'Values': ['true']}])
  
  for reservation in instances['Reservations']:
    for instance in reservation['Instances']:
      ec2.terminate_instances(InstanceIds=[instance['InstanceId']])

14. Compliance and Audit Trails

Tagging can play a crucial role in maintaining compliance and audit trails. By tagging resources with relevant compliance information, you can quickly identify which resources adhere to specific compliance standards or regulations.

This is particularly important in industries with strict regulatory requirements.

Tags can be incorporated into scripts and automation tools that assess resource compliance and generate audit reports.

Info

You can use AWS Config rules with custom YAML templates to check for compliance based on tag values.

Example: Use AWS Config rules and custom evaluations in YAML to check for compliance based on tags. For example, ensure all RDS instances have a "Compliance" tag.

ConfigRule:
  Type: "AWS::Config::ConfigRule"
  Properties:
    ConfigRuleName: "compliance-check-rds-tags"
    Description: "Checks if RDS instances have a 'Compliance' tag"
    Source:
      Owner: AWS
      SourceIdentifier: "RDS_INSTANCE_COMPLIANCE_CHECK"
    InputParameters: {}
    Scope:
      ComplianceResourceTypes:
        - "AWS::RDS::DBInstance"
    MaximumExecutionFrequency: "TwentyFour_Hours"`

15. AWS Resource Groups with CloudFormation

You can use AWS Resource Groups in conjunction with AWS CloudFormation to create and manage infrastructure as code.

Resource Groups can be referenced in CloudFormation templates, allowing you to create and manage resource groups dynamically as part of your infrastructure provisioning process.

AWS CloudFormation templates (usually written in YAML or JSON) can reference AWS Resource Groups, allowing you to create and manage resource groups as part of your infrastructure provisioning process.

Example: Reference a resource group in a CloudFormation YAML template to dynamically manage resources within that group during stack creation or updates.

MyResourceGroup:
  Type: "AWS::ResourceGroups::Group"
  Properties:
    Name: "MyResourceGroup"
    Description: "A group of resources for my CloudFormation stack"
    ResourceQuery:
      Type: "TAG_FILTERS_1_0"
      Query:
        ResourceTypeFilters:
          - "AWS::AllSupported"
        TagFilters:
          - Key: "Environment"
            Values:
              - "Development"

16. Third-Party Integration

Many third-party AWS management and monitoring tools offer advanced tagging features and integration. These tools can provide enhanced visibility, governance, and automation capabilities using AWS tags.

Examples include AWS-native solutions like AWS Config, AWS Organizations, and AWS Resource Access Manager, as well as third-party solutions like Datadog, CloudHealth, and Splunk.

Third-party AWS management and monitoring tools may involve their own code or configuration files for tagging and integration, so check out on those tools for detailed steps.

Also, configuration for third-party tools can vary, but YAML files are commonly used for settings and policies.

17. Tagging for Security and Incident Response

Tags can be used to enhance security by identifying resources that are part of a critical application or service. In the event of a security incident, tags can be used to quickly isolate affected resources and take necessary actions.

Incident response scripts or automation can use tags to identify and isolate affected resources also, YAML files may be used to configure incident response playbooks and policies, but the tags themselves are typically set within AWS resources.

Note

While YAML configuration files are not directly used for many of these advanced tagging practices, AWS CloudFormation, which utilizes YAML templates, can be used to automate and manage various aspects of AWS resource tagging and related configurations.

18. Security Risk Management Tags

Tags can be applied to resources to indicate those that need more stringent security risk management procedures, such as Amazon EC2 instances hosting applications that handle confidential or sensitive data.

Automated compliance checks can be made possible by this to guarantee that the right access restrictions are in place, patch compliance is current, etc.

19. Less is more when starting small.

Because tagging decisions are reversible, you can amend or modify them as necessary in the future. As a result, if you add a new cost allocation tag, it becomes effective immediately.

Previous reports on cost allocation will not be covered by the new tag.

A new tag can be assigned to a group of resources in bulk, but first, you must decide which resources need it and what value to give them.

Create new tags as needed, starting with a smaller collection of tags that are known to be necessary.

This method is advised against specifying an excessive number of tags that may not be required in the near future.

20. Keep Multi-Valued Cost Allocation Tags to a Minimum

You might need to divide the cost of shared resources among numerous apps, initiatives, or departments. Making multi-valued tags with a number of allocation codes and maybe matching allocation ratios is one method of assigning costs.

An illustration would be:

anycompany:cost-center = 1600|0.25|1625|0.20|1731|0.50|1744|0.05 

21. Take Action on Untagged Resources

Although crucial, proactive tag management and automation are not always successful. To find resources that are incorrectly classified and fix them, several clients also use reactive tag governance techniques.

Reactive tag governance techniques include (1) employing tools programmatically, such as the Resource Tagging API, AWS Config rules, and custom scripts; and (2) using the Tag Editor and thorough billing reports.

Common Mistakes to Watch Out for When Tagging in AWS

  1. Inconsistent Tagging: Using different tags or naming conventions can lead to confusion. For instance, don't tag one resource as "Development" and another as "Dev."

  2. Forgetting Cleanup: Leaving tags on unused resources clutters your system. Remove tags from old resources, like decommissioned EC2 instances.

  3. Manual Tagging Overload: Manually tagging every resource is error-prone. Automate tagging with scripts, like automatically tagging new S3 buckets with "Backup."

  4. Team Tagging Knowledge Gap: Team members unaware of tagging's importance can lead to mix-ups. Train your team to use tags effectively, such as adding "Owner" tags to identify responsible team members.

  5. Neglecting Cost Allocation: Skipping cost allocation tags can obscure spending. For instance, use "Cost Center" tags to assign AWS expenses to specific departments.

  6. Tag Policy Neglect: No tag policies mean no tagging standards. Enforce tag policies, like requiring an "Environment" tag for EC2 instances, to maintain consistency.

  7. Resource Group Underuse: Failing to utilize resource groups means missed opportunities for organization. Create a resource group for "Production" resources to simplify management.

  8. Ignoring Tag Updates: Outdated tagging strategies can lead to confusion. Update your tagging approach when your infrastructure changes, like introducing a "Project" tag for new initiatives.

  9. Complex Tags: Overly complex tags hinder readability. Keep it simple, like using "App" for the application name and "Env" for the environment.

  10. Lack of Tag Audits: Skipping tag audits makes it hard to catch errors. Regularly review and adjust tags, such as checking for missing "Compliance" tags on sensitive resources.

Few more tagging tips:

  • Depending on the requirements of your company, use obligatory and optional tags.

  • To assign expenditures to various teams or projects, use tags.

  • Use AWS Budgets to implement tag-based budget notifications.

  • To maintain consistency, use tagging into your CI/CD workflow.

  • Useless or personally identifiable information (PII) should not be included in tags

  • Don't disregard how crucial it is to keep tags updated as resource configurations change.

  • Don't disregard the limitations and guidelines for AWS resource tagging

FAQs

1. What are AWS resource tags, and why are they important?

AWS resource tags are labels that you can attach to your cloud resources to add metadata and organization. They are essential for managing and identifying resources, cost allocation, and implementing security and compliance policies effectively.

2. How can I enforce a tagging policy across my AWS organization?

You can enforce a tagging policy across your AWS organization using Service Control Policies (SCPs) within AWS Organizations. Define SCPs to mandate specific tags or restrict tag values on AWS resources.

3. Can I control access to AWS resources based on tags?

Yes, you can control access to AWS resources using IAM policies that incorporate conditionals based on resource tags. This allows you to grant or deny access to resources based on their tag values.

4. How can I analyze my AWS spending based on resource tags?

You can use AWS Cost Explorer to analyze AWS spending based on resource tags. You can filter cost and usage data by specific tags, helping you understand and allocate costs more effectively.

5. Are there any automation tools for managing resource groups based on tags?

Yes, AWS Resource Groups can be managed programmatically using the AWS SDKs (e.g., Boto3 for Python) or AWS CLI. You can create, modify, and perform actions on resource groups based on tag criteria using code.

6. What is the best practice for automating resource lifecycle management with tags?

The best practice for automating resource lifecycle management with tags is to use AWS Lambda functions triggered by CloudWatch Events. For example, you can periodically scan and take actions on resources with specific tags, like terminating EC2 instances.

7. How can I ensure compliance and audit trails using resource tags?

To ensure compliance, you can use AWS Config rules with custom evaluations to check whether resources adhere to specific tagging standards. Tags can be used to track compliance with regulatory requirements and maintain audit trails of resource changes.

Share with friends

Priyansh Khodiyar's profile

Written by Priyansh Khodiyar

Priyansh is the founder of UnYAML and a software engineer with a passion for writing. He has good experience with writing and working around DevOps tools and technologies, APMs, Kubernetes APIs, etc and loves to share his knowledge with others.

Further Reading

Life is better with cookies 🍪

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt out if you wish. Cookie Policy