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.
Python code
35 linesimport 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
[ {
"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
- Use `boto3` to fetch live AWS resources and apply the enforcer to actual ARNs
- 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
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.