brave-barista-3373
11/12/2024, 8:55 PMcustom_s3 = CustomS3('name')
custom_s3.attach_alb_policy()
custom_s3.attach_cloudfront_policy('someid')
customS3.py
class CustomS3(pulumi.ComponentResource):
def __init__():
...
self.s3_bucket= aws.s3.BucketV2 (self.name)
...
def attach_alb_policy(self):
...
configure_bucket_policy ('policy to add')
def attach_cloudfront_policy(self,origin_access_id):
...
configure_bucket_policy ('policy to add')
def configure_bucket_policy (self, policy_to_add):
#Try to pull teh current policy if exists on bucket
try:
current_policy = aws.s3.get_bucket_policy(bucket=self.s3_bucket)
except:
#Found no policy current attached
current_policy = None
generated_policy = json.dumps(collapse_policy_statements(json.loads(current_policy.policy),policy_to_add)) if current_policy else json.dumps(policy_to_add)
print (generated_policy)
self.bucket_policy = aws.s3.BucketPolicy(
f"s3-policy-{self.name}",
bucket=self.s3_bucket,
policy= generated_policy,
opts=pulumi.ResourceOptions(parent=self.s3_bucket)
)
modern-zebra-45309
11/12/2024, 9:02 PMaws.s3.BucketPolicy
generated by your configure_bucket_policy
method is always f"s3-policy-{self.name}"
, where self.name
is the name of the S3 bucket.modern-zebra-45309
11/12/2024, 9:03 PMself.bucket_policy
every time you call the method, so this will always be set to the latest policy object.modern-zebra-45309
11/12/2024, 9:04 PMbrave-barista-3373
11/12/2024, 9:11 PMmodern-zebra-45309
11/12/2024, 9:14 PMclass CustomS3(pulumi.ComponentResource):
def __init__(self, name: str):
...
self.bucket_name = name
self.bucket_policies = []
def configure_policy(self, policy: str):
...
new_policy = aws.s3.BucketPolicy(
# generate a unique resource name
f"s3-policy-for-{self.bucket_name}-{len(self.bucket_policies)}",
...)
self.bucket_policies.append(new_policy)
modern-zebra-45309
11/12/2024, 9:15 PMmodern-zebra-45309
11/12/2024, 9:15 PMself.bucket_policies
could also be a dictionary for easier lookup, perhaps you have a set of standard policies that you frequently re-use that have proper names.modern-zebra-45309
11/12/2024, 9:19 PMbrave-barista-3373
11/12/2024, 9:19 PMmodern-zebra-45309
11/12/2024, 9:20 PMbrave-barista-3373
11/12/2024, 9:24 PMmodern-zebra-45309
11/12/2024, 9:24 PMaws.s3.BucketPolicy
only after you've collected all the statements.brave-barista-3373
11/12/2024, 9:25 PMmodern-zebra-45309
11/12/2024, 9:25 PMmodern-zebra-45309
11/12/2024, 9:26 PMaws.s3.get_bucket_policy()
if you have the bucket resource in your stack, which you do.brave-barista-3373
11/12/2024, 9:27 PM