

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Tutorial: uso di un trigger Amazon S3 per richiamare una funzione Lambda
<a name="with-s3-example"></a>

In questo tutorial si utilizzerà la console per creare una funzione Lambda e configurare un trigger per un bucket Amazon Simple Storage Service (Amazon S3). Ogni volta che aggiungi un oggetto al tuo bucket Amazon S3, la funzione viene eseguita e invia il tipo di oggetto in Amazon Logs. CloudWatch 

![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/services-s3-example/s3_tut_config.png)


Questo tutorial dimostra come:

1. Crea un bucket Amazon S3.

1. Crea una funzione Lambda che restituisce il tipo di oggetto in un bucket Amazon S3.

1. Configura un trigger Lambda che richiami la tua funzione quando gli oggetti vengono caricati nel bucket.

1. Prova la tua funzione, prima con un evento fittizio e poi usando il trigger.

Completando questi passaggi, imparerai come configurare una funzione Lambda da eseguire ogni volta che vengono aggiunti o eliminati oggetti da un bucket Amazon S3. Puoi completare questo tutorial soltanto dalla Console di gestione AWS.

## Crea un bucket Amazon S3
<a name="with-s3-example-create-bucket"></a>

![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps1.png)


**Come creare un bucket Amazon S3.**

1. Apri la [console Amazon S3](https://console.aws.amazon.com/s3) e seleziona la pagina **Bucket per uso generico**.

1. Seleziona quello più Regione AWS vicino alla tua posizione geografica. Puoi modificare la regione utilizzando l'elenco a discesa nella parte superiore dello schermo. Più avanti nel tutorial, è necessario creare la funzione Lambda nella stessa regione.  
![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/console_region_select.png)

1. Scegliere **Create bucket (Crea bucket)**.

1. In **General configuration (Configurazione generale)**, eseguire le operazioni seguenti:

   1. Per **Tipo di secchio**, assicurati che sia selezionata l'**opzione Uso generale**.

   1. Per **Nome del bucket**, inserisci un nome univoco globale che soddisfi le [regole di denominazione dei bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html) di Amazon S3. I nomi dei bucket possono contenere solo lettere minuscole, numeri, punti (.) e trattini (-).

1. Lascia tutte le altre opzioni impostate sui valori predefiniti e scegli **Crea bucket**.

## Caricamento di un oggetto di test in un bucket
<a name="with-s3-example-upload-test-object"></a>

![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps2.png)


**Caricamento di un oggetto di test**

1. Apri la pagina [Bucket](https://console.aws.amazon.com/s3/buckets) della console Amazon S3 e scegli il bucket che hai creato durante il passaggio precedente.

1. Scegli **Carica**.

1. Scegli **Aggiungi file** e seleziona l'oggetto da caricare. È possibile selezionare qualsiasi file (ad esempio, `HappyFace.jpg`).

1. Seleziona **Apri**, quindi **Carica**.

Più avanti nel tutorial, testerai la funzione Lambda utilizzando questo oggetto.

## Creazione di una policy di autorizzazione
<a name="with-s3-example-create-policy"></a>

![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps3.png)


Crea una politica di autorizzazioni che consenta a Lambda di ottenere oggetti da un bucket Amazon S3 e di scriverli su Amazon Logs. CloudWatch 

**Come creare la policy**

1. Apri la pagina [Policies (Policy)](https://console.aws.amazon.com/iam/home#/policies) nella console IAM.

1. Scegli **Crea policy**.

1. Scegliere la scheda **JSON** e quindi incollare la seguente policy personalizzata nell'editor JSON.

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "logs:PutLogEvents",
                   "logs:CreateLogGroup",
                   "logs:CreateLogStream"
               ],
               "Resource": "arn:aws:logs:*:*:*"
           },
           {
               "Effect": "Allow",
               "Action": [
                   "s3:GetObject"
               ],
               "Resource": "arn:aws:s3:::*/*"
           }
       ]
   }
   ```

------

1. Scegliere **Next: Tags (Successivo: Tag)**.

1. Scegliere **Next:Review (Successivo: Rivedi)**.

1. In **Rivedi policy**, per **Nome** della policy inserisci **s3-trigger-tutorial**.

1. Scegli **Crea policy**.

## Creazione di un ruolo di esecuzione
<a name="with-s3-example-create-role"></a>

![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps4.png)


Un [ruolo di esecuzione](lambda-intro-execution-role.md) è un ruolo AWS Identity and Access Management (IAM) che concede a una funzione Lambda l'autorizzazione all' Servizi AWS accesso e alle risorse. In questa fase, creare un ruolo di esecuzione utilizzando la policy di autorizzazioni creata nel passaggio precedente.

**Creazione di un ruolo di esecuzione e collegamento di una policy di autorizzazione personalizzata**

1. Aprire la [pagina Roles (Ruoli)](https://console.aws.amazon.com/iam/home#/roles) della console IAM.

1. Scegli **Crea ruolo**.

1. Per il tipo di entità attendibile, scegli **Servizio AWS **, quindi per il caso d'uso seleziona **Lambda**.

1. Scegli **Next (Successivo)**.

1. Nella casella di ricerca delle policy, immettere **s3-trigger-tutorial**.

1. Nei risultati della ricerca, seleziona la policy creata (`s3-trigger-tutorial`), quindi scegli **Next** (Successivo).

1. In **Role details** (Dettagli del ruolo), per **Role name** (Nome del ruolo), specifica **lambda-s3-trigger-role**, quindi scegli **Create role** (Crea ruolo).

## Creazione della funzione Lambda
<a name="with-s3-example-create-function"></a>

![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps5.png)


Crea una funzione Lambda nella console usando il runtime Python 3.14.

**Creazione della funzione Lambda**

1. Aprire la pagina [Funzioni](https://console.aws.amazon.com/lambda/home#/functions) della console Lambda.

1. Assicurati di lavorare nello stesso bucket in Regione AWS cui hai creato il tuo bucket Amazon S3. Puoi modificare la regione utilizzando l'elenco a discesa nella parte superiore dello schermo.  
![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/console_region_select.png)

1. Scegli **Crea funzione**.

1. Scegli **Crea da zero**.

1. In **Basic information (Informazioni di base)** eseguire queste operazioni:

   1. Nel campo **Nome funzione**, inserisci `s3-trigger-tutorial`.

   1. Per **Runtime**, scegli **Python 3.14**.

   1. In **Architecture** (Architettura), scegli **x86\$164**.

1. Nella scheda **Modifica ruolo di esecuzione predefinito**, effettua le seguenti operazioni:

   1. Espandi la scheda, quindi scegli **Utilizza un ruolo esistente**.

   1. Seleziona il `lambda-s3-trigger-role` che hai creato in precedenza.

1. Scegli **Crea funzione**.

## Implementazione del codice della funzione
<a name="with-s3-example-deploy-code"></a>

![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps6.png)


Questo tutorial utilizza il runtime di Python 3.14, ma abbiamo anche fornito file di codice di esempio per altri runtime. Per visualizzare il codice per il runtime che ti interessa, seleziona la scheda corrispondente nella casella seguente.

La funzione Lambda recupera il nome della chiave dell'oggetto caricato e il nome del bucket dal parametro `event` che riceve da Amazon S3. La funzione utilizza quindi il metodo [get\$1object](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/get_object.html) di AWS SDK per Python (Boto3) per recuperare i metadati dell'oggetto, incluso il tipo di contenuto (tipo MIME) dell'oggetto caricato.

**Implementazione del codice della funzione**

1. Scegli la scheda **Python** nella casella seguente e copia il codice.

------
#### [ .NET ]

**SDK per .NET**  
 C'è altro su. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di [Esempi serverless](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda). 
Utilizzo di un evento S3 con Lambda tramite .NET.  

   ```
   // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   // SPDX-License-Identifier: Apache-2.0
   ﻿using System.Threading.Tasks;
   using Amazon.Lambda.Core;
   using Amazon.S3;
   using System;
   using Amazon.Lambda.S3Events;
   using System.Web;
   
   // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
   [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
   
   namespace S3Integration
   {
       public class Function
       {
           private static AmazonS3Client _s3Client;
           public Function() : this(null)
           {
           }
   
           internal Function(AmazonS3Client s3Client)
           {
               _s3Client = s3Client ?? new AmazonS3Client();
           }
   
           public async Task<string> Handler(S3Event evt, ILambdaContext context)
           {
               try
               {
                   if (evt.Records.Count <= 0)
                   {
                       context.Logger.LogLine("Empty S3 Event received");
                       return string.Empty;
                   }
   
                   var bucket = evt.Records[0].S3.Bucket.Name;
                   var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key);
   
                   context.Logger.LogLine($"Request is for {bucket} and {key}");
   
                   var objectResult = await _s3Client.GetObjectAsync(bucket, key);
   
                   context.Logger.LogLine($"Returning {objectResult.Key}");
   
                   return objectResult.Key;
               }
               catch (Exception e)
               {
                   context.Logger.LogLine($"Error processing request - {e.Message}");
   
                   return string.Empty;
               }
           }
       }
   }
   ```

------
#### [ Go ]

**SDK per Go V2**  
 C'è dell'altro GitHub. Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di [Esempi serverless](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda). 
Utilizzo di un evento S3 con Lambda tramite Go.  

   ```
   // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   // SPDX-License-Identifier: Apache-2.0
   package main
   
   import (
   	"context"
   	"log"
   
   	"github.com/aws/aws-lambda-go/events"
   	"github.com/aws/aws-lambda-go/lambda"
   	"github.com/aws/aws-sdk-go-v2/config"
   	"github.com/aws/aws-sdk-go-v2/service/s3"
   )
   
   func handler(ctx context.Context, s3Event events.S3Event) error {
   	sdkConfig, err := config.LoadDefaultConfig(ctx)
   	if err != nil {
   		log.Printf("failed to load default config: %s", err)
   		return err
   	}
   	s3Client := s3.NewFromConfig(sdkConfig)
   
   	for _, record := range s3Event.Records {
   		bucket := record.S3.Bucket.Name
   		key := record.S3.Object.URLDecodedKey
   		headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput{
   			Bucket: &bucket,
   			Key:    &key,
   		})
   		if err != nil {
   			log.Printf("error getting head of object %s/%s: %s", bucket, key, err)
   			return err
   		}
   		log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType)
   	}
   
   	return nil
   }
   
   func main() {
   	lambda.Start(handler)
   }
   ```

------
#### [ Java ]

**SDK per Java 2.x**  
 C'è dell'altro GitHub. Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di [Esempi serverless](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda). 
Utilizzo di un evento S3 con Lambda tramite Java.  

   ```
   // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   // SPDX-License-Identifier: Apache-2.0
   package example;
   
   import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
   import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
   import software.amazon.awssdk.services.s3.S3Client;
   
   import com.amazonaws.services.lambda.runtime.Context;
   import com.amazonaws.services.lambda.runtime.RequestHandler;
   import com.amazonaws.services.lambda.runtime.events.S3Event;
   import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord;
   
   import org.slf4j.Logger;
   import org.slf4j.LoggerFactory;
   
   public class Handler implements RequestHandler<S3Event, String> {
       private static final Logger logger = LoggerFactory.getLogger(Handler.class);
       @Override
       public String handleRequest(S3Event s3event, Context context) {
           try {
             S3EventNotificationRecord record = s3event.getRecords().get(0);
             String srcBucket = record.getS3().getBucket().getName();
             String srcKey = record.getS3().getObject().getUrlDecodedKey();
   
             S3Client s3Client = S3Client.builder().build();
             HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey);
   
             logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType());
   
             return "Ok";
           } catch (Exception e) {
             throw new RuntimeException(e);
           }
       }
   
       private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) {
           HeadObjectRequest headObjectRequest = HeadObjectRequest.builder()
                   .bucket(bucket)
                   .key(key)
                   .build();
           return s3Client.headObject(headObjectRequest);
       }
   }
   ```

------
#### [ JavaScript ]

**SDK per JavaScript (v3)**  
 C'è altro da fare. GitHub Trova l’esempio completo e scopri come eseguire la configurazione e l’esecuzione nel repository di [Esempi serverless](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda). 
Consumo di un evento S3 con JavaScript Lambda utilizzando.  

   ```
   import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3";
   
   const client = new S3Client();
   
   export const handler = async (event, context) => {
   
       // Get the object from the event and show its content type
       const bucket = event.Records[0].s3.bucket.name;
       const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
   
       try {
           const { ContentType } = await client.send(new HeadObjectCommand({
               Bucket: bucket,
               Key: key,
           }));
   
           console.log('CONTENT TYPE:', ContentType);
           return ContentType;
   
       } catch (err) {
           console.log(err);
           const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
           console.log(message);
           throw new Error(message);
       }
   };
   ```
Consumo di un evento S3 con TypeScript Lambda utilizzando.  

   ```
   // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   // SPDX-License-Identifier: Apache-2.0
   import { S3Event } from 'aws-lambda';
   import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3';
   
   const s3 = new S3Client({ region: process.env.AWS_REGION });
   
   export const handler = async (event: S3Event): Promise<string | undefined> => {
     // Get the object from the event and show its content type
     const bucket = event.Records[0].s3.bucket.name;
     const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
     const params = {
       Bucket: bucket,
       Key: key,
     };
     try {
       const { ContentType } = await s3.send(new HeadObjectCommand(params));
       console.log('CONTENT TYPE:', ContentType);
       return ContentType;
     } catch (err) {
       console.log(err);
       const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
       console.log(message);
       throw new Error(message);
     }
   };
   ```

------
#### [ PHP ]

**SDK per PHP**  
 C'è altro da fare. GitHub Trova l’esempio completo e scopri come eseguire la configurazione e l’esecuzione nel repository di [Esempi serverless](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda). 
Utilizzo di un evento S3 con Lambda tramite PHP.  

   ```
   <?php
   
   use Bref\Context\Context;
   use Bref\Event\S3\S3Event;
   use Bref\Event\S3\S3Handler;
   use Bref\Logger\StderrLogger;
   
   require __DIR__ . '/vendor/autoload.php';
   
   
   class Handler extends S3Handler 
   {
       private StderrLogger $logger;
       public function __construct(StderrLogger $logger)
       {
           $this->logger = $logger;
       }
       
       public function handleS3(S3Event $event, Context $context) : void
       {
           $this->logger->info("Processing S3 records");
   
           // Get the object from the event and show its content type
           $records = $event->getRecords();
           
           foreach ($records as $record) 
           {
               $bucket = $record->getBucket()->getName();
               $key = urldecode($record->getObject()->getKey());
   
               try {
                   $fileSize = urldecode($record->getObject()->getSize());
                   echo "File Size: " . $fileSize . "\n";
                   // TODO: Implement your custom processing logic here
               } catch (Exception $e) {
                   echo $e->getMessage() . "\n";
                   echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n";
                   throw $e;
               }
           }
       }
   }
   
   $logger = new StderrLogger();
   return new Handler($logger);
   ```

------
#### [ Python ]

**SDK per Python (Boto3)**  
 C'è dell'altro GitHub. Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di [Esempi serverless](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda). 
Utilizzo di un evento S3 con Lambda tramite Python.  

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   import json
   import urllib.parse
   import boto3
   
   print('Loading function')
   
   s3 = boto3.client('s3')
   
   
   def lambda_handler(event, context):
       #print("Received event: " + json.dumps(event, indent=2))
   
       # Get the object from the event and show its content type
       bucket = event['Records'][0]['s3']['bucket']['name']
       key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
       try:
           response = s3.get_object(Bucket=bucket, Key=key)
           print("CONTENT TYPE: " + response['ContentType'])
           return response['ContentType']
       except Exception as e:
           print(e)
           print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
           raise e
   ```

