Automating AWS EC2 instance tagging with Lambda and Python
EC2 tags make a cloud estate searchable, billable and governable. Manual tagging drifts quickly, leaving teams unsure which instances are safe to stop, charge or automate.
A reliable pattern combines EventBridge, Lambda, Python and a scheduled drift sweep. It applies agreed metadata without relying on an engineer to remember every key after each launch.
Why tagging governance matters
Tags drive cost allocation, ownership searches, automation conditions and cleanup decisions. A missing Owner or Environment key can therefore become an operational problem, especially when stale instances survive a project and continue accruing charges.
Australian teams often span Sydney workloads in ap-southeast-2 and Melbourne capacity in ap-southeast-4, while finance reconciles departmental spending in AUD. In the blunt language common in Australian operations chats, an untagged resource is a “mystery box”: nobody can confidently say who owns it.
Designing a tag contract
Define a small contract before coding: Application, Owner, Environment, CostCentre and ManagedBy are usually enough. Keep values predictable, prohibit secrets or personal data, and require Application at launch because later automation cannot reliably infer which policy applies.
Store versioned application-to-tag mappings in SSM Parameter Store, such as orders mapping to production, payments and a shared cost centre. On hybrid estates that still include VMware, link EC2 records to the configuration system; practitioner walkthroughs at IT Diversified show how AWS automation fits wider infrastructure work.
Building the event path
Create an EventBridge rule for EC2 CloudTrail API events such as RunInstances, CreateTags and DeleteTags. The handler can extract instance IDs, read current tags and add only missing or conflicting values. A scheduled scan remains necessary because events can be delayed, filtered out or missed.
The Lambda role needs ssm:GetParameter, ec2:DescribeInstances and ec2:CreateTags, plus logging permissions, while the rule needs permission to invoke the function. Use tag-key conditions where suitable, and put mandatory tags into launch templates because Lambda runs after the launch request completes.
Implementing the Python handler
The handler below reads policy from Parameter Store and uses existing tags to select the correct mapping. If Application is absent or unknown, it logs the instance and leaves it for review rather than guessing.
import json
import os
import boto3
ec2 = boto3.client("ec2")
ssm = boto3.client("ssm")
policy_name = os.environ["TAG_POLICY_ARN"]
def instance_ids(detail):
ids = set()
for item in detail.get("responseElements", {}).get(
"instancesSet", {}
).get("items", []):
if item.get("instanceId"):
ids.add(item["instanceId"])
for item in detail.get("requestParameters", {}).get(
"resourcesSet", {}
).get("items", []):
if item.get("resourceId"):
ids.add(item["resourceId"])
return ids
def handler(event, context):
detail = event["detail"]
ids = instance_ids(detail)
result = ssm.get_parameter(Name=policy_name)
policy = json.loads(result["Parameter"]["Value"])
for instance_id in ids:
response = ec2.describe_instances(
InstanceIds=[instance_id]
)
instance = response["Reservations"][0]["Instances"][0]
tags = {
tag["Key"]: tag["Value"]
for tag in instance.get("Tags", [])
}
desired = policy.get(tags.get("Application"))
if not desired:
print(f"No tag policy for {instance_id}")
continue
desired = {**desired, "ManagedBy": "lambda"}
changes = [
{"Key": key, "Value": value}
for key, value in desired.items()
if tags.get(key) != value
]
if changes:
ec2.create_tags(
Resources=[instance_id],
Tags=changes
)
return {"processed": len(ids)}
The operation is idempotent: applying the desired values creates another event, but the second invocation finds no changes and does nothing. Keep policy writes restricted, because a bad Parameter Store update can affect many instances at once.
Deploying and testing the function
Package the function with its runtime settings and set TAG_POLICY_ARN. The AWS SDK for Python is included in the Lambda runtime, so boto3 needs no external package. Configure a reserved concurrency limit, a dead-letter destination for failed events, and structured logs containing the instance ID, policy version and action.
Test in a non-production account with a disposable instance carrying an Application tag, then remove one required tag and confirm it is restored. For a home lab, recording tested commands and outputs in a personal hands-on lab space gives other engineers a reproducible path.
Running tagging as an operational service
Run a paginated reconciliation Lambda on a schedule to inspect instances and flag missing or conflicting tags. Publish the policy version in every result so an operator can trace the decision, and keep CloudTrail records for tag API calls.
Before deployment
- Require Application, Owner, Environment and CostCentre in launch templates.
- Scope Lambda to the parameter and EC2 tag actions it needs.
- Test policy changes against disposable and representative instances.
During operation
- Schedule pagination-aware scans for missing or conflicting tags.
- Alert on Lambda errors, access denials and unresolved applications.
- Retain CloudTrail evidence and record the active policy version.
Alerts should cover function errors, denied API calls and resources that remain unresolved. Treat a policy update as a controlled deployment, test it against a representative fleet, and roll it back by restoring the previous Parameter Store version.
Comparing automation patterns
Event-driven tagging works best when the event contract is narrow and the remediation policy is centralised. The main alternatives differ in when they detect drift and how much control they give the operator.
| Approach | Trigger | Strength | Main limitation |
|---|---|---|---|
| EventBridge and Lambda | EC2 API events | Near-real-time correction and flexible logic | Requires careful event filters and IAM |
| AWS Config and Lambda | Resource configuration changes | Broad configuration coverage | More moving parts and eventual evaluation |
| Scheduled Lambda | EventBridge Scheduler | Simple fleet-wide drift sweep | Periodic execution and additional API traffic |
| Systems Manager Automation | Manual or workflow run | Auditable, repeatable remediation | Less suitable for continuous tagging |
For most estates, EventBridge-driven Lambda plus scheduled reconciliation provides immediate correction and a dependable safety net. AWS Config adds policy breadth, while Systems Manager Automation suits a manually triggered, auditable runbook.