# Impostare caricamenti di file e immagini su S3

**URL:** https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229
**Category:** Self-Hosting
**Tags:** configuring, how-to
**Created:** [6 Giugno 2013, 7:37pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229 "2013-06-06T19:37:43Z")
**Posts on this page:** 20
**Page:** 1

<div class="post-metadata">

### Author: ![Discourse](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/discourse/32/148734_2.png) [@Discourse](https://meta.discourse.org/u/Discourse)
#### Post date: [6 Giugno 2013, 7:37pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/1 "2013-06-06T19:37:43Z")

</div>

So, you want to use S3 to handle image uploads? Here’s the _definitive_ guide, but also see [Configure an S3 compatible object storage provider for uploads](https://meta.discourse.org/t/configure-an-s3-compatible-object-storage-provider-for-uploads/148916) to see how to configure your app.yml.

## S3 registration

Head over to [https://aws.amazon.com/free/](https://aws.amazon.com/free/) and click on ![Create a Free Account](https://global.discourse-cdn.com/meta/original/3X/5/2/52347dfe5f0b7652db9c59085032728eb1edd27e.png)

During the create account process, make sure you provide payment information, otherwise you won’t be able to use S3. There’s no registration fee, you will only be charged for [what you use](https://aws.amazon.com/s3/pricing/), if you exceed the [AWS Free Usage Tier](https://aws.amazon.com/free/).

## Bucket

Go to [S3](https://s3.console.aws.amazon.com/s3/home?region=eu-west-1) and click on **Create bucket** , then fill out the **Bucket name**. Remember this name because we’ll need it for the next step.

- The bucket name should _not_ contain periods as this will cause [huge HTTPS problems for you](https://shlomoswidler.com/2009/08/amazon-s3-gotcha-using-virtual-host.html).

- The bucket name should be [all lowercase](https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html)

Name of your bucket

Select a **Region**. You should enter the location (eg. “EU (Frankfurt)”) that is nearest to your users for better performance.

Scroll down a little until you get to the **Permissions** panel.

> ⚠ Since April 2023, new S3 buckets have ACLs disabled by default (“Bucket owner enforced”). You have two options:
> 
> **Option A — ACLs disabled (simpler):** Keep the AWS defaults (ACLs disabled, all public access blocked). Later, set `s3_use_acls` to `false` in Discourse. Uploads will be served via presigned URLs or a CDN. You can also omit `s3:PutObjectAcl` and `s3:PutObjectVersionAcl` from the IAM policy below.
> 
> **Option B — ACLs enabled (legacy, Discourse default):** Change **Object Ownership** to **“ACLs enabled”** (choose “Bucket owner preferred”). Then uncheck **Block all public access** and check the bottom two checkboxes. You’ll also have to acknowledge that your settings may make the bucket public.

 ![AWS-bucket-access](https://global.discourse-cdn.com/meta/original/3X/7/2/72401448608da2b7faf2b84c371c985b93ea5c0b.png)

## User creation

### Creating a policy

Sign in to [AWS Management Console](https://console.aws.amazon.com/) and search for the “ **IAM** ” service to access the [AWS Identity and Access Management (IAM)](https://console.aws.amazon.com/iam/home#/policies) console which enables you to manage access to your AWS resources.

First, click Policies in the sidebar. Then, click on **Create Policy** and choose the JSON tab:

![image](https://global.discourse-cdn.com/meta/original/3X/f/1/f14734efce0f60c836e144be7157cb8c946a7f5f.png)

Use the following piece of code as a template for your policy document:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
               "s3:List*",
               "s3:Get*",
               "s3:AbortMultipartUpload",
               "s3:DeleteObject",
               "s3:PutObject",
               "s3:PutObjectAcl",
               "s3:PutObjectVersionAcl",
               "s3:PutLifecycleConfiguration",
               "s3:PutBucketCORS"
      ],
      "Resource": [
        "arn:aws:s3:::=BUCKET=",
        "arn:aws:s3:::=BUCKET=/*"
      ]
    },
    {
       "Effect": "Allow",
       "Action": [
           "s3:ListAllMyBuckets",
           "s3:ListBucket"
       ],
       "Resource": "*"
    }
  ]
}

```

> ⚠ Make sure that these two lines contain the actual name of your bucket. 😊
> 
> > ![image](https://global.discourse-cdn.com/meta/original/3X/5/f/5fa20c06b21ec84c6d6d087a662d6b353fd7e136.png)
> 
> 🌟 If you also intend to do S3 backups, you can include your backup bucket here too like this:
> 
> > ![image](https://global.discourse-cdn.com/meta/original/3X/3/9/39feef9d647cd55f800c480a79edfe2a4890d04e.png)

> ℹ If you chose **Option A** above (ACLs disabled), you can remove `s3:PutObjectAcl` and `s3:PutObjectVersionAcl` from the policy since they are only needed when `s3_use_acls` is enabled.

Then click on **Review Policy** and fill out the **Name** field. For example, you can call it `s3-discourse-policy`

Then click on **Create Policy** at the bottom.

### Creating a user account

Now that you’ve created the right policy, you’re ready to create the user account. Click on the **Users** link on the left side of the [IAM console](https://console.aws.amazon.com/iam/home#/users) and then the ![Add user](https://global.discourse-cdn.com/meta/original/3X/c/f/cf00df33f3a169aa52ec49951ff6787464552c80.png) button.

Type in a descriptive user name and make sure the “ **Programmatic access** ” checkbox is checked.

### Setting permissions

The next step in the process is to configure the user’s permissions. Click on the button that says **Next: Permissions** and then click on «Attach existing policies directly»:

 ![image](https://global.discourse-cdn.com/meta/original/3X/7/c/7c22bf4cc492caea147d1da679825b9aa1bdd97b.png)

Now search for the policy name you created in the previous step (in our case it’s `s3-discourse-policy`). When you find it, select the checkbox and click on **Next: Tags** , then **Next: Review** , then finally **Create user**.

Here’s the critical step: Make sure you either download the credentials (Download .csv) or you copy and paste somewhere safe both **Access key ID** and **Secret access key** values. We will need them in the next step.

## Discourse configuration

Now that you’ve properly set up S3, the final step is to configure your Discourse forum. These instructions should work, but **the preferred method is to use environment variables and a CDN** as described in [Configure an S3 compatible object storage provider for uploads](https://meta.discourse.org/t/configure-an-s3-compatible-object-storage-provider-for-uploads/148916).

Make sure you’re logged in with an administrator account and go the **Settings** section in the admin panel.

Type in “S3” in the textbox on the right to display only the relevant settings:

 ![image](https://global.discourse-cdn.com/meta/original/3X/a/d/ad46687ba7e291e3ba944dbfb3a2da253c1f0099.png)

You will need to:

- Check the “`enable s3 uploads`” checkbox to activate the feature
- Paste in both “`Access Key Id`” and “`Secret Access Key`” in their respective text fields
- Enter `=BUCKET=` in the “`s3 upload bucket`” field
- If you chose **Option A** (ACLs disabled) for your bucket, set `s3_use_acls` to **false**

You need to append a prefix to the bucket name if you want to use the same bucket for uploads and backups.

> **Examples of valid bucket settings**
>
> 1. Different buckets
> 
> 2. Different prefixes
> 
> 3. Prefix for backups

The “`s3_region`” setting is optional and defaults to “`US East (N. Virginia)`”. You should enter the location (eg. “EU (Frankfurt)”) that is nearest to your users for better performance. If you created the bucket manually, you’ll need to select the region you selected during the creation process.

## Enjoy

That’s it. From now on, all your images will be uploaded to and served from S3.

## Backups

Do you want store backups of your Discourse forum on S3 as well? Take a look at [Configure automatic backups for Discourse](https://meta.discourse.org/t/configure-automatic-backups-for-discourse/14855).

## Frequently Asked Questions

### I reused the same bucket for uploads and backups and now backups aren’t working. What should I do?

Name of your bucket for backups

The easiest solution is to append a path to the `s3_backup_bucket`. Here’s an example of how your settings should look afterwards.

- **`s3_upload_bucket`:** `=BACKUPS=`
- **`s3_backup_bucket`:** `=BACKUPS=/backups`

You can use the [S3 Console](https://s3.console.aws.amazon.com/s3) to [move existing backups](https://docs.aws.amazon.com/AmazonS3/latest/gsg/CopyingAnObject.html) into the new folder.

### Do I really need to use separate buckets for uploads and backups?

No, you don’t, but it’s usually the easiest way to set-up. Essentially you need to either use two different buckets or a prefix for the backup bucket. For example, the following combinations will work:

1. Different buckets

2. Different prefixes

3. Prefix for backups (not recommended unless you previously reused the same bucket – see above question)

### I’ve enabled S3 uploads in my Discourse instance (which has been going for a while); what do I do with the existing local uploads?

To migrate your existing uploads to S3, you can do a couple of **rake tasks**. To perform this, you need SSH access, root permissions, and have entered the discourse app (as per [Administrative Bulk Operations](https://meta.discourse.org/t/administrative-bulk-operations/118349)). Oh, and you [have to set some environmental variables in app.yml](https://meta.discourse.org/t/setting-up-file-and-image-uploads-to-s3/7229/175). Not for the faint-hearted.

Once you have done all that you are ready for the rake tasks:

```plaintext
rake uploads:migrate_to_s3

```

Once that is done, posts that need to be rebaked will be marked accordingly and will be rebaked by a regular task. If you have resources and are in a hurry, you can issue this command (which is recommended by the above rake task):

```plaintext
rake posts:rebake_uncooked_posts

```

Once the posts are all rebaked (and the uploads are working well) you no longer need to include uploads in your backups. And as a bonus, you will be able to [Restore a backup from the command line](https://meta.discourse.org/t/restore-a-backup-from-command-line/108034) in the event of catastrophe (just keep a copy of app.yml somewhere).

## One-way door

Unlike many configuration decisions in Discourse, note that using S3 is a “one-way door;” that is, a move that _cannot easily be reversed._ There is no safe or maintained way to move files out of S3 to be in the local uploads. In particular, the `migrate_to_s3` moves more than just post images to S3; files for which there is no reverse path. (For more details, see [Migrate\_from\_s3 problems](https://meta.discourse.org/t/migrate-from-s3-problems/119064)).

## Backing up your S3 assets

Using versioning, or syncing to a different region are all good strategies.

> Last edited by @JammyDodger 2024-05-25T10:58:50Z
> 
> > **Check document**
> >
> > Perform check on document:

---

<div class="post-metadata">

### Author: ![kuaza](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/kuaza/32/264151_2.png) [@kuaza](https://meta.discourse.org/u/kuaza)
#### Post date: [28 Aprile 2024, 4:42pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/248 "2024-04-28T16:42:16Z")

</div>

Questa narrazione deve essere aggiornata. O non posso. Dopo l’installazione, le immagini vengono caricate nel bucket, ma non riesco ad accedervi. Qualunque cosa abbia fatto, non ha funzionato. Qualcuno ha provato di recente e ci è riuscito?

---

<div class="post-metadata">

### Author: ![pfaffman](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/pfaffman/32/120154_2.png) [@pfaffman](https://meta.discourse.org/u/pfaffman)
#### Post date: [29 Aprile 2024, 1:17am UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/249 "2024-04-29T01:17:43Z")

</div>

Cosa succede quando provi ad accedervi?

Hai una cdn?

Quale servizio hai utilizzato?

Le immagini sono state caricate e le autorizzazioni del bucket non ti consentono di vederle?

Se il pm deve essere aggiornato, dovrai fornire maggiori informazioni su ciò che hai fatto e su cosa sta succedendo.

Il sito è pubblico? Dove

---

<div class="post-metadata">

### Author: ![kuaza](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/kuaza/32/264151_2.png) [@kuaza](https://meta.discourse.org/u/kuaza)
#### Post date: [29 Aprile 2024, 8:21pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/250 "2024-04-29T20:21:04Z")

</div>

Seguo esattamente la spiegazione. Carico le immagini. Tuttavia, le immagini non sono accessibili. URL di esempio: [https://awssorucevap24.s3.eu-central-1.amazonaws.com/original/2X/6/62c89621b0764112e0029bc91c957dd49d75d819.jpeg](https://awssorucevap24.s3.eu-central-1.amazonaws.com/original/2X/6/62c89621b0764112e0029bc91c957dd49d75d819.jpeg)

La sezione dei permessi appare così:

 ![image](https://global.discourse-cdn.com/meta/original/4X/c/a/3/ca35aafd05b31459f0c95876b0c36c5b45d9d005.png)

Non apro l’ACL quando installo il Bucket, non ci sono informazioni al riguardo e non riesco ad accedervi nemmeno quando modifico questa impostazione nei miei tentativi precedenti.

Nota aggiuntiva: non c’è l’impostazione “ **Accesso programmatico** ” quando si crea un utente, c’era molto tempo fa, ora non c’è più. Potrebbe essere correlato a questo? Oppure puoi spiegare come possiamo farlo nel nuovo sistema quando creiamo un utente?

Ho anche preparato il dominio cloudfront e cdn. Il mio unico problema è che non ho accesso ai file. Spero che possiamo trovare quello che mi è sfuggito 🙂

---

<div class="post-metadata">

### Author: ![Diego\_Santos](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/diego_santos/32/362118_2.png) [@Diego\_Santos](https://meta.discourse.org/u/Diego_Santos)
#### Post date: [4 Maggio 2024, 3:42pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/251 "2024-05-04T15:42:06Z")

</div>

![image](https://global.discourse-cdn.com/meta/original/4X/7/4/6/7465c998dc9606d003a20113354e07fa6e5f054f.png)

**rake uploads:migrate\_to\_s3**  
FileStore::ToS3MigrationError: Si prega di fornire le seguenti variabili d’ambiente: (FileStore::ToS3MigrationError)

- DISCOURSE\_S3\_BUCKET
- DISCOURSE\_S3\_REGION  
e uno tra
- DISCOURSE\_S3\_ACCESS\_KEY\_ID
- DISCOURSE\_S3\_SECRET\_ACCESS\_KEY  
o
- DISCOURSE\_S3\_USE\_IAM\_PROFILE

Per quanto vedo, non è né la chiave di accesso né il profilo IAM. Nel mio caso, sto usando il profilo IAM. Qualche raccomandazione qui?

---

<div class="post-metadata">

### Author: ![kuaza](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/kuaza/32/264151_2.png) [@kuaza](https://meta.discourse.org/u/kuaza)
#### Post date: [4 Maggio 2024, 10:46pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/252 "2024-05-04T22:46:08Z")

</div>

Penso che tu debba definire questi dati in un file yml. Prima, assicurati che il processo di caricamento funzioni e poi migra.

Comunque, come l’hai configurato? Ho provato a farlo, i file venivano caricati ma non si aprivano nel browser. Dava un errore di accesso negato.

> [@Cloudflare R2: Navigating Setup and Handling Configuration Errors](https://meta.discourse.org/t/cloudflare-r2-navigating-setup-and-handling-configuration-errors/305617/13?u=kuaza):
>
> Or maybe I sort-of owe you and apology. I do seem to have made it work, though I don’t have time to promise that I can write instructions that will allow you to make it work. DISCOURSE\_USE\_S3: true DISCOURSE\_S3\_REGION: 'auto' DISCOURSE\_S3\_ENDPOINT: https://=ACCOUNT\_ID=.r2.cloudflarestorage.com DISCOURSE\_S3\_ACCESS\_KEY\_ID: '=ACCESS\_KEY\_ID=' DISCOURSE\_S3\_SECRET\_ACCESS\_KEY: '=SECRET\_ACCESS\_KEY' DISCOURSE\_S3\_CDN\_URL: '=S3\_CDN\_URL=' DISCOURSE\_CDN\_URL: '=CDN\_URL=' DISCOURS…

---

<div class="post-metadata">

### Author: ![Diego\_Santos](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/diego_santos/32/362118_2.png) [@Diego\_Santos](https://meta.discourse.org/u/Diego_Santos)
#### Post date: [5 Maggio 2024, 1:53am UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/253 "2024-05-05T01:53:32Z")

</div>

Il caricamento e l’accesso in lettura pubblica funzionano correttamente.

Sto usando il ruolo e la policy IAM associati a EC2. Fammi sapere se desideri maggiori dettagli a riguardo.

Ah, credo di sapere cosa sta succedendo nel tuo caso. Controlla queste configurazioni:

Blocca accesso pubblico (impostazioni del bucket)

 ![image](https://global.discourse-cdn.com/meta/original/4X/7/2/1/72106b5502ad7c3a2767b65d634615a93db6341b.png)

Proprietà degli oggetti

 ![image](https://global.discourse-cdn.com/meta/original/4X/f/f/5/ff54de4897b98abfa08e58c451c24ba7c9c6ee2f.png)

Elenco di controllo degli accessi (ACL) – Probabilmente qui sta il trucco per te

 ![image](https://global.discourse-cdn.com/meta/original/4X/8/f/1/8f153e1189a9d3674ecdd0faadeff1131b268af4.png)

---

<div class="post-metadata">

### Author: ![kuaza](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/kuaza/32/264151_2.png) [@kuaza](https://meta.discourse.org/u/kuaza)
#### Post date: [5 Maggio 2024, 12:00pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/254 "2024-05-05T12:00:24Z")

</div>

Non ho visto nulla nella spiegazione riguardo all’attivazione dell’impostazione ACL, quindi ho provato a farlo senza toccarla ogni volta.

Non è più importante per me, passerò a Cloudflare R2. Questa spiegazione sarà molto utile per qualcun altro in futuro. Grazie.

---

<div class="post-metadata">

### Author: ![Diego\_Santos](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/diego_santos/32/362118_2.png) [@Diego\_Santos](https://meta.discourse.org/u/Diego_Santos)
#### Post date: [5 Maggio 2024, 12:55pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/255 "2024-05-05T12:55:19Z")

</div>

Non sono sicuro che questa sia la configurazione migliore, ma è così che l’ho trovata finora. Voglio chiedere al [@team](https://meta.discourse.org/groups/team) di dare un’occhiata e guidarci.

È questo il modo migliore per mantenerla sicura e funzionante correttamente?

---

<div class="post-metadata">

### Author: ![Diego\_Santos](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/diego_santos/32/362118_2.png) [@Diego\_Santos](https://meta.discourse.org/u/Diego_Santos)
#### Post date: [5 Maggio 2024, 12:56pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/256 "2024-05-05T12:56:05Z")

</div>

> [@kuaza](#):
>
> passa a cloudflare R2. Questo

Potresti condividere maggiori dettagli in merito?

---

<div class="post-metadata">

### Author: ![kuaza](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/kuaza/32/264151_2.png) [@kuaza](https://meta.discourse.org/u/kuaza)
#### Post date: [5 Maggio 2024, 1:01pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/257 "2024-05-05T13:01:21Z")

</div>

Dopo un po’ di sforzo, sono passato a R2 _(non dimentichiamo gli amici che hanno aiutato, rispetto)_. I file assets e uploads sono pubblicati su clouflare. L’unico problema è che non sono riuscito a caricare automaticamente i file theme-javascripts e stylesheets su R2. Ricercherò questo problema quando avrò tempo.

> [@Cloudflare R2: Navigating Setup and Handling Configuration Errors](https://meta.discourse.org/t/cloudflare-r2-navigating-setup-and-handling-configuration-errors/305617/6):
>
> I tried everything but I always get this error: Aws::S3::Errors::BadRequest I wonder what I’m missing? When I upload an image from the R2 panel, this image opens with the special cdn url. The problem is that the image cannot be loaded on the site. I created cors and opened all methods. [{ "AllowedOrigins": ["https://SITENAME.com"], "AllowedMethods": ["GET", "POST", "HEAD", "DELETE", "PUT"] } ] any ideas?

---

<div class="post-metadata">

### Author: ![Diego\_Santos](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/diego_santos/32/362118_2.png) [@Diego\_Santos](https://meta.discourse.org/u/Diego_Santos)
#### Post date: [5 Maggio 2024, 1:03pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/258 "2024-05-05T13:03:54Z")

</div>

È stata una decisione tecnica, di costo o entrambe?

---

<div class="post-metadata">

### Author: ![kuaza](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/kuaza/32/264151_2.png) [@kuaza](https://meta.discourse.org/u/kuaza)
#### Post date: [5 Maggio 2024, 1:14pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/259 "2024-05-05T13:14:21Z")

</div>

Il primo è tecnico, non sono riuscito a installare Amazon, ma stavo già usando Cloudflare, quindi ho pensato perché non installare il CDN da lì. E poi ho visto che è stata una buona decisione perché Cloudflare ha lanciato questo servizio per noi sviluppatori contro gli eccessivamente costosi sistemi cloud S3. Non è molto bello?

> **[Cloudflare R2 | Stockage d'objets sans frais de trafic sortant](https://www.cloudflare.com/fr-fr/developer-platform/products/r2/)**
>
> Cloudflare R2 est une solution de stockage d'objets compatible S3 et sans frais de trafic sortant. Déplacez librement les données et construisez l'architecture multicloud de votre choix.

---

<div class="post-metadata">

### Author: ![Diego\_Santos](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/diego_santos/32/362118_2.png) [@Diego\_Santos](https://meta.discourse.org/u/Diego_Santos)
#### Post date: [5 Maggio 2024, 1:18pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/260 "2024-05-05T13:18:34Z")

</div>

È bello. Ci darò un’occhiata più approfondita.

E per quanto riguarda l’integrazione in discourse? Com’è stata quell’esperienza?

Utilizzi anche Cloudflare WAF?

---

<div class="post-metadata">

### Author: ![kuaza](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/kuaza/32/264151_2.png) [@kuaza](https://meta.discourse.org/u/kuaza)
#### Post date: [5 Maggio 2024, 3:10pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/261 "2024-05-05T15:10:59Z")

</div>

No, non l’ho usato, in realtà non sono sicuro se ne avrò bisogno. Ma uso Cloudflare “ARGO”.

---

<div class="post-metadata">

### Author: ![catchthewavecoke](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/catchthewavecoke/32/423120_2.png) [@catchthewavecoke](https://meta.discourse.org/u/catchthewavecoke)
#### Post date: [8 Luglio 2024, 12:44am UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/262 "2024-07-08T00:44:55Z")

</div>

> [@Discourse](#):
>
> Quando imposti le autorizzazioni, assicurati di consentire le ACL pubbliche, altrimenti i caricamenti falliranno.

Ho un bucket S3 per caricamenti di immagini con ACL abilitate e un ruolo IAM configurato correttamente e assegnato all’istanza EC2 che esegue la mia istanza standalone. Tuttavia, gli URL delle immagini S3 nei miei post di test non sono visualizzabili. Vorrei ospitare immagini S3 in un bucket che possa essere visualizzato solo dagli utenti Discourse autenticati. Perché i riferimenti URL alle immagini S3 non includono un URL pre-firmato per un accesso corretto? Se accedo al file tramite la console S3 e richiedo un URL pre-firmato tramite AWS per un periodo di tempo definito, come 10 minuti, l’immagine verrà caricata come previsto, quindi so che può funzionare.

---

<div class="post-metadata">

### Author: ![wal](https://avatars.discourse-cdn.com/v4/letter/w/d6d6ee/32.png) [@wal](https://meta.discourse.org/u/wal)
#### Post date: [30 Luglio 2024, 6:15pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/263 "2024-07-30T18:15:10Z")

</div>

> [@kuaza](#):
>
> Penso che tu debba definire questi dati in un file yml. Prima, assicurati che il processo di caricamento funzioni e poi migra.

Siamo sicuri che debba essere memorizzato nel file app.yml?

L’ho fatto in questo modo;

```bash
# entra nell'app
cd /var/discourse
./launcher enter app

# passa le variabili d'ambiente con il comando al runtime
DISCOURSE_S3_BUCKET=my-bucket DISCOURSE_S3_REGION=us-east-1 DISCOURSE_S3_ACCESS_KEY_ID=abcdefg DISCOURSE_S3_SECRET_ACCESS_KEY=zxywqrst rake uploads:migrate_to_s3

```

L’ho fatto in questo modo poiché non volevo che la mia chiave di accesso rimanesse nel file YAML, dato che ne faccio il backup in vari posti. Passare la chiave segreta AWS attraverso l’ambiente è ~generalmente~ un po’ più “sicuro”. Penso, giusto? Non sono sicuro di quanto duri la cronologia dello scrollback all’interno del container dell’app, immagino che venga cancellata dopo il riavvio del container.

Volevo invece configurare l’accesso S3 nel modo “normale” memorizzando la chiave di accesso AWS e la chiave segreta nel file `~/.aws/credentials` del server, tuttavia, non sono del tutto sicuro di come ciò funzionerebbe con l’app in esecuzione all’interno del container.

Inoltre, come indicato nella guida qui, ti viene richiesto di copiare e incollare semplicemente le chiavi di accesso e segrete nell’interfaccia web delle impostazioni di amministrazione di Discourse e salvarle lì; non mi è chiaro dove vengano memorizzate queste chiavi nel backend, poiché salvarle qui non popola il file app.yml con esse. Quindi immagino che siano da qualche parte nel database Postgres? Speriamo crittografate, forse?

Spero che non memorizzando le chiavi di accesso e segrete AWS in app.yml, non avrò problemi in futuro? C’è qualche altro processo che richiede che le chiavi risiedano lì?

---

<div class="post-metadata">

### Author: ![wal](https://avatars.discourse-cdn.com/v4/letter/w/d6d6ee/32.png) [@wal](https://meta.discourse.org/u/wal)
#### Post date: [7 Agosto 2024, 4:53pm UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/264 "2024-08-07T16:53:40Z")

</div>

Ho abilitato AWS Cloudfront per una cache CDN davanti al mio bucket S3, configurato come descritto qui. Tuttavia, la configurazione di Cloudfront ha richiesto alcune modifiche alle policy di accesso S3. In particolare, sembrano esserci alcune policy che limiterebbero l’accesso al bucket S3 solo a Cloudfront, invece dell’accesso pubblico suggerito da questa guida. Qualcuno è in grado di esaminare quali dovrebbero essere le corrette policy di autorizzazione del bucket S3 se si utilizza la CDN Cloudfront con il proprio bucket S3 su Discourse? Attualmente, la mia CDN funziona, ma non sono sicuro se sia necessario rimuovere eventuali autorizzazioni di accesso superflue dal bucket S3.

---

<div class="post-metadata">

### Author: ![Bathinda](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/bathinda/32/135888_2.png) [@Bathinda](https://meta.discourse.org/u/Bathinda)
#### Post date: [31 Agosto 2024, 10:55am UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/265 "2024-08-31T10:55:20Z")

</div>

Ho usato questa policy del bucket mostrata nel primo post di questo argomento, su un nuovo bucket AWS. Ma oggi, mi dà un errore di sintassi JSON.

> **Errore nella policy fornita nell'OP/1° post dell'argomento:**
>
> Dà errori "Missing Principal", "Unsupported Policy" nelle righe 4, 23, 26, 29, e quando riesco a correggere quegli errori in qualche modo leggendo la documentazione AWS, allora appare "Json Syntax Error" verso la fine del codice.
> 
> ```plaintext
> {
> "Version": "2012-10-17",
> "Statement": [
> {
> "Effect": "Allow",
> "Action": [
> "s3:List*",
> "s3:Get*",
> "s3:AbortMultipartUpload",
> "s3:DeleteObject",
> "s3:PutObject",
> "s3:PutObjectAcl",
> "s3:PutObjectVersionAcl",
> "s3:PutLifecycleConfiguration",
> "s3:CreateBucket",
> "s3:PutBucketCORS"
> ],
> "Resource": [
> "arn:aws:s3:::your-uploads-bucket",
> "arn:aws:s3:::your-uploads-bucket/*"
> ]
> },
> {
> "Effect": "Allow",
> "Action": [
> "s3:ListAllMyBuckets",
> "s3:ListBucket"
> ],
> "Resource": "*"
> }
> ]
> }
> 
> ```

> **Quello che ho provato a creare, che non mostra errori di sintassi nella console, tranne un errore "Invalid Principal", che non sono riuscito a superare**
>
> #### Usato i miei nomi di bucket
> 
> ```plaintext
> {
> "Id": "Policy1725098748430",
> "Version": "2012-10-17",
> "Statement": [
> {
> "Sid": "Stmt1725098741436",
> "Action": [
> "s3:AbortMultipartUpload",
> "s3:CreateBucket",
> "s3:DeleteObject",
> "s3:GetObject",
> "s3:List*",
> "s3:ListBucket",
> "s3:ListBucketMultipartUploads",
> "s3:PutBucketCORS",
> "s3:PutLifecycleConfiguration",
> "s3:PutObject",
> "s3:PutObjectAcl",
> "s3:PutObjectVersionAcl"
> ],
> "Effect": "Allow",
> "Resource": [
> "arn:aws:s3:::t9478010203",
> "arn:aws:s3:::t9478010203/backups/",
> "arn:aws:s3:::t9478010203/uploads/"
> ],
> "Principal": {
> "AWS": [
> "123456789012"
> ]
> }
> }
> ]
> }
> 
> ```

---

<div class="post-metadata">

### Author: ![nathank](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/nathank/32/290039_2.png) [@nathank](https://meta.discourse.org/u/nathank)
#### Post date: [6 Settembre 2024, 8:47am UTC](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229/266 "2024-09-06T08:47:34Z")

</div>

Questo argomento necessita davvero di un aggiornamento: stavo giusto armeggiando con la policy in S3/IAM e ho notato anch’io gli errori. Fortunatamente sembra funzionare bene!

Mi chiedo se qualcuno con le competenze e le conoscenze necessarie potrebbe dare un’occhiata e aggiornare quella che _dovrebbe_ essere la policy. @pfaffman?

[Next page](https://meta.discourse.org/t/set-up-file-and-image-uploads-to-s3/7229.md?page=2)
