DEV Community

gurpreet kaur
gurpreet kaur

Posted on

Automating Resource Tagging in AWS : Lambda, AWS Config & Systems Manager

In cloud environments, enforcing compliance is not just a best practice—it’s a necessity. One simple yet powerful way to do this in AWS is through resource tagging. Tags allow you to identify, organize, and control your resources by assigning meaningful key-value metadata such as Environment: Prod.

In this blog, we’ll walk through a hands-on approach to automatically enforce compliance using a combination of AWS services including Lambda, EC2, AWS Config, and Systems Manager (SSM). Our goal: ensure all EC2 instances are correctly tagged with Environment: Prod.

🧠 Understanding the AWS Services Involved
To automate compliance enforcement using tagging, we’ll leverage the following AWS services:

AWS Lambda:
A serverless compute service that runs your code in response to events—like changes in AWS resources—without needing to manage servers. It’s ideal for lightweight automation tasks.

AWS Systems Manager (SSM):
A management service that helps you automate operational tasks across AWS resources. In this context, it triggers Lambda functions as part of automated remediation workflows.

AWS Config:
A monitoring service that tracks AWS resource configurations and evaluates them against compliance rules. It alerts and remediates when resources don’t meet defined standards—like missing required tags.

Steps involved:
🏷️Step 1: Tag Your EC2 Instance

Start by launching an EC2 instance and apply a few initial tags manually (such as Owner: DevOps, Project: Alpha, etc.). This forms the baseline for what compliant tagging should look like.

🧠 Step 2: Create a Lambda Function to Auto-Tag Resources

Next, create an AWS Lambda function in Python that auto-applies the Environment: Prod tag to a given EC2 instance. Here's the core functionality:

  • Accepts an instance ID as input.
  • Constructs the correct resource ARN.
  • Uses the tag_resources method of boto3’s resourcegroupstaggingapi to apply tags.
  • Returns a compliance annotation.
import boto3
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    logger.info(event)

    client = boto3.client('sts')
    account_id = client.get_caller_identity()['Account']

    instance_id = event['instanceId']
    resource_arn = f"arn:aws:ec2:us-east-1:{account_id}:instance/{instance_id}"

    tagging_client = boto3.client('resourcegroupstaggingapi')
    try:
        response = tagging_client.tag_resources(
            ResourceARNList=[resource_arn],
            Tags={'Environment': 'Prod'}
        )
        print(response)
    except Exception as e:
        logger.exception(e)

    return {
        "compliance_type": "COMPLIANT",
        "annotation": "This resource is compliant with the rule."
    }
Enter fullscreen mode Exit fullscreen mode

⚙️ Step 3: Create an SSM Automation Document

Head over to AWS Systems Manager and create a custom SSM Automation Document that invokes the Lambda function created in Step 2. This automation will apply the required Environment: Prod tag to any EC2 instance found non-compliant.

schemaVersion: '0.3'
parameters:
  InstanceId:
    type: String
    description: ID of the instance to be tagged
mainSteps:
  - name: updatetags
    action: aws:invokeLambdaFunction
    isEnd: true
    inputs:
      InvocationType: Event
      Payload: |
        {
          "instanceId": "{{ InstanceId }}"
        }
      FunctionName: arn:aws:lambda:us-east-1:<account_id>:function:labFunction
Enter fullscreen mode Exit fullscreen mode

📊 Step 4: Set Up AWS Config to Monitor Compliance

In AWS Config, create a configuration recorder that logs changes in your resource states and sends them to an S3 bucket.

Make sure to:

  • Choose an S3 bucket prefixed with config-bucket-.
  • Set a prefix such as Config to help organize config data.

✅ Tip: AWS Config's Rules Development Kit (RDK) is highly useful for implementing compliance-as-code patterns, especially when working with custom Lambda-backed rules.

🛠️ Step 5: Create a Config Rule to Enforce Tags

Let’s now create a rule in AWS Config that checks whether EC2 instances have the required Environment: Prod tag.

Resource type: AWS::EC2::Instance
Parameter tag1Key: Environment
Parameter tag1Value: Prod

⚠️ Note: Tag keys and values are case-sensitive in AWS Config.
Once set, this rule automatically flags any EC2 instance that lacks the specified tag as non-compliant.

🔁 Step 6: Automate Remediation Through AWS Config

After creating the rule:

  • Click the rule and choose Manage Remediation.
  • Select Manual remediation.
  • Choose the remediation action that runs your SSM document (from Step 3).
  • Map the Resource ID parameter to instanceId.

Finally:

  • Select the instance from the Resources in scope.
  • Click Remediate.

After a few minutes, refresh the page. The resource's compliance status should change to Compliant once the tag is successfully applied.

Outcome: Automated Compliance for EC2 Instances
With this setup, any EC2 instance missing the Environment: Prod tag is automatically detected and remediated, ensuring your environment stays compliant with organizational tagging policies.

This approach leverages:

  • Lambda for automation,
  • AWS Config for compliance monitoring,
  • SSM for remediation,
  • And tags as the foundation of governance.

🚀** Final Thoughts**
Tagging isn’t just for cost management or organization—it’s also a crucial part of security and compliance enforcement. By combining native AWS services, you can ensure that your cloud environment remains compliant, auditable, and easy to manage at scale.

Top comments (0)