------
#### [ Ruby ]

**SDK per Ruby**  
 C'è dell'altro GitHub. Trova l’esempio completo e scopri come eseguire la configurazione e l’esecuzione nel repository di [Esempi serverless](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda). 
Utilizzo di un evento S3 con Lambda tramite Ruby.  

   ```
   require 'json'
   require 'uri'
   require 'aws-sdk'
   
   puts 'Loading function'
   
   def lambda_handler(event:, context:)
     s3 = Aws::S3::Client.new(region: 'region') # Your AWS region
     # puts "Received event: #{JSON.dump(event)}"
   
     # Get the object from the event and show its content type
     bucket = event['Records'][0]['s3']['bucket']['name']
     key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8)
     begin
       response = s3.get_object(bucket: bucket, key: key)
       puts "CONTENT TYPE: #{response.content_type}"
       return response.content_type
     rescue StandardError => e
       puts e.message
       puts "Error getting object #{key} from bucket #{bucket}. Make sure they exist and your bucket is in the same region as this function."
       raise e
     end
   end
   ```

------
#### [ Rust ]

**SDK per Rust**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di [Esempi serverless](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda). 
Utilizzo di un evento S3 con Lambda tramite Rust.  

   ```
   // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   // SPDX-License-Identifier: Apache-2.0
   use aws_lambda_events::event::s3::S3Event;
   use aws_sdk_s3::{Client};
   use lambda_runtime::{run, service_fn, Error, LambdaEvent};
   
   
   /// Main function
   #[tokio::main]
   async fn main() -> Result<(), Error> {
       tracing_subscriber::fmt()
           .with_max_level(tracing::Level::INFO)
           .with_target(false)
           .without_time()
           .init();
   
       // Initialize the AWS SDK for Rust
       let config = aws_config::load_from_env().await;
       let s3_client = Client::new(&config);
   
       let res = run(service_fn(|request: LambdaEvent<S3Event>| {
           function_handler(&s3_client, request)
       })).await;
   
       res
   }
   
   async fn function_handler(
       s3_client: &Client,
       evt: LambdaEvent<S3Event>
   ) -> Result<(), Error> {
       tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS");
   
       if evt.payload.records.len() == 0 {
           tracing::info!("Empty S3 event received");
       }
   
       let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist");
       let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist");
   
       tracing::info!("Request is for {} and object {}", bucket, key);
   
       let s3_get_object_result = s3_client
           .get_object()
           .bucket(bucket)
           .key(key)
           .send()
           .await;
   
       match s3_get_object_result {
           Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"),
           Err(_) => tracing::info!("Failure with S3 Get Object request")
       }
   
       Ok(())
   }
   ```

------

1. Nel riquadro **Codice sorgente** della console Lambda, incolla il codice nell'editor di codice, sostituendo il codice creato da Lambda.

1. Nella sezione **DEPLOY**, scegli **Implementa** per aggiornare il codice della tua funzione:  
![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/getting-started-tutorial/deploy-console.png)

## Creazione del trigger Amazon S3
<a name="with-s3-example-create-trigger"></a>

![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps7.png)


**Creazione del trigger Amazon S3**

1. Nel riquadro **Panoramica della funzione**, scegli **Aggiungi trigger**.  
![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/overview-trigger.png)

1. Seleziona **S3**.

1. In **Bucket**, seleziona il bucket che hai creato in precedenza nel tutorial.

1. In **Tipi di eventi**, verifica che sia selezionata l'opzione **Tutti gli eventi di creazione di oggetti**.

1. In **Invocazione ricorsiva**, seleziona la casella di controllo per confermare che non è consigliabile utilizzare lo stesso bucket Amazon S3 per input e output.

1. Scegliere **Aggiungi**.

**Nota**  
Quando crei un trigger Amazon S3 per una funzione Lambda utilizzando la console Lambda, Amazon S3 configura una [notifica degli eventi](https://docs.aws.amazon.com/AmazonS3/latest/userguide/EventNotifications.html) sul bucket specificato. Prima di configurare questa notifica di evento, Amazon S3 esegue una serie di controlli per confermare che la destinazione dell'evento esista e disponga delle policy IAM richieste. Amazon S3 esegue questi test anche su qualsiasi altra notifica di eventi configurata per quel bucket.  
A causa di questo controllo, se il bucket ha precedentemente configurato destinazioni di eventi per risorse che non esistono più o per risorse che non dispongono delle policy di autorizzazione richieste, Amazon S3 non sarà in grado di creare la nuova notifica di evento. Verrà visualizzato il seguente messaggio di errore che indica che non è stato possibile creare il trigger:  

```
An error occurred when creating the trigger: Unable to validate the following destination configurations.
```
Puoi visualizzare questo errore se in precedenza hai configurato un trigger per un'altra funzione Lambda utilizzando lo stesso bucket e da allora hai eliminato la funzione o modificato le sue policy di autorizzazioni.

## Test di una funzione Lambda con un evento fittizio
<a name="with-s3-example-test-dummy-event"></a>

![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps8.png)


**Test della funzione Lambda con un evento fittizio**

1. Nella pagina della console Lambda della funzione, seleziona la scheda **Test**.  
![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/test-tab.png)

1. Per **Event name (Nome evento)** immettere `MyTestEvent`.

1. Nella sezione **JSON dell'evento**, incolla il seguente evento di test. Assicurati di sostituire i seguenti valori:
   + Sostituisci `us-east-1` con la regione in cui è stato creato il bucket Amazon S3.
   + Sostituisci entrambe le istanze di `amzn-s3-demo-bucket` con il nome del bucket Amazon S3.
   + Sostituisci `test%2FKey` con il nome dell'oggetto di test che hai caricato in precedenza nel tuo bucket (ad esempio, `HappyFace.jpg`).

   ```
   {
     "Records": [
       {
         "eventVersion": "2.0",
         "eventSource": "aws:s3",
         "awsRegion": "us-east-1",
         "eventTime": "1970-01-01T00:00:00.000Z",
         "eventName": "ObjectCreated:Put",
         "userIdentity": {
           "principalId": "EXAMPLE"
         },
         "requestParameters": {
           "sourceIPAddress": "127.0.0.1"
         },
         "responseElements": {
           "x-amz-request-id": "EXAMPLE123456789",
           "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH"
         },
         "s3": {
           "s3SchemaVersion": "1.0",
           "configurationId": "testConfigRule",
           "bucket": {
             "name": "amzn-s3-demo-bucket",
             "ownerIdentity": {
               "principalId": "EXAMPLE"
             },
             "arn": "arn:aws:s3:::amzn-s3-demo-bucket"
           },
           "object": {
             "key": "test%2Fkey",
             "size": 1024,
             "eTag": "0123456789abcdef0123456789abcdef",
             "sequencer": "0A1B2C3D4E5F678901"
           }
         }
       }
     ]
   }
   ```

1. Scegli **Save** (Salva).

1. Scegli **Test (Esegui test)**.

1. Se la tua funzione viene eseguita correttamente, vedrai un output simile al seguente nella scheda **Risultati dell'esecuzione**.

   ```
   Response
   "image/jpeg"
   
   Function Logs
   START RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Version: $LATEST
   2021-02-18T21:40:59.280Z    12b3cae7-5f4e-415e-93e6-416b8f8b66e6    INFO    INPUT BUCKET AND KEY:  { Bucket: 'amzn-s3-demo-bucket', Key: 'HappyFace.jpg' }
   2021-02-18T21:41:00.215Z    12b3cae7-5f4e-415e-93e6-416b8f8b66e6    INFO    CONTENT TYPE: image/jpeg
   END RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6
   REPORT RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6    Duration: 976.25 ms    Billed Duration: 977 ms    Memory Size: 128 MB    Max Memory Used: 90 MB    Init Duration: 430.47 ms        
   
   Request ID
   12b3cae7-5f4e-415e-93e6-416b8f8b66e6
   ```

### Test della funzione Lambda mediante il trigger Amazon S3
<a name="with-s3-example-test-s3-trigger"></a>

![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps9.png)


Per verificare la funzione con il trigger configurato, carica un oggetto sul bucket Amazon S3 utilizzando la console. Per verificare che la funzione Lambda sia stata eseguita come previsto, usa CloudWatch Logs per visualizzare l'output della funzione.

**Caricamento di un oggetto nel bucket Amazon S3**

1. Apri la pagina [Bucket](https://console.aws.amazon.com/s3/buckets) della console Amazon S3 e scegli il bucket che hai creato in precedenza.

1. Scegli **Carica**.

1. Scegli **Aggiungi file** e usa il selettore di file per scegliere un oggetto da caricare. Tale oggetto può essere qualsiasi file desideri.

1. Seleziona **Apri**, quindi **Carica**.

**Per verificare l'invocazione della funzione utilizzando Logs CloudWatch**

1. Aprire la console [CloudWatch](https://console.aws.amazon.com/cloudwatch/home).

1. Assicurati di lavorare nella stessa modalità in Regione AWS cui hai creato la funzione Lambda. Puoi modificare la regione utilizzando l'elenco a discesa nella parte superiore dello schermo.  
![\[\]](http://docs.aws.amazon.com/it_it/lambda/latest/dg/images/console_region_select.png)

1. Scegli **Log** e quindi **Gruppi di log**.

1. Scegli il nome del gruppo di log per la funzione (`/aws/lambda/s3-trigger-tutorial`).

1. In **Flussi di log**, scegli il flusso di log più recente.

1. Se la tua funzione è stata richiamata correttamente in risposta al trigger Amazon S3, vedrai un output simile al seguente. Il `CONTENT TYPE` visualizzato dipende dal tipo di file che hai caricato nel bucket.

   ```
   2022-05-09T23:17:28.702Z	0cae7f5a-b0af-4c73-8563-a3430333cc10	INFO	CONTENT TYPE: image/jpeg
   ```

## Pulizia delle risorse
<a name="cleanup"></a>

Ora è possibile eliminare le risorse create per questo tutorial, a meno che non si voglia conservarle. Eliminando AWS le risorse che non utilizzi più, eviti addebiti inutili a tuo carico. Account AWS

**Per eliminare la funzione Lambda**

1. Aprire la pagina [Functions (Funzioni)](https://console.aws.amazon.com/lambda/home#/functions) della console Lambda.

1. Selezionare la funzione creata.

1. Scegliere **Operazioni**, **Elimina**.

1. Inserisci **confirm** nel campo di immissione del testo, quindi scegli **Elimina**.

**Come eliminare il ruolo di esecuzione**

1. Aprire la pagina [Ruoli](https://console.aws.amazon.com/iam/home#/roles) della console IAM.

1. Selezionare il ruolo di esecuzione creato.

1. Scegliere **Elimina**.

1. Inserisci il nome del ruolo nel campo di immissione testo e seleziona **Delete** (Elimina).

**Per eliminare il bucket S3**

1. Aprire la [console Amazon S3](https://console.aws.amazon.com//s3/home#).

1. Selezionare il bucket creato in precedenza.

1. Scegli **Elimina**.

1. Inserisci il nome del bucket nel campo di immissione testo.

1. Scegli **Delete Bucket** (Elimina bucket).

## Fasi successive
<a name="next-steps"></a>

In [Tutorial: uso di un trigger Amazon S3 per creare immagini in miniatura](with-s3-tutorial.md), il trigger Amazon S3 richiama una funzione per creare un'immagine in miniatura per ogni file immagine caricato nel bucket. Questo tutorial richiede un livello moderato di conoscenza del AWS dominio Lambda. Dimostra come creare risorse utilizzando AWS Command Line Interface (AWS CLI) e come creare un pacchetto di distribuzione di archivi di file.zip per la funzione e le sue dipendenze.