in awscli/customizations/cloudtrail/subscribe.py [0:0]
def setup_new_bucket(self, bucket, prefix, custom_policy=None):
"""
Creates a new S3 bucket with an appropriate policy to let CloudTrail
write to the prefix path.
"""
sys.stdout.write(
'Setting up new S3 bucket {bucket}...\n'.format(bucket=bucket))
account_id = get_account_id(self.sts)
# Clean up the prefix - it requires a trailing slash if set
if prefix and not prefix.endswith('/'):
prefix += '/'
# Fetch policy data from S3 or a custom URL
if custom_policy is not None:
policy = custom_policy
else:
policy = self._get_policy(S3_POLICY_TEMPLATE)
policy = policy.replace('<BucketName>', bucket)\
.replace('<CustomerAccountID>', account_id)
if '<Prefix>/' in policy:
policy = policy.replace('<Prefix>/', prefix or '')
else:
policy = policy.replace('<Prefix>', prefix or '')
LOG.debug('Bucket policy:\n{0}'.format(policy))
bucket_exists = s3_bucket_exists(self.s3, bucket)
if bucket_exists:
raise Exception('Bucket {bucket} already exists.'.format(
bucket=bucket))
# If we are not using the us-east-1 region, then we must set
# a location constraint on the new bucket.
params = {'Bucket': bucket}
if self.region_name != 'us-east-1':
bucket_config = {'LocationConstraint': self.region_name}
params['CreateBucketConfiguration'] = bucket_config
data = self.s3.create_bucket(**params)
try:
self.s3.put_bucket_policy(Bucket=bucket, Policy=policy)
except ClientError:
# Roll back bucket creation.
self.s3.delete_bucket(Bucket=bucket)
raise
return data