I have been working on setting up CloudTrail for an IAM user using Boto but I have run into an error:
An error occurred (InsufficientS3BucketPolicyException) when calling the CreateTrail operation: Incorrect S3 bucket policy is detected for bucket: goodbucket
I am not sure what's wrong here. Saving the CloudTrail log is not a priority but I will need ResourceID, to delete resource later on using Lambda functions.
import boto3
import sys
import json
import time
iam = boto3.client('iam')
sts = boto3.client('sts')
ec2 = boto3.resource('ec2')
cloudtrail = boto3.client('cloudtrail')
response = iam.create_user(
UserName='GoodUser'
)
IDK = sts.get_caller_identity()
print(IDK['UserId'])
response = iam.create_group(
GroupName='GoodGroup'
)
response = iam.add_user_to_group(
GroupName='GoodGroup',
UserName='GoodUser'
)
some_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "ec2:RunInstances",
"Resource": [
f"arn:aws:ec2:us-east-2:{IDK['Account']}:instance/*",
f"arn:aws:ec2:us-east-2:{IDK['Account']}:network-interface/*",
f"arn:aws:ec2:us-east-2:{IDK['Account']}:key-pair/*",
f"arn:aws:ec2:us-east-2:{IDK['Account']}:security-group/*",
f"arn:aws:ec2:us-east-2:{IDK['Account']}:subnet/*",
f"arn:aws:ec2:us-east-2:{IDK['Account']}:volume/*",
f"arn:aws:ec2:us-east-2:{IDK['Account']}:image/ami-0a91cd140a1fc148a"
],
"Condition": {
"ForAllValues:NumericLessThanEquals": {
"ec2:VolumeSize": "10"
},
"ForAllValues:StringEquals": {
"ec2:InstanceType": "t2.micro"
}
}
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": [
"ec2:TerminateInstances",
"ec2:StartInstances",
"ec2:StopInstances"
],
"Resource": f"arn:aws:ec2:us-east-2:{IDK['Account']}:instance/*",
"Condition": {
"ForAllValues:StringEquals": {
"ec2:InstanceType": "t2.micro"
}
}
},
{
"Sid": "VisualEditor2",
"Effect": "Allow",
"Action": [
"ec2:Describe*",
"ec2:GetConsole*",
"cloudwatch:DescribeAlarms",
"iam:ListInstanceProfiles",
"cloudwatch:GetMetricStatistics",
"ec2:DescribeKeyPairs",
"ec2:CreateKeyPair"
],
"Resource": "*",
"Condition": {
"DateGreaterThan": {
"aws:CurrentTime": "2020-12-10T05:00:00Z"
},
"DateLessThanEquals": {
"aws:CurrentTime": "2020-12-10T05:35:00Z"
}
}
}
]
}
response = iam.create_policy(
PolicyName='GoodPolicy',
PolicyDocument=json.dumps(some_policy)
)
print(response)
IDK1 = iam.attach_group_policy(
GroupName='GoodGroup',
PolicyArn= f"arn:aws:iam::{IDK['Account']}:policy/GoodPolicy"
)
logs = cloudtrail.create_trail(
Name='GoodTrail',
S3BucketName='goodbucket',
)
print (logs)
You are configuring AWS CloudTrail to write log files to an Amazon S3 bucket. To do this, the S3 bucket requires a Bucket Policy that grants permission to the CloudTrail service to write to the bucket.
From Amazon S3 Bucket Policy for CloudTrail - AWS CloudTrail: