

Avviso di fine del supporto: il 20 maggio 2026, AWS terminerà il supporto per AWS IoT Events. Dopo il 20 maggio 2026, non potrai più accedere alla AWS IoT Events console o AWS IoT Events alle risorse. Per ulteriori informazioni, consulta [AWS IoT Events Fine del supporto](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-end-of-support.html).

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à.

# Creazione di una funzione Lambda in AWS IoT Events
<a name="alarms-create-lambda"></a>

AWS IoT Events fornisce una funzione Lambda che consente agli allarmi di inviare e ricevere notifiche e-mail e SMS.

## Requisiti
<a name="alarms-lambda-requirements"></a>

I seguenti requisiti si applicano quando si crea una funzione Lambda per gli allarmi:
+ Se il tuo allarme invia notifiche SMS, assicurati che Amazon SNS sia configurato per recapitare messaggi SMS.
  + Per ulteriori informazioni, consulta la seguente documentazione:
    + [Messaggi di testo mobili con identità Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/sns-mobile-phone-number-as-subscriber.html) [e Origination per i messaggi SMS di Amazon SNS nella Amazon Simple](https://docs.aws.amazon.com/sns/latest/dg/channels-sms-originating-identities.html) *Notification Service Developer Guide.*
    + [Cos'è AWS End User Messaging SMS?](https://docs.aws.amazon.com/sms-voice/latest/userguide/what-is-sms-mms.html) nella *Guida AWS SMS per l'utente*.
+ Se il tuo allarme invia notifiche e-mail o SMS, devi disporre di un ruolo IAM che AWS Lambda consenta di lavorare con Amazon SES e Amazon SNS.

  

  Politica di esempio:

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

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Effect": "Allow",
              "Action": [
                  "ses:GetIdentityVerificationAttributes",
                  "ses:SendEmail",
                  "ses:VerifyEmailIdentity"
              ],
              "Resource": "*"
          },
          {
              "Effect": "Allow",
              "Action": [
                  "sns:Publish",
                  "sns:OptInPhoneNumber",
                  "sns:CheckIfPhoneNumberIsOptedOut",
                  "sms-voice:DescribeOptedOutNumbers"
              ],
              "Resource": "*"
          },
          {
              "Effect": "Deny",
              "Action": "sns:Publish",
              "Resource": "arn:aws:sns:*:*:*"
          },
          {
            "Effect" : "Allow",
            "Action" : [
              "logs:CreateLogGroup",
              "logs:CreateLogStream",
              "logs:PutLogEvents"
            ],
            "Resource" : "*"
          }
      ]
  }
  ```

------
+ È necessario scegliere la stessa AWS regione per entrambi AWS IoT Events e AWS Lambda. Per l'elenco delle regioni supportate, consulta [AWS IoT Events endpoint e quote](https://docs.aws.amazon.com/general/latest/gr/iot-events.html) e [AWS Lambda endpoint e quote](https://docs.aws.amazon.com/general/latest/gr/lambda-service.html) in. *Riferimenti generali di Amazon Web Services*

# Implementa una funzione Lambda per l'utilizzo AWS IoT Events CloudFormation
<a name="alarms-create-lambda-cfn"></a>

Questo tutorial utilizza un CloudFormation modello per distribuire una funzione Lambda. Questo modello crea automaticamente un ruolo IAM che consente alla funzione Lambda di funzionare con Amazon SES e Amazon SNS.

Di seguito viene illustrato come utilizzare la AWS Command Line Interface (AWS CLI) per creare uno CloudFormation stack.

1. <a name="install-cli"></a>Nel terminale del tuo dispositivo, `aws --version` esegui per verificare se hai installato il AWS CLI. Per ulteriori informazioni, consulta [Installing or updating to the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) nella *Guida per l'utente dell'AWS Command Line Interface *.

1. <a name="configure-cli"></a>Esegui `aws configure list` per verificare se lo hai configurato AWS CLI nella AWS regione che ha tutte le AWS risorse per questo tutorial. Per ulteriori informazioni, consulta [Impostare e visualizzare le impostazioni di configurazione utilizzando i comandi](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-methods) nella *Guida AWS Command Line Interface per l'utente*

1. Scarica il CloudFormation modello, [NotificationLambda.template.yaml.zip](samples/notificationLambda.template.yaml.zip).
**Nota**  
Se hai difficoltà a scaricare il file, il modello è disponibile anche in. [CloudFormation modello](alarms-create-lambda.md#cfn-template)

1. Decomprimere il contenuto e salvarlo localmente come `notificationLambda.template.yaml`.

1. Apri un terminale sul tuo dispositivo e vai alla directory in cui hai scaricato il `notificationLambda.template.yaml` file.

1. Per creare uno CloudFormation stack, esegui il seguente comando:

   ```
   aws cloudformation create-stack --stack-name notificationLambda-stack --template-body file://notificationLambda.template.yaml --capabilities CAPABILITY_IAM
   ```

È possibile modificare questo CloudFormation modello per personalizzare la funzione Lambda e il relativo comportamento.

**Nota**  
AWS Lambda riprova due volte gli errori di funzione. Se la funzione non dispone di capacità sufficiente per gestire tutte le richieste in entrata, gli eventi possono attendere in coda per ore o giorni per essere inviati alla funzione. È possibile configurare una coda di messaggi non recapitati (DLQ) sulla funzione per acquisire gli eventi che non sono stati elaborati correttamente. Per ulteriori informazioni, consulta [Chiamata asincrona](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html) nella *Guida per gli sviluppatori AWS Lambda *.

Puoi anche creare o configurare lo stack nella console. CloudFormation Per ulteriori informazioni, consulta [Working with stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacks.html), nella Guida per l'*AWS CloudFormation utente*.

# Creazione di una funzione Lambda personalizzata per AWS IoT Events
<a name="alarms-create-custom-lambda"></a>

È possibile creare una funzione Lambda o modificare quella fornita da. AWS IoT Events

I seguenti requisiti si applicano quando si crea una funzione Lambda personalizzata.
+ Aggiungi autorizzazioni che consentono alla funzione Lambda di eseguire azioni specifiche e AWS accedere alle risorse.
+ Se usi la funzione Lambda fornita da AWS IoT Events, assicurati di scegliere il runtime Python 3.7.

Esempio di funzione Lambda:

```
import boto3
import json
import logging
import datetime
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ses = boto3.client('ses')
sns = boto3.client('sns')
def check_value(target):
  if target:
    return True
  return False

# Check whether email is verified. Only verified emails are allowed to send emails to or from.
def check_email(email):
  if not check_value(email):
    return False
  result = ses.get_identity_verification_attributes(Identities=[email])
  attr = result['VerificationAttributes']
  if (email not in attr or attr[email]['VerificationStatus'] != 'Success'):
      logging.info('Verification email for {} sent. You must have all the emails verified before sending email.'.format(email))
      ses.verify_email_identity(EmailAddress=email)
      return False
  return True

# Check whether the phone holder has opted out of receiving SMS messages from your account
def check_phone_number(phone_number):
  try:
    result = sns.check_if_phone_number_is_opted_out(phoneNumber=phone_number)
    if (result['isOptedOut']):
        logger.info('phoneNumber {} is not opt in of receiving SMS messages. Phone number must be opt in first.'.format(phone_number))
        return False
    return True
  except Exception as e:
    logging.error('Your phone number {} must be in E.164 format in SSO. Exception thrown: {}'.format(phone_number, e))
    return False

def check_emails(emails):
  result = True
  for email in emails:
      if not check_email(email):
          result = False
  return result

def lambda_handler(event, context):
  logging.info('Received event: ' + json.dumps(event))
  nep = json.loads(event.get('notificationEventPayload'))
  alarm_state = nep['alarmState']
  default_msg = 'Alarm ' + alarm_state['stateName'] + '\n'
  timestamp = datetime.datetime.utcfromtimestamp(float(nep['stateUpdateTime'])/1000).strftime('%Y-%m-%d %H:%M:%S')
  alarm_msg = "{} {} {} at {} UTC ".format(nep['alarmModelName'], nep.get('keyValue', 'Singleton'), alarm_state['stateName'], timestamp)
  default_msg += 'Sev: ' + str(nep['severity']) + '\n'
  if (alarm_state['ruleEvaluation']):
    property = alarm_state['ruleEvaluation']['simpleRule']['inputProperty']
    default_msg += 'Current Value: ' + str(property) + '\n'
    operator = alarm_state['ruleEvaluation']['simpleRule']['operator']
    threshold = alarm_state['ruleEvaluation']['simpleRule']['threshold']
    alarm_msg += '({} {} {})'.format(str(property), operator, str(threshold))
  default_msg += alarm_msg + '\n'

  emails = event.get('emailConfigurations', [])
  logger.info('Start Sending Emails')
  for email in emails:
    from_adr = email.get('from')
    to_adrs = email.get('to', [])
    cc_adrs = email.get('cc', [])
    bcc_adrs = email.get('bcc', [])
    msg = default_msg + '\n' + email.get('additionalMessage', '')
    subject = email.get('subject', alarm_msg)
    fa_ver = check_email(from_adr)
    tas_ver = check_emails(to_adrs)
    ccas_ver = check_emails(cc_adrs)
    bccas_ver = check_emails(bcc_adrs)
    if (fa_ver and tas_ver and ccas_ver and bccas_ver):
      ses.send_email(Source=from_adr,
                     Destination={'ToAddresses': to_adrs, 'CcAddresses': cc_adrs, 'BccAddresses': bcc_adrs},
                     Message={'Subject': {'Data': subject}, 'Body': {'Text': {'Data': msg}}})
      logger.info('Emails have been sent')

  logger.info('Start Sending SNS message to SMS')
  sns_configs = event.get('smsConfigurations', [])
  for sns_config in sns_configs:
    sns_msg = default_msg + '\n' + sns_config.get('additionalMessage', '')
    phone_numbers = sns_config.get('phoneNumbers', [])
    sender_id = sns_config.get('senderId')
    for phone_number in phone_numbers:
        if check_phone_number(phone_number):
          if check_value(sender_id):
            sns.publish(PhoneNumber=phone_number, Message=sns_msg, MessageAttributes={'AWS.SNS.SMS.SenderID':{'DataType': 'String','StringValue': sender_id}})
          else:
            sns.publish(PhoneNumber=phone_number, Message=sns_msg)
          logger.info('SNS messages have been sent')
