Skip to content

Instantly share code, notes, and snippets.

@seeker815
Created March 28, 2024 12:32
Show Gist options
  • Save seeker815/bd7689886f518aa06856b37c63fdaee6 to your computer and use it in GitHub Desktop.
Save seeker815/bd7689886f518aa06856b37c63fdaee6 to your computer and use it in GitHub Desktop.
To ensure that the usage of the 'root' account in an Amazon Web Services (AWS) environment is monitored using Terraform, you can combine IAM policies with CloudTrail logs. Here's a step-by-step guide:
1. Create an IAM Group and Role for root account access:
First, create an IAM group and attach the necessary policies that allow the root user to perform required actions in your AWS environment. However, it is strongly recommended that you use IAM users or roles instead of the root account for day-to-day tasks. Here's a snippet of Terraform configuration for creating an IAM group and attaching a policy:
```hcl
resource "aws_iam_group" "example_group" {
name = "example_root_access_group"
description = "Example root access group."
}
resource "aws_iam_policy_attachment" "example_policy_attachment" {
name = "example_policy_attachment"
policy_arn = "arn:aws:iam::aws:policy/AmazonS3FullAccess"
groups = [aws_iam_group.example_group.name]
}
```
2. Create an IAM Role for assumed root account access (if required):
If you need to allow temporary or rotating access for the root account, create an IAM role and attach policies as necessary. Here's a Terraform configuration snippet:
```hcl
resource "aws_iam_role" "example_root_access_role" {
name = "example_root_access_role"
description = "Example root access role."
assume_role_policy {
users = ["root"]
}
}
resource "aws_iam_policy_attachment" "example_policy_attachment" {
name = "example_policy_attachment"
policy_arn = "arn:aws:iam::aws:policy/AmazonS3FullAccess"
roles = [aws_iam_role.example_root_access_role.name]
}
```
3. Create a CloudTrail trail to monitor all AWS activity:
Use the `aws_cloudtrail_trail` resource in Terraform to create a CloudTrail trail that will store logs in an S3 bucket and apply other desirable settings. Here's a snippet of Terraform configuration for creating a CloudTrail trail:
```hcl
resource "aws_cloudtrail_trail" "example_trail" {
name = "example_cloudtrail_trail"
bucket_name = "your-bucket-name"
s3_key_prefix = "cloudtrail/example_trail/"
is_multi_region_trail = true
include_global_service_events = true
is_monitoring_enabled = true
}
```
4. Monitor root account usage:
With the above setup, all AWS API calls made using the root account will be logged and stored in your S3 bucket. You can then analyze the logs to monitor and ensure that the root account usage is as intended.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment