Set S3 Bucket Policy to include ELB Account

After utilizing the AWS console to create a bucket for access logging via the load balancer edit attributes screen, I am now in the process of transforming this action into CDK code using TypeScript. This allows me to automate the creation of new S3 buckets for access logging in environments that do not allow console usage. The specific policy I need to translate into TypeScript CDK code is as follows:

"Statement": [
{
    "Effect":Allow",
    "Principal": {
        "AWS": "arn:--ELB-arnstuff--:root"
    },
    "Action": "s3:PutObject",
    "Resource": "arn:--S3-Bucket-arnstuff--/AWSLogs/123456789/*"
}
]

So far, I have made progress with the CDK code up to this point:

bucket.addToResourcePolicy(
    new cdk.aws_iam.PolicyStatement({ 
      effect: awsIam.Effect.ALLOW,
      principals: //'**This is part I haven't figured out**',
      actions: ['s3:PutObject'],
      resources: ['${bucket.bucketArn}/*']
    })
);

Although I am open to hardcoding the solution in the CDK at this stage, any assistance in figuring out the remaining piece would be greatly appreciated. Thank you!

Answer №1

The AWS documentation outlines the bucket policy and specifies which AWS accounts can be utilized. You can find more information in the AWS documentation:

Region  Region name     Elastic Load Balancing account ID
us-east-1   US East (N. Virginia)   127311923021
us-east-2   US East (Ohio)  033677994240
us-west-1   US West (N. California)     027434742980
us-west-2   US West (Oregon)    797873946194
af-south-1  Africa (Cape Town)  098369216593
ca-central-1    Canada (Central)    985666609251
eu-central-1    Europe (Frankfurt)  054676820928
eu-west-1   Europe (Ireland)    156460612806
eu-west-2   Europe (London)     652711504416
eu-south-1  Europe (Milan)  635631232127
eu-west-3   Europe (Paris)  009996457667
eu-north-1  Europe (Stockholm)  897822967062
ap-east-1   Asia Pacific (Hong Kong)    754344448648
ap-northeast-1  Asia Pacific (Tokyo)    582318560864
ap-northeast-2  Asia Pacific (Seoul)    600734575887
ap-northeast-3  Asia Pacific (Osaka)    383597477331
ap-southeast-1  Asia Pacific (Singapore)    114774131450
ap-southeast-2  Asia Pacific (Sydney)   783225319266
ap-southeast-3  Asia Pacific (Jakarta)  589379963580
ap-south-1  Asia Pacific (Mumbai)   718504428378
me-south-1  Middle East (Bahrain)   076674570225
sa-east-1   South America (São Paulo)   507241528517
us-gov-west-1*  AWS GovCloud (US-West)  048591011584
us-gov-east-1*  AWS GovCloud (US-East)  190560391635
cn-north-1*     China (Beijing)     638102146993
cn-northwest-1*     China (Ningxia)     037604701340

Answer №2

Upon investigating, I discovered the reason why my initial attempt to use .fromJson to directly incorporate an AWS generated policy into the CDK failed. It turns out that the addToResourcePolicy function can only accept one object at a time, while the AWS generated policy contained 3 objects. This led to an error when trying to pass multiple objects using .fromJson.

In the code snippet provided above, I focused on identifying the cdk equivalent Principal object for an AWS ELB Account. To work around this issue, I used .fromJson specifically for this single policy object:

bucket.addToResourcePolicy(
  cdk.aws_iam.PolicyStatement.fromJson({
    "Effect":Allow",
    "Principal": {
      "AWS": "arn:--ELB-arnstuff--:root"
    },
    "Action": "s3:PutObject",
    "Resource": "arn:--S3-Bucket-arnstuff--/AWSLogs/123456789/*"
  })
);

It is important to note the omission of the new operator when working with a Json object. If you encounter the same issue with multiple policies, you will need to create a unique bucket.addToResourcePolicy block of code for each Json object policy you intend to apply.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring NextJS with Typescript

Struggling to incorporate Typescript with NextJS has been a challenge, especially when it comes to destructured parameters in getInitialProps and defining the type of page functions. Take for example my _app.tsx: import { ThemeProvider } from 'styled ...

Next.js Error: Inconsistent text content between server-rendered HTML and hydration. Unicode characters U+202F versus U+0020

Having issues with dates in Next.js development. Encountering three errors that need to be addressed: Warning: Text content did not match. Server: "Tuesday, January 24, 2023 at 11:01 AM" Client: "Tuesday, January 24, 2023 at 11:01 AM" ...

Encountering an error while trying to `gulp install`, which displays as `Cannot read property 'apply' of undefined`

Following the instructions on AWS documentation, I successfully installed NVM and NPM on an EC2 instance. Next, I proceeded to install gulp and gulp-cli using the following commands: npm install --global gulp npm install --global gulp-cli After that, w ...

What is the process for transferring a local image to an S3 bucket from a Lambda function using Node.js?

I am currently working on a Node script that involves image manipulation and saving the results to S3. Despite my efforts, the resulting image file in S3 is coming out blank. I have tried different approaches such as using the result image, the source im ...

Tips for implementing a coupon code feature on Stripe checkout in an Angular 8+ application

I need to implement an input option for entering coupons in the Stripe payment gateway when the handler is open on the front end. I currently have a Stripe window open and would like to provide users with a way to enter coupon codes. // Function to Load ...

Having trouble with React state not updating?

Hello, I am a beginner in the world of React and currently working on fetching an array of endpoints. My goal is to update the API's status every 15 seconds. Here is the code snippet for the array of endpoints: export const endpoints: string[] = [ " ...

Is there a way to verify if multiple variables in Typescript are null or undefined?

Background To address the issue of checking whether a specific variable is null or undefined, I created the isNullish function. The implementation of this function is shown below. type Nullish = null | undefined; const isNullish = (target: unknown): targe ...

Extract HTML content using CKEditor

Hey there! I'm in need of some help with getting user-entered data from a textarea. I've already attempted using CKEDITOR.instances.editor1.getData() and CKEDITOR.instances.ckeditor.document.getBody.getHtml(), but unfortunately both only return ...

The best approach for sending parameters to the parent class in TypeScript for optimal efficiency

What's the optimal solution to this problem? I really appreciate how we can specify attributes in the constructor and TypeScript takes care of handling everything to assign values to the props in JavaScript - like I did with 'department' her ...

Tips for utilizing interpolation for conditions instead of using *ngIf

For my application, I am using two different languages and have written them within two <option> tags. Is it possible to combine both conditions into a single <option> tag using interpolation? <option *ngIf="this.language=='en&apos ...

Issue with Angular: Child component not receiving data after successful parent component call

I'm currently working with a parent and child component setup. Within the child component, I have a button configured like this: //child.component.html <button mat-raised-button [disabled]="!form.valid || submitButtonDisable" type = 'Submi ...

Showing the state on a different page: A step-by-step guide

I'm currently in the process of creating a model for a real estate website. On the homepage, users can choose between 'rent' or 'purchase' using a select option and view the results on that page. I have successfully stored the sear ...

Having trouble with vscode compiling the typescript file?

Even though I diligently followed the tutorial provided by vscode on compiling typescript code, I encountered a problem. The configurations were set up as per the instructions in the tutorial, but when I tried to run the code without debugging, I received ...

What is the best way to prevent users from entering a zero in the first position of a text box using JavaScript

Although I am aware this may be a duplicate issue, the existing solution does not seem to work for me. The field should accept values like: valid - 123,33.00, 100,897,99, 8000 10334 9800,564,88.36 invalid - 001, 0 ...

Exploring the Depths of Observables in Angular2 Guards

I have a Guardian overseeing a specific route. Within the canActivate method, I am trying to perform two HTTP requests, with the second request being dependent on the response of the first one. However, it seems like the second request is not being trigger ...

How can I prevent the enter key from working with Twitter Typeahead?

Is there a way to prevent the enter key from being pressed on an element within Twitter Typeahead's dropdown feature while using Angular with Typescript? I attempted to utilize preventDefault() when event.keycode === 13 on the ng-keydown event for th ...

"Exploring the dynamic duo of Angular2 and ng2Material

I am currently facing an issue with the styling in my code while using ng2Material with Angular2. First: A demonstration of Material style functioning properly can be seen in this plunker. When you click on the button, you will notice an animation effect. ...

Retrieve data upon component mounting and deactivate the query in React-query

When navigating to a search result page, query parameters are passed to useQuery. I want the data to be fetched only when the user clicks the "Search" button after changing the search prompt. I attempted to use enabled: false and call refetch() on button ...

"React with Typescript - a powerful combination for

I'm facing an issue trying to create a simple list of items in my code. Adding the items manually works, but when I try to map through them it doesn't work. Apologies for any language mistakes. import './App.css' const App = () => { ...

What is the process for incorporating a standalone custom directive into a non-standalone component in Angular?

Implementing a custom directive in a non-standalone component I have developed a custom structural directive and I would like to use it across multiple components. Everything functions as expected when it is not standalone, but encountering an error when ...