```

Per ulteriori informazioni, consulta [Cos'è AWS Lambda?](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) nella *Guida per gli sviluppatori AWS Lambda *.

## CloudFormation modello
<a name="cfn-template"></a>

Usa il seguente CloudFormation modello per creare la tua funzione Lambda.

```
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Notification Lambda for Alarm Model'
Resources:
  NotificationLambdaRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      Path: "/"
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/AWSLambdaExecute'
      Policies:
        - PolicyName: "NotificationLambda"
          PolicyDocument:
            Version: "2012-10-17"		 	 	 
            Statement:
              - Effect: "Allow"
                Action:
                  - "ses:GetIdentityVerificationAttributes"
                  - "ses:SendEmail"
                  - "ses:VerifyEmailIdentity"
                Resource: "*"
              - Effect: "Allow"
                Action:
                  - "sns:Publish"
                  - "sns:OptInPhoneNumber"
                  - "sns:CheckIfPhoneNumberIsOptedOut"
                  - "sms-voice:DescribeOptedOutNumbers"
                Resource: "*"
              - Effect: "Deny"
                Action:
                  - "sns:Publish"
                Resource: "arn:aws:sns:*:*:*"
  NotificationLambdaFunction:              
    Type: AWS::Lambda::Function
    Properties:
      Role: !GetAtt NotificationLambdaRole.Arn
      Runtime: python3.7
      Handler: index.lambda_handler
      Timeout: 300
      MemorySize: 3008
      Code:
        ZipFile: |
          import boto3
          import json
          import logging
          import datetime
          logger = logging.getLogger()
          logger.setLevel(logging.INFO)
          ses = boto3.client('ses')
          sns = boto3.client('sns')
          def check_value(target):
            if target:
              return True
            return False

          # Check whether email is verified. Only verified emails are allowed to send emails to or from.
          def check_email(email):
            if not check_value(email):
              return False
            result = ses.get_identity_verification_attributes(Identities=[email])
            attr = result['VerificationAttributes']
            if (email not in attr or attr[email]['VerificationStatus'] != 'Success'):
                logging.info('Verification email for {} sent. You must have all the emails verified before sending email.'.format(email))
                ses.verify_email_identity(EmailAddress=email)
                return False
            return True

          # Check whether the phone holder has opted out of receiving SMS messages from your account
          def check_phone_number(phone_number):
            try:
              result = sns.check_if_phone_number_is_opted_out(phoneNumber=phone_number)
              if (result['isOptedOut']):
                  logger.info('phoneNumber {} is not opt in of receiving SMS messages. Phone number must be opt in first.'.format(phone_number))
                  return False
              return True
            except Exception as e:
              logging.error('Your phone number {} must be in E.164 format in SSO. Exception thrown: {}'.format(phone_number, e))
              return False

          def check_emails(emails):
            result = True
            for email in emails:
                if not check_email(email):
                    result = False
            return result

          def lambda_handler(event, context):
            logging.info('Received event: ' + json.dumps(event))
            nep = json.loads(event.get('notificationEventPayload'))
            alarm_state = nep['alarmState']
            default_msg = 'Alarm ' + alarm_state['stateName'] + '\n'
            timestamp = datetime.datetime.utcfromtimestamp(float(nep['stateUpdateTime'])/1000).strftime('%Y-%m-%d %H:%M:%S')
            alarm_msg = "{} {} {} at {} UTC ".format(nep['alarmModelName'], nep.get('keyValue', 'Singleton'), alarm_state['stateName'], timestamp)
            default_msg += 'Sev: ' + str(nep['severity']) + '\n'
            if (alarm_state['ruleEvaluation']):
              property = alarm_state['ruleEvaluation']['simpleRule']['inputProperty']
              default_msg += 'Current Value: ' + str(property) + '\n'
              operator = alarm_state['ruleEvaluation']['simpleRule']['operator']
              threshold = alarm_state['ruleEvaluation']['simpleRule']['threshold']
              alarm_msg += '({} {} {})'.format(str(property), operator, str(threshold))
            default_msg += alarm_msg + '\n'

            emails = event.get('emailConfigurations', [])
            logger.info('Start Sending Emails')
            for email in emails:
              from_adr = email.get('from')
              to_adrs = email.get('to', [])
              cc_adrs = email.get('cc', [])
              bcc_adrs = email.get('bcc', [])
              msg = default_msg + '\n' + email.get('additionalMessage', '')
              subject = email.get('subject', alarm_msg)
              fa_ver = check_email(from_adr)
              tas_ver = check_emails(to_adrs)
              ccas_ver = check_emails(cc_adrs)
              bccas_ver = check_emails(bcc_adrs)
              if (fa_ver and tas_ver and ccas_ver and bccas_ver):
                ses.send_email(Source=from_adr,
                               Destination={'ToAddresses': to_adrs, 'CcAddresses': cc_adrs, 'BccAddresses': bcc_adrs},
                               Message={'Subject': {'Data': subject}, 'Body': {'Text': {'Data': msg}}})
                logger.info('Emails have been sent')

            logger.info('Start Sending SNS message to SMS')
            sns_configs = event.get('smsConfigurations', [])
            for sns_config in sns_configs:
              sns_msg = default_msg + '\n' + sns_config.get('additionalMessage', '')
              phone_numbers = sns_config.get('phoneNumbers', [])
              sender_id = sns_config.get('senderId')
              for phone_number in phone_numbers:
                  if check_phone_number(phone_number):
                    if check_value(sender_id):
                      sns.publish(PhoneNumber=phone_number, Message=sns_msg, MessageAttributes={'AWS.SNS.SMS.SenderID':{'DataType': 'String','StringValue': sender_id}})
                    else:
                      sns.publish(PhoneNumber=phone_number, Message=sns_msg)
                    logger.info('SNS messages have been sent')
```