Automating Privileged Access Management in AWS: A Python & Terraform Solution

In today’s cloud-first world, managing privileged access in your AWS environment is a critical part of maintaining security and compliance. One of the best ways to enforce least privilege is to dynamically adjust permissions based on the actions a user…


This content originally appeared on DEV Community and was authored by Prathamesh AWS AWS

In today's cloud-first world, managing privileged access in your AWS environment is a critical part of maintaining security and compliance. One of the best ways to enforce least privilege is to dynamically adjust permissions based on the actions a user is performing in your environment. In this blog, we will explore how to automate privileged access management using a combination of AWS CloudTrail, Python, and Terraform. This approach will allow you to automatically detect a user's actions and resources, then create and attach a custom IAM policy to restrict access to only the resources and actions they use most frequently.

Why Privileged Access Management?
Privileged access refers to the access granted to users or services that can perform actions that affect the entire AWS environment. This includes activities like creating users, managing security policies, and accessing sensitive resources. It's important to grant these permissions cautiously and only to those who need it for their role. By automating privileged access management, you can reduce human error and better enforce security best practices.

Overview of the Solution

The solution we will build consists of two main components:

Python Script: The script will extract a user's actions and resources from AWS CloudTrail logs. It will analyze the most frequent actions and resources, then create a deny policy that restricts access to those specific resources and actions.

Terraform: Once the policy is created, Terraform will be used to automatically apply the policy to the user, ensuring that the user only has access to the actions and resources they need.

How to Automate IAM Policy Creation Using CloudTrail Data and Terraform
In this blog post, we'll walk through a process that automates the creation of an IAM policy using CloudTrail logs for a particular user, analyzes the most frequently used actions and resources, and then uses Terraform to apply this policy dynamically. We'll also discuss how to handle issues like missing resource ARNs and ensure the policy is well-formed.

Prerequisites
Before starting, make sure you have the following prerequisites:

  1. AWS Account with sufficient permissions to access CloudTrail, IAM, and execute Terraform.
  2. AWS CLI configured with necessary access credentials.
  3. Python 3.x installed with boto3, dotenv, and subprocess libraries.
  4. Terraform installed and configured for your AWS environment.
  5. CloudTrail enabled in your AWS account for at least 30 days to gather the logs.

You will also need to set up environment variables to securely manage your AWS credentials:
Create a .env file in code directory.

  1. AWS_USERNAME: IAM username for which you want to create the policy.
  2. AWS_REGION: The region where CloudTrail and IAM are located.
  3. DAYS: (Optional) The number of past days to analyze CloudTrail logs.

Steps for Automating Privileged Access Management

Step 1: Setting Up Your Environment
Before diving into the code, you'll need the following tools:

AWS IAM: Ensure your AWS user has the necessary permissions to access CloudTrail and create IAM policies and users.
Python: Make sure Python is installed along with the boto3 (AWS SDK) and dotenv (for environment variable management) libraries.
Terraform: Install Terraform to manage AWS resources.

pip install boto3 python-dotenv

Ensure that your AWS credentials are set up either through AWS CLI or environment variables.

Step 2: Fetching CloudTrail Data
To begin, we need to collect the CloudTrail logs for a user. The Python script will query CloudTrail for all actions performed by the user in a given timeframe (e.g., the last 30 days).

import boto3
import datetime
from collections import Counter

def get_cloudtrail_data(user_name, region, days=30):
    cloudtrail = boto3.client('cloudtrail', region_name=region)
    end_time = datetime.datetime.utcnow()
    start_time = end_time - datetime.timedelta(days=days)

    events = []
    paginator = cloudtrail.get_paginator('lookup_events')
    response_iterator = paginator.paginate(
        LookupAttributes=[{'AttributeKey': 'Username', 'AttributeValue': user_name}],
        StartTime=start_time,
        EndTime=end_time
    )

    for page in response_iterator:
        events.extend(page['Events'])

    return events

Step 3: Analyzing the User’s Activities
The script will analyze the actions and resources accessed by the user. We will extract the most frequent actions and resources to build our IAM policy.

def analyze_user_activity(events):
    actions = []
    resources = []

    for event in events:
        event_name = event.get('EventName', 'Unknown')
        event_source = event.get('EventSource', '').replace('.amazonaws.com', '')
        resources_accessed = event.get('Resources', [])

        if event_name != 'Unknown' and event_source:
            actions.append(f"{event_source}:{event_name}")

        for resource in resources_accessed:
            resources.append(resource.get('ResourceName', 'Unknown'))

    actions_counter = Counter(actions)
    resources_counter = Counter(resources)

    return {
        "most_frequent_actions": [action for action, _ in actions_counter.most_common()],
        "most_frequent_resources": [resource for resource, _ in resources_counter.most_common()]
    }

