How to Enforce Tag Policies on AWS Resources in Python

Build a reusable Python class that checks AWS resources against a required-tag policy and reports compliance with missing tags.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 15 views 0 copies

Python code

35 lines
Python 3.9+
import json
from dataclasses import dataclass, field
from typing import Dict, List


@dataclass
class Resource:
    arn: str
    tags: Dict[str, str] = field(default_factory=dict)


class TagPolicyEnforcer:
    def __init__(self, required_tags: List[str]):
        self.required_tags = set(required_tags)

    def enforce(self, resource: Resource) -> Dict[str, any]:
        missing = self.required_tags - set(resource.tags.keys())
        compliant = not missing
        return {
            "arn": resource.arn,
            "compliant": compliant,
            "missing_tags": sorted(missing),
            "resource_tags": resource.tags,
        }


if __name__ == "__main__":
    policy = TagPolicyEnforcer(required_tags=["environment", "owner"])
    resources = [
        Resource("arn:aws:s3:::bucket-a", {"environment": "prod", "owner": "team-x"}),
        Resource("arn:aws:ec2:us-east-1:123:instance/i-abc", {"owner": "team-y"}),
        Resource("arn:aws:rds:us-east-1:123:db/mydb"),
    ]
    reports = [policy.enforce(r) for r in resources]
    print(json.dumps(reports, indent=2))

Output

stdout
[  {
    "arn": "arn:aws:s3:::bucket-a",
    "compliant": true,
    "missing_tags": [],
    "resource_tags": {
      "environment": "prod",
      "owner": "team-x"
    }
  },
  {
    "arn": "arn:aws:ec2:us-east-1:123:instance/i-abc",
    "compliant": false,
    "missing_tags": [
      "environment"
    ],
    "resource_tags": {
      "owner": "team-y"
    }
  },
  {
    "arn": "arn:aws:rds:us-east-1:123:db/mydb",
    "compliant": false,
    "missing_tags": [
      "environment",
      "owner"
    ],
    "resource_tags": {}
  }
]

How it works

The TagPolicyEnforcer stores required tags as a set for O(1) lookups and efficient difference operations. Each Resource is a dataclass that carries its ARN and a dictionary of tags, defaulting to an empty dict. The enforce method computes the intersection between required and actual tags using set subtraction, then emits a structured report with the ARN, compliance boolean, and sorted missing tags. Using json.dumps with indent=2 gives readable output for cloud automation logs or audit reports. The code is pure standard-library Python, so it runs anywhere without extra dependencies.

Common mistakes

  • Forgetting to handle resources with no tags, which should default to an empty dictionary
  • Assuming tag keys always exist when accessing `resource.tags` directly
  • Using lists instead of sets for required tags, making membership checks O(n)
  • Not sorting missing tags, leading to inconsistent output ordering across runs

Variations

  1. Use `boto3` to fetch live AWS resources and apply the enforcer to actual ARNs
  2. Return the report as a pandas DataFrame for integration with analytics tooling

Real-world use cases

  • Running a compliance audit script that checks every EC2 instance in an account against a mandatory cost-center tag.
  • Enforcing tagging standards in a CI/CD pipeline before resources are provisioned via CloudFormation or Terraform.
  • Generating a quarterly governance report of untagged S3 buckets for security and cost allocation.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.