How to configure an S3 bucket in Terraform to meet specific needs?

62    Asked by DavidEDWARDS in Devops , Asked on Jul 16, 2024

 I am currently working on a task related to a terraforming project to set up an S3 bucket for storing the application logs. I need to ensure that only a specific IAM role, named LogReaderRole should read from the bucket, while all others should be denied. How can I configure the S3 bucket policy in the terraform so that I can meet this particular requirement? 

Answered by Dipesh Bhardwaj

 In the context of DevOps, here are the steps given of how you can define a bucket policy in the terraform that Explicitly allows LogReaderRole to have S3: Gwtobject permission while all others are denied:-


Define the S3 bucket
Firstly, you would need to define the S3 bucket:
Resource “aws_s3_bucket” “log_bucket” {
  Bucket = “my-application-logs”
}
Creating the bucket policies
Now you can create or form a bucket policy:
Data “aws_iam_policy_document” “bucket_policy” {
  Statement {
    Actions = [“s3:GetObject”]
    Resources = [“${aws_s3_bucket.log_bucket.arn}/*”]
    Principals {
      Type = “AWS”
      Identifiers = [“arn:aws:iam::123456789012:role/LogReaderRole”]
    }
    Effect = “Allow”
  }
  Statement {
    Actions = [“s3:*”]
    Resources = [“${aws_s3_bucket.log_bucket.arn}/*”]
    Effect = “Deny”
    Condition {
      Test = “Bool”
      Variable = “aws:SecureTransport”
      Values = [“false”]
    }
  }
}
Attach the policy to the S3 bucket
After completing the process of formation of a policy, you can attach this created policy to your particular S3 bucket:
Resource “aws_s3_bucket_policy” “log_bucket_policy” {
  Bucket = aws_s3_bucket.log_bucket.id
  Policy = data.aws_iam_policy_document.bucket_policy.json
}
This would ensure that only the LogReaderRole should read from the bucket, while all others should be denied.
Here is a Python-based scenario given of how you can use the Boto3 library to create an S3 Bucket and attach a policy that would ensure only a specific IAM role has read access. It would also include a part that denies all other access:-
Import boto3
Import json
# Initialize a session using Amazon S3
Session = boto3.Session(
    Aws_access_key_id=’YOUR_AWS_ACCESS_KEY’,
    Aws_secret_access_key=’YOUR_AWS_SECRET_KEY’,
    Region_name=’YOUR_AWS_REGION’
)
# Create an S3 client
S3_client = session.client(‘s3’)
# Specify the bucket name
Bucket_name = ‘my-application-logs’
# Create the S3 bucket
Try:
    S3_client.create_bucket(
        Bucket=bucket_name,
        CreateBucketConfiguration={
            ‘LocationConstraint’: ‘YOUR_AWS_REGION’
        }
    )
    Print(f’Bucket {bucket_name} created successfully.’)
Except Exception as e:
    Print(f’Error creating bucket: {e}’)
# Define the bucket policy
Bucket_policy = {
    “Version”: “2012-10-17”,
    “Statement”: [
        {
            “Effect”: “Allow”,
            “Principal”: {
                “AWS”: “arn:aws:iam::123456789012:role/LogReaderRole”
            },
            “Action”: “s3:GetObject”,
            “Resource”: f”arn:aws:s3:::{bucket_name}/*”
        },
        {
            “Effect”: “Deny”,
            “Principal”: “*”,
            “Action”: “s3:*”,
            “Resource”: f”arn:aws:s3:::{bucket_name}/*”,
            “Condition”: {
                “Bool”: {
                    “aws:SecureTransport”: “false”
                }
            }
        }
    ]
}
# Convert the policy to JSON
Bucket_policy_json = json.dumps(bucket_policy)
# Apply the policy to the S3 bucket
Try:
    S3_client.put_bucket_policy(
        Bucket=bucket_name,
        Policy=bucket_policy_json
    )
    Print(f’Policy attached to bucket {bucket_name} successfully.’)
Except Exception as e:
    Print(f’Error attaching policy: {e}’)
Here is the java based approach given :-
Import com.amazonaws.auth.AWSStaticCredentialsProvider;
Import com.amazonaws.auth.BasicAWSCredentials;
Import com.amazonaws.services.s3.AmazonS3;
Import com.amazonaws.services.s3.AmazonS3ClientBuilder;
Import com.amazonaws.services.s3.model.SetBucketPolicyRequest;
Public class S3BucketPolicyExample {
    Public static void main(String[] args) {
        String accessKey = “YOUR_ACCESS_KEY”;
        String secretKey = “YOUR_SECRET_KEY”;
        String region = “YOUR_REGION”;
        String bucketName = “my-logs”;
        String roleArn = “arn:aws:iam::123456789012:role/LogReaderRole”;
        // Create S3 client
        BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey);
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                .withRegion(region)
                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                .build();
        // Define policy
        String bucketPolicy = “{
” +
                “ ”Version”: ”2012-10-17”,
” +
                “ ”Statement”: [
” +
                “ {
” +
                “ ”Effect”: ”Allow”,
” +
                “ ”Principal”: {”AWS”: ”” + roleArn + “”},
” +
                “ ”Action”: ”s3:GetObject”,
” +
                “ ”Resource”: ”arn:aws:s3:::” + bucketName + “/*”
” +
                “ }
” +
                “ ]
” +
                “}”;
        // Apply policy
        SetBucketPolicyRequest policyRequest = new SetBucketPolicyRequest(bucketName, bucketPolicy);
        S3Client.setBucketPolicy(policyRequest);
        System.out.println(“Policy set for bucket “ + bucketName);
    }
}


Your Answer

Interviews

Parent Categories