Step 4: Dynamically Create IAM Policy
Now that we have the most frequently used actions and resources, we can create an IAM policy that allows these actions on the corresponding resources and denies everything else.

def create_deny_policy(user_name, allowed_actions, allowed_resources, region):
    # If no specific resources are found, fallback to "*"
    if not allowed_resources:
        allowed_resources = ["*"]

    policy = {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": allowed_actions,
                "Resource": allowed_resources
            },
            {
                "Effect": "Deny",
                "Action": "*",
                "Resource": "*"
            }
        ]
    }

    with open("deny_policy.json", "w") as file:
        json.dump(policy, file, indent=4)
    print("Deny policy 'deny_policy.json' created successfully.")

Step 5: Creating and Attaching the Policy with Terraform
After the policy has been created, Terraform will help us deploy the policy by attaching it to the specified user.

provider "aws" {
  region = "us-east-2"
}

resource "aws_iam_user_policy" "deny_policy" {
  name   = "deny-policy-for-${var.user_name}"
  user   = var.user_name
  policy = file("deny_policy.json")
}

Step 6: Automatically Fixing Privileged Access
This system not only monitors the user’s activities but also fixes excessive or unnecessary permissions by denying access to actions and resources that the user does not require. If the user has resources that are not part of the policy, the script ensures that those resources are excluded dynamically. This allows you to enforce the least privilege without manually managing policies for each user.

Step 7: Optional User List
You can pass a list of users to the script to analyze and manage multiple users' access automatically. If no user list is passed, the script will default to a single user. Here’s an optional approach to handle this:

def main():
    user_names = os.getenv("USER_LIST", "").split(",")  # Get list of users from environment variable

    if not user_names:
        user_names = [os.getenv("AWS_USERNAME")]

    for user_name in user_names:
        print(f"Processing user: {user_name}")
        events = get_cloudtrail_data(user_name, region, days)
        if not events:
            print(f"No CloudTrail logs found for user '{user_name}' in the last {days} days.")
            continue

        analysis = analyze_user_activity(events)
        allowed_actions = analysis["most_frequent_actions"]
        allowed_resources = analysis["most_frequent_resources"]

        create_deny_policy(user_name, allowed_actions, allowed_resources, region)
        create_terraform_file(user_name)
        deploy_with_terraform()

Run the Script
python3 script.py

Conclusion
By using a combination of Python, AWS CloudTrail, and Terraform, this solution automates the process of fixing privileged access on your AWS environment. It dynamically analyzes user actions, creates the least privileged IAM policies, and automatically applies them. This automation ensures your environment remains secure, reduces the risk of human error, and enforces best practices.

With this approach, you can easily maintain privileged access and minimize security risks associated with unnecessary permissions in your AWS account.

Next Steps:
Run the script periodically as part of your security audits.
Extend the logic to support other AWS services or additional user activity analysis.
Monitor and refine the policy size to ensure it fits within AWS limits.


This content originally appeared on DEV Community and was authored by Prathamesh AWS AWS


Print Share Comment Cite Upload Translate Updates
APA

Prathamesh AWS AWS | Sciencx (2025-01-16T16:38:03+00:00) Automating Privileged Access Management in AWS: A Python & Terraform Solution. Retrieved from https://www.scien.cx/2025/01/16/automating-privileged-access-management-in-aws-a-python-terraform-solution/

MLA
" » Automating Privileged Access Management in AWS: A Python & Terraform Solution." Prathamesh AWS AWS | Sciencx - Thursday January 16, 2025, https://www.scien.cx/2025/01/16/automating-privileged-access-management-in-aws-a-python-terraform-solution/
HARVARD
Prathamesh AWS AWS | Sciencx Thursday January 16, 2025 » Automating Privileged Access Management in AWS: A Python & Terraform Solution., viewed ,<https://www.scien.cx/2025/01/16/automating-privileged-access-management-in-aws-a-python-terraform-solution/>
VANCOUVER
Prathamesh AWS AWS | Sciencx - » Automating Privileged Access Management in AWS: A Python & Terraform Solution. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/01/16/automating-privileged-access-management-in-aws-a-python-terraform-solution/
CHICAGO
" » Automating Privileged Access Management in AWS: A Python & Terraform Solution." Prathamesh AWS AWS | Sciencx - Accessed . https://www.scien.cx/2025/01/16/automating-privileged-access-management-in-aws-a-python-terraform-solution/
IEEE
" » Automating Privileged Access Management in AWS: A Python & Terraform Solution." Prathamesh AWS AWS | Sciencx [Online]. Available: https://www.scien.cx/2025/01/16/automating-privileged-access-management-in-aws-a-python-terraform-solution/. [Accessed: ]
rf:citation
» Automating Privileged Access Management in AWS: A Python & Terraform Solution | Prathamesh AWS AWS | Sciencx | https://www.scien.cx/2025/01/16/automating-privileged-access-management-in-aws-a-python-terraform-solution/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.