How to receive AWS CloudWatch alerts on your mobile phone with Amazon Connect?

By Manikandan DUpdated as on March 24, 2023 11 minutes read 159 Views

AWS

Overview

Amazon Connect is a self-service, cloud-based contact center service that makes it easy for businesses to deliver better customer service at a lower cost. The self-service graphical interface in Amazon Connect makes it easy for non-technical users to design contact flows, manage agents, and track performance metrics — no specialized skills required.

There are various ways to get a CloudWatch alert using email or SMS. The following steps outline how to get a voice alert on your phone using Amazon Connect:

1.The CloudWatch alarm is that generates an event. An Amazon CloudWatch event rule triggers an AWS Lambda function, which uses the Amazon Connect API to initiate an outbound call to the concerned party

AWS

Walkthrough

To implement this solution, you must create the following resources:

  1. A contact flow.
  2. An AWS Lambda function.
  3. An Amazon CloudWatch event rule.

Prerequisites

To follow this walkthrough, you must create at least one Amazon Connect virtual contact center instance with a claimed phone number. For details, see Amazon Connect — Customer Contact Center in the Cloud.

Amazon Connect instance Launch:

  1. Open the Amazon Connect console at https://console.aws.amazon.com/connect/.
  2. Choose Get started. If you have previously created an instance, choose Add an instance instead.
  3. Choose one of the following options:
    • Store users within Amazon Connect — Use Amazon Connect to create and manage user accounts.
    • Link to an existing directory — Use an AWS Directory Service directory to manage your users. You can use each directory with one Amazon Connect instance at a time.
    • SAML 2.0-based authentication — Use an existing identity provider (IdP) to federate users with Amazon Connect.
  4. If you chose Store users within Amazon Connect provide the left-most label for Access URL. This label must be unique across all Amazon Connect instances in all Regions. You can’t change the access URL after you create your instance.
  5. If you chose Link to an existing directory, select the AWS Directory Service directory for Directory. The directory name is used as the left-most label for Access URL.
  6. Choose Next step.

Administrator

After you specify the user name of the administrator for the Amazon Connect instance, a user account is created in Amazon Connect and the user is assigned the Admin security profile.

To specify the administrator for your instance

  1. Do one of the following, based on the option that you chose in the previous step:
    • If you chose Store users within Amazon Connect, select Add a new admin, and provide a name, password, and email address for the user account in Amazon Connect.
  2. Choose Next step.

Telephony options

Use the options in this section to choose whether you want your agents to receive calls from customers, make outbound calls, and hear early media audio.

Early media

When early media audio is enabled, for outbound calls your agents can hear pre-connection audio such as busy signals, failure-to-connect errors, or other informational messages provided by telephony providers.

By default, early media is enabled for you. Note the following exception:

Your instance was created before April 17, 2020, and you weren’t enrolled in the preview program. You need to enable early media audio using the option described in this procedure.

To configure telephony options for your instance

  1. (Optional) To enable customers to call into your contact center, choose I want to handle incoming calls with Amazon Connect.
  2. (Optional) To enable outbound calling from your contact center, choose I want to make outbound calls with Amazon Connect.
  3. (Optional) To enable agents to hear pre-connection audio such as busy signals or “This phone number has been disconnected and is no longer in service,” choose I want to enable early media.
  4. Choose Next step.

Data storage

When you create an instance, by default we create an Amazon S3 bucket. Data, such as reports and recordings of conversations, is encrypted using AWS Key Management Service, and then stored in the Amazon S3 bucket.

This bucket and key are used for both recordings of conversations and exported reports. Alternatively, you can specify separate buckets and keys for recordings of conversations and exported reports.

By default, Amazon Connect creates buckets for storing call recordings, chat transcripts, exported reports, and contact flow logs.

When a bucket is created to store call recordings, call recording is enabled at the instance level. The next step for setting up this functionality is to set up recording behavior in a contact flow.

When a bucket is created to store chat transcripts, chat transcription is enabled at the instance level. Now all chat transcripts will be stored. Only if you want to monitor chat conversations do you need to set up recording behavior in a contact flow

Live media streaming is not enabled by default.

