agent: |
beFXCgLXgZ2RhT96pGCRUpdate the AWS S3 Bucket Policy to Allow CUR Logging
Update the AWS S3 Bucket Policy to Allow CUR Logging
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
In this task, the S3 bucket's policy is updated to grant necessary permissions for AWS Cost and Usage Reports to deliver log files to the bucket, ensuring secure and compliant data storage.
inputs
outputs
import boto3
import json
from botocore.exceptions import ClientError
# Retrieve AWS credentials from the vault
creds = _get_creds(cred_label)['creds']
access_key = creds['username']
secret_key = creds['password']
# Initialize STS client and get account ID
sts_client = boto3.client('sts', aws_access_key_id=access_key, aws_secret_access_key=secret_key)
account_id = sts_client.get_caller_identity()["Account"]
def update_s3_bucket_policy_for_cur(bucket_name, account_id, region):
"""
Updates the S3 bucket policy to allow AWS CUR to deliver log files.
:param bucket_name: Name of the S3 bucket.
:param account_id: AWS account ID.
:param region: AWS region.
"""
policy = {
"Version": "2008-10-17",
"Id": "Policy1335892530063",
"Statement": [
{
"Sid": "Stmt1335892150622",
"Effect": "Allow",
"Principal": {
"Service": "billingreports.amazonaws.com"
},
"Action": [
"s3:GetBucketAcl",
"s3:GetBucketPolicy"
],
"Resource": f"arn:aws:s3:::{bucket_name}",
"Condition": {
"StringEquals": {
"aws:SourceAccount": account_id,
"aws:SourceArn": f"arn:aws:cur:us-east-1:{account_id}:definition/*" # These endpoints here only work on us-east-1 even if the region_name is different
}
}
},
{
"Sid": "Stmt1335892526596",
"Effect": "Allow",
"Principal": {
"Service": "billingreports.amazonaws.com"
},
"Action": "s3:PutObject",
"Resource": f"arn:aws:s3:::{bucket_name}/*",
"Condition": {
"StringEquals": {
"aws:SourceAccount": account_id,
"aws:SourceArn": f"arn:aws:cur:us-east-1:{account_id}:definition/*" # These endpoints here only work on us-east-1 even if the region_name is different
}
}
}
]
}
s3_client = boto3.client('s3', aws_access_key_id=access_key, aws_secret_access_key=secret_key)
try:
s3_client.put_bucket_policy(Bucket=bucket_name, Policy=json.dumps(policy))
print(f"Bucket policy updated to allow CUR deliveries for '{bucket_name}'.")
except ClientError as e:
print(f"Error updating bucket policy: {e}")
# Example usage
# bucket_name = 'test-this-cur-logging-bucket-1234' # Replace with the name of your existing bucket
# region_name = 'us-east-1' # Replace with your region, e.g., 'us-east-1'
update_s3_bucket_policy_for_cur(BUCKET_NAME, account_id, region_name)
copied