To customize the data storage settings for your instance or enable/disable certain functionality:

  1. Choose Customize settings.
  2. (Optional) To specify the bucket and KMS key for recordings of voice conversations, choose Call recordings, Edit, specify the bucket name and prefix, select the KMS key by name, and then choose Save.
  3. (Optional) To specify the bucket and KMS key for recordings (transcripts) of chat conversations, choose Chat transcripts, Edit, specify the bucket name and prefix, select the KMS key by name, and then choose Save.
  4. (Optional) To specify the bucket and KMS key for exported reports, choose Exported reports, Edit, specify the bucket name and prefix, select the KMS key by name, and then choose Save.
  5. (Optional) To disable contact flow logs, clear Enable Contact flow logs.
  6. (Optional) To enable file sharing for both agents and customers, next to Attachments choose Edit, then Enable Attachments sharing. For more information about this option and additional steps, see Enable attachments to share files using chat
  7. Choose Next step.

Review and create

When you are finished configuring your instance, you can create it.

To create your instance

  1. Review the configuration choices. Remember that you cannot change the identity management options after you create the instance.
  2. (Optional) To change any of the configuration options, choose Change.
  3. Choose Create instance.
  4. (Optional) To continue configuring your instance, choose Get started and then choose Let’s go. If you prefer, you can access your instance and configure it later on.

Step 1: Create a contact flow

Create a contact flow IVR to enable the outbound call and play the alert message based on the event.

  1. In the Amazon Connect console, choose Overview. As the administrator, choose Login.
  2. On the Routing menu, choose Contact Flows, Create Contact flow.
  3. On the left pane, enter a name for the contact flow, for example, “SampleAlert.”
  4. On the left pane, for Interact, drag and drop the Play prompt IVR block to the grid on the right.
  5. On the left pane, for Interact, drag and drop the Get customer input IVR block to the grid on the right.
  6. On the left pane, for Terminate/Transfer, drag and drop the Disconnect / hang up IVR block to the grid on the right.
  7. Connect these three IVR blocks to make a contact flow, as shown in the following screenshot.
AWS
  1. Double-click the Play prompt IVR block. On the Play prompt page, configure the following fields:
    • Choose Text to speech (Ad hoc).
    • Choose Enter text, and enter the following:
<speak>
<prosody rate=”slow”>
$.Attributes.Message
</prosody>
</speak>

c. For Interpret as, choose SSML.

d. Choose Save.

2. Choose Save & Publish.

3. On the left pane, for Show additional flow information, note the contact flow ID for the contact flow you just published for future use. The Lambda function only needs the last 36-digit number, as underlined in the following screenshot.

AWS

Step 2: Create a Lambda function

Before you create the Lambda function to trigger the contact flow, create an IAM role for it to use. For more information, see the Creating an IAM Role section in the IAM Roles for Amazon EC2 topic.

To create an IAM role

  1. In the IAM console, choose PoliciesCreate Policy.
  2. On the JSON tab, copy the following IAM policy, and choose Review policy.
{
“Version”: “2012–10–17”,
“Statement”: [
{
“Sid”: “VisualEditor0”,
“Effect”: “Allow”,
“Action”: [
“logs:CreateLogStream”,
“logs:PutLogEvents”
],
“Resource”: “arn:aws:logs:*:*:*”
},
{
“Sid”: “VisualEditor1”,
“Effect”: “Allow”,
“Action”: [
“iam:ListAccountAliases”
],
“Resource”: “*”
},
{
“Sid”: “VisualEditor2”,
“Effect”: “Allow”,
“Action”: [
“connect:ListInstances”,
“connect:StartOutboundVoiceContact”
],
“Resource”: “*”
},
{
“Sid”: “VisualEditor3”,
“Effect”: “Allow”,
“Action”: “logs:CreateLogGroup”,
“Resource”: “arn:aws:logs:*:*:*”
}
]
}

To create a Lambda function.

For more information, see Create a Lambda Function with the Console

  1. In the Lambda console, choose Author from scratch.
  2. For Runtime, choose Python 2.7.
  3. For Execution role, select Use an existing role, then select the IAM role created in the previous step.
  4. Choose Create Function, remove the default function, and copy the following code into the Function Code window:
import json
import boto3
import logging
import os
import time
import botocore.session
from botocore.exceptions import ClientError
session = botocore.session.get_session()
logging.basicConfig(level=logging.DEBUG)
logger=logging.getLogger(__name__)
def lambda_handler(event, context):
logger.setLevel(logging.DEBUG)
eventname = event[‘detail’][‘state’][‘value’]
DestPhoneNumber = os.environ[‘DestPhoneNumber’] #Getting the destination phone number passed in by the environment variables.
D_phone = DestPhoneNumber.split(“,”,)
ContactFlowId = os.environ[‘ContactFlowId’] #Getting the Amazon Connect ContactFlowID passed in by the environment variables.
InstanceId = os.environ[‘InstanceId’] #Getting the Amazon Connect InstanceId passed in by the environment variables.
SourcePhoneNumber = os.environ[‘SourcePhoneNumber’]
AlarmName = event[‘detail’][‘alarmName’]
logger.debug(“Event is — — %s” %event)
logger.debug(“Event Name is — — %s” %eventname)
logger.debug(“DestPhoneNumber is — %s” %DestPhoneNumber)
logger.debug(“Alarm Name is — %s” %AlarmName)
client = boto3.client(‘iam’)
connectclient = boto3.client(‘connect’)
response = client.list_account_aliases()
logger.debug(“List account alias response — — %s” %response)
try:
if not response[‘AccountAliases’]:
accntAliase = (boto3.client(‘sts’).get_caller_identity()[‘Account’])
logger.info(“Account alias is not defined. Account ID is %s” %accntAliase)
else:
accntAliase = response[‘AccountAliases’][0]
logger.info(“Account alias is : %s” %accntAliase)
except ClientError as e:
logger.error(“Client error occurred”)
for i in D_phone:
try:
#Making the outbound phone alert…
OutboundResponse = connectclient.start_outbound_voice_contact(
DestinationPhoneNumber=i,
ContactFlowId=ContactFlowId,
InstanceId=InstanceId,
SourcePhoneNumber=SourcePhoneNumber,
Attributes={‘Message’: ‘This is a critical alert message! Resource utilization state-%s detected in-%s’ %(eventname,AlarmName)
}
)
logger.debug(“outbound Call response is — %s” %OutboundResponse)
time.sleep(3)
except ClientError as e:
logger.error(“An error occurred: %s” %e)

5. In the Environment variables section, enter the following key-value pairs:

  1. Key= ContactFlowId
    Value= Enter the value of the contact flow from an earlier step.
  2. Key= DestPhoneNumber
    Value= Enter the phone number where you want to receive the alert call (prepend the number with “+country code”).
  3. Key= InstanceId
    Value= Enter the ID of your Amazon Connect instance. To find the Amazon Connect instance ID, see How do I find my Amazon Connect instance ID.
  4. Key= SourcePhoneNumber
    Value= Enter the phone number assigned to your Amazon Connect instance. The format should be “+country code” followed by the number. For example, for a US number, use +14567891234.
  5. Choose Save.

In the next step, you add a trigger to this Lambda function.

Step 3: Create a CloudWatch Events rule

This rule catches a console login event and all other API events performed by a root user, and triggers the Lambda function (set as a target) when these events are detected.

  1. In the CloudWatch console, choose Rules, Create rule.
  2. On the Step 1: Create rule page:
  3. Under Event Source, select Event Pattern, and copy the following event into the preview pane (note placement in the screenshot after the following code):
{
“source”: [
“aws.cloudwatch”
],
“detail-type”: [
“CloudWatch Alarm State Change”
],
“detail”: {
“alarmName”: [
“dev-cpu-utilization”
],
“state”: {
“value”: [
“ALARM”
]
}
}
}

c. For Targets, select Lambda function, and select the Lambda function created in Step 2.

  1. Choose Configure details.
  2. On the Step 2: Configure rule details page, add a name and description for the rule.
  3. For State, select Enabled, and choose Create rule.

To add a trigger to the Lambda function created earlier:

  1. In the Lambda console, select the Lambda function that you created in Step 2, and open the designer section on the left panel.
  2. Under Add triggers, choose CloudWatch Events, and select the CloudWatch event rule created earlier.
  3. Select Enable trigger and choose Add.
  4. On the top-right corner, choose Save. You should see the following screenshot.
AWS

Solution validation

I demonstrate that after deploying the solution, I received a phone call alert for resource utilization.