Create an Omnichannel Chatbot using Amazon Lex and Amazon Connect

Background

These days, chatbots are used pretty much everywhere. From getting quotes to resetting password, their use cases are endless. They also elevate the customer experience, as now customers don’t need to call during your helpdesk’s manned hours, instead they can call anytime that is convenient to them. One of the biggest business benefits is that of lessening the load on their support staff.

A good practice to adhere by, when deploying chatbots is to make them channel agnostic. This means that your chatbots are available via the internet and also via a phone call, and they provide the same customer experience. This enables your customers to choose whichever channel suits them best, without any loss of customer experience.

In this blog, I will demonstrate how you can use Amazon Connect and Amazon Lex, to create an omnichannel chatbot.

I will be extending one of my previous blogs, so if you haven’t read it already, I would highly recommend that you do so, prior to continuing. Here is the link to the blog https://nivleshc.wordpress.com/2020/04/08/create-a-web-chatbot-for-generating-life-insurance-quotes-using-amazon-lex/).

High Level Architecture Diagram

Below is the high-level architecture diagram for the solution. We will build the section inside the blue box.

For steps 1 – 5 please refer to https://nivleshc.wordpress.com/2020/04/08/create-a-web-chatbot-for-generating-life-insurance-quotes-using-amazon-lex/

For steps 6 – 8 please refer to https://nivleshc.wordpress.com/2020/05/24/publish-a-web-chatbot-frontend-using-aws-amplify-console/

Steps 9 – 12 will be created in this blog and are described below:

9. The customer calls the phone number for the chatbot. This is attached to a contact flow in Amazon Connect

10. Amazon Connect proxies the customer to the Amazon Lex chatbot (this is the web chatbot created in https://nivleshc.wordpress.com/2020/04/08/create-a-web-chatbot-for-generating-life-insurance-quotes-using-amazon-lex/ )

11. The output from the Amazon Lex chatbot is sent back to Amazon Connect.

12. Amazon Connect converts the output from the Amazon Lex chatbot into audio and then plays it to the customer.

Prerequisites

This blog assumes the following:

  • you already have an Amazon Connect instance deployed and configured.
  • you have a working Amazon Lex web chatbot

You can refer to the following blogs, if you need to deploy either of the above prerequisites

https://nivleshc.wordpress.com/2020/04/08/create-a-web-chatbot-for-generating-life-insurance-quotes-using-amazon-lex/

https://nivleshc.wordpress.com/2020/05/24/publish-a-web-chatbot-frontend-using-aws-amplify-console/

Implementation

Let’s get started.

  1. Login to your AWS Management Console, open the Amazon Connect console and change to the respective AWS region.
  2. Within the Amazon Connect console, choose the instance that will be used and click its Instance Alias.
  3. In the next screen, from the left-hand side menu, click Contact flows. Then, in the right-hand side screen, under Amazon Lex select the Region where the Amazon Lex bot resides. From the Bot drop-down list, select the name of the Amazon Lex bot. Once done, click +Add Lex Bot.
  4. Click Overview from the left-hand side menu, and then click Login URL to open the Amazon Connect administration portal. Enter your administrator credentials (currently only the following internet browsers are supported – latest three versions of Google Chrome, Mozilla Firefox ESR, Mozilla Firefox).
  5. Once logged in, from the left hand-side menu, click Routing and then Contact flows.
  6. Click Create contact flow (located on the top-right). You will now see the contact flow designer.
  7. Enter a name for the contact flow (top left where it says Enter a name)
  8. From the left-hand side menu, expand Interact and drag Get customer input to the right-hand side screen.
  9. Click on the circle to the right of Start in the Entry point block and drag the arrow to the Get customer input block. This will connect the two blocks.
  10. Click on the title of the Get customer input block to open its configuration.
  11. Select Text-to-speech or chat text. Click Enter text and in the textbox underneath, type the message you want to play to the customer when they call the chatbot.
  12. Click Amazon Lex and then under Lex bot Name select the Amazon Lex bot that you had created earlier (if the bot doesn’t show, ensure you had carried out step 3 above). Under Intents type the Amazon Lex bot intent that should be invoked. Click Save.

13. From the left-hand side menu, expand Interact and drag two Play prompt blocks to the right-hand side screen.

14. The first Play prompt block will be used to play a goodbye message, after the Amazon Lex bot has finished execution. Click on the title of this block to open its configuration. Click Text-to-speech or chat text and then click Enter text. Enter a message to be played before the call is ended. Click Save.

  15. The second Play prompt block will be used to play a message when an error occurs. Click on the title of this block to open its configuration. Click Text-to-speech or chat text and then click Enter text. Enter a message to be played when an error occurs. Click Save.

16. From the left-hand side menu, expand Terminate / Transfer and drag the Disconnect / hang up block to the right-hand side screen.

17. In the designer (right-hand side screen), in the Get customer input block, click the circle beside startConversation (this is the name of your Amazon Lex bot intent) and drag the arrow to the first Play prompt block.

18. Repeat step 17 for the circle beside Default in the Get customer input block.

19. In the Get customer input block, click the circle beside Error and drag it to the second Play prompt block.

20. Inside both the Play prompt blocks, click the circle beside Okay and drag the arrow to the Disconnect / hang up block.

21. From the top-right, click Save. This will save the work you have done.

22. From the top-right, click Publish. You will get a prompt Are you sure you want to publish this content flow? Click Publish.

23. Once done, you should see a screen similar to the one below:

24. Next, we need to ensure that whenever someone calls, the newly created contact flow is invoked. To do this, from the left-hand side menu, click Routing and then click Phone numbers.

25. In the right-hand side, click the phone number that will be used for the chatbot. This will open its settings. Enter a description (optional) and then from the drop-down list underneath Contact flow / IVR, choose the contact flow that was created above. Click Save.

Give it a few minutes for the settings to take effect. Now, call the phone number that was assigned to the contact flow above. You should be greeted by the welcome message you had created above. The phone chatbot experience would be the same as what you experienced when interacting with the chatbot over the internet!

Congratulations! You just created your first omnichannel chatbot! How easy was that?

Till the next time, Enjoy!

Publish A Web Chatbot Frontend Using AWS Amplify Console

Background

In my previous blog (https://nivleshc.wordpress.com/2020/04/08/create-a-web-chatbot-for-generating-life-insurance-quotes-using-amazon-lex/), I demonstrated how easy it was to create a web chatbot using Amazon Lex. As discussed in that blog, one of the challenges with Amazon Lex is not having an out-of-the-box frontend solution for the bots. This can throw a spanner in the works, if you are planning on showcasing your chatbots to customers, without wanting to overwhelm them with the code. Luckily, with some work, you can create a front-end that exposes just the bot. I provided instructions for achieving this in the same blog.

Having a static website hosted out of an Amazon S3 bucket is good, however it does come with a few challenges. As the website gains popularity, it becomes more integral to your business. Soon, you will not be able to afford any website outages. In such situations, how do you deploy changes to the website without breaking it? How do you track the changes, to ensure they can be rolled back, if something does break? How do you ensure your end-users don’t suffer from slow webpage loads? These are some of the questions that need to be answered, as your website achieves popularity.

AWS Amplify Console provides an out-of-the-box solution for deploying static websites. The contents of the website can be hosted in a source code repository. This provides an easy solution to track changes, and to rollback, should the need arise. AWS Amplify Console serves the website using Amazon CloudFront, AWS’s Content Delivery Network. This ensures speedy page loads for end-users. These are just some of the features that make hosting a static website using AWS Amplify Console a great choice.

In this blog, I will modify my life Insurance quote web chatbot solution, by migrating its frontend from an Amazon S3 bucket to AWS Amplify Console.

High Level Architecture Diagram

Below is a high-level architecture diagram for the solution described in this blog.

Steps 1 – 5 are from my previous blog https://nivleshc.wordpress.com/2020/04/08/create-a-web-chatbot-for-generating-life-insurance-quotes-using-amazon-lex

Steps 6 – 8 will be created in this blog and are described below:

6. Website developer will push changes for the Amazon Lex web chatbot frontend to GitHub.

7. GitHub will inform AWS Amplify about the new changes.

8. AWS Amplify will retrieve the changes from GitHub, build the new web chatbot frontend and deploy it, thereby updating the previous web chatbot        frontend.

Implementation

Before we continue, if you haven’t already, I would highly recommend that you read my Amazon Lex Life Insurance quote generating web chatbot blog ( https://nivleshc.wordpress.com/2020/04/08/create-a-web-chatbot-for-generating-life-insurance-quotes-using-amazon-lex)

Let’s get started.

  1. Login to your AWS Management Console, open the AWS Amplify Console and change to your AWS Region of choice.
  2. Click on Connect app.
  3. Next, choose the location where the source code is hosted. As I have stored the web chatbot frontend files in GitHub, I chose GitHub. Note that the repository should contain only the frontend files. Click Continue.
  4. Unless you had previously authorised AWS Amplify Console access to your source code repository, a screen will pop-up requesting access to your source code repository. Click Authorize aws-amplify-console.
  5. Once successfully authorised, you will be returned to the AWS Amplify Console. Using the dropdown menu beside Select a repository select the repository that contains the frontend code.
  6. Next, choose the Branch to use and then click Next.
  7. The next screen shows the Configure build settings page. AWS Amplify Console will inspect the source code and deduce the appropriate App build and test settings. If what is shown is incorrect, or you would like to modify it, you can use the Edit button.

    In my case, I did not find anything needed changing from what AWS Amplify Console had provided.

    You can change the App name, if this needs to be different from what is automatically provided.

    Click Next.

  8. In the next screen, review all the settings. Once confirmed, click Save and deploy.
  9. AWS Amplify Console will start creating the application. You will be redirected to the application’s configuration page, where on the right, a continuous deployment pipeline, similar to the one below, will be shown.

  10. Wait for all stages of the pipeline to complete successfully and then click on the url on the left (the one similar to https://master…amplifyapp.com). The page that opens next is the Insurance Chatbot Frontend, served by AWS Amplify Console! (below is how the web chatbot looks like)

  11. Now, whenever the frontend files are modified and pushed into the master branch of the source code repository (GitHub in this case), AWS Amplify Console will automatically update the Insurance Chatbot frontend, with all changes easily trackable from within GitHub.
  12. You can use a custom domain name, to make the application URL more personalised (by default, AWS Amplify Console applications are allocated the amplifyapp.com domain urls). To do this, from your application’s configuration page, click Domain management in the left-hand side menu. Then click add domain and follow the instructions.
  13. You might also benefit from email notifications whenever AWS Amplify Console updates your application. To configure this, from your application’s configuration page, click Notifications in the left-hand side menu. Then click Add notification and add an email address to receive notifications for successful and failed builds.
  14. To view site access logs, from your applications configuration page, click Access logs in the left-hand side menu.

There you go. Hopefully this provides valuable information for those looking for an easy solution to deploy their static websites in a consistent, auditable and highly available manner.

Till the next time, Enjoy!

Automate Training, Build And Deployment Of Amazon SageMaker Models Using AWS Step Functions

Background

A few weeks back, I was tasked with automating the training, build and deployment of an Amazon SageMaker model. Initially, I thought that an AWS Lambda Function would be the best candidate for this, however as I started experimenting, I quickly realised that I needed to look elsewhere.

After some research, I found articles that pointed me towards AWS Step Functions. As it happens, AWS has been making AWS Step Functions more Amazon SageMaker friendly, to the point that AWS Step Functions now natively supported most of the Amazon SageMaker APIs.

With the technology decided, I started figuring out how I would achieve what I had set out to do. I did find some good documentation and examples, however they didn’t entirely cover everything I was after.

After much research and experimentation, I finally created a solution that was able to automatically train, build and then deploy an Amazon SageMaker model.

In this blog, I will outline the steps I followed, with the hope that it benefits those wanting to do the same, saving them countless hours of frustration and experimentation.

High Level Architecture Diagram

Below is a high-level architecture diagram of the solution I used.

The steps (as denoted by the numbers in the diagram) are as follows:

  1. The first AWS Step Function state calls the Amazon SageMaker API to create a Training Job, passing it all the necessary parameters.
  2. Using the supplied parameters, Amazon SageMaker downloads the training and validation files from the Amazon S3 bucket, and then runs the training algorithm. The output is uploaded to the same Amazon S3 bucket that contained that training and validation files.
  3. The next AWS Step Function state calls the Amazon SageMaker API to create a model,  using the artifacts from the Training Job.
  4. The next AWS Step Function state calls the Amazon SageMaker API to create an endpoint configuration, using the model that was created in the previous state.
  5. The next AWS Step Function state calls the Amazon SageMaker API to create a model endpoint, using the endpoint configuration that was created in the previous state.
  6. Using the endpoint configuration, Amazon SageMaker deploys the model using Amazon SageMaker Hosting Services, making it available to any client wanting to use it.

Let’s get started.

Implementation

For this blog, I will be using the data and training parameters described in the Amazon SageMaker tutorial at https://docs.aws.amazon.com/sagemaker/latest/dg/gs-console.html

1. Create an Amazon S3 bucket. Create a folder called data inside your Amazon S3 bucket, within which, create three subfolders called train, validation and test (technically these are not folders and subfolders, but keys. However, to keep things simple, I will refer to them as folders and subfolders).

2. Follow Step 4 from the above-mentioned Amazon SageMaker tutorial (https://docs.aws.amazon.com/sagemaker/latest/dg/ex1-preprocess-data.html) to download and transform the training, validation and test data. Then upload the data to the respective subfolders in your Amazon S3 bucket (we won’t be using the test data in this blog, however you can use it to test the deployed model).

For the next three months, you can download the transformed training, validation and test data from my Amazon S3 bucket using the following URLs

https://niv-sagemaker.s3-ap-southeast-2.amazonaws.com/data/train/examples

https://niv-sagemaker.s3-ap-southeast-2.amazonaws.com/data/validation/examples

https://niv-sagemaker.s3-ap-southeast-2.amazonaws.com/data/test/examples

3. Create an AWS IAM role with the following permissions
AmazonSageMakerFullAccess (AWS Managed Policy)

and a custom policy to read, write and delete objects from the Amazon S3 bucket created in Step 1. The policy will look similar to the one below

{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:ListBucket"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::bucketName"
]
},
{
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::bucketName/*"
]
}
]
}

where bucketName is the name of the Amazon S3 bucket created in Step 1 above.

4. Open the AWS Step Functions console and change to the AWS Region where the Amazon SageMaker model endpoint will be deployed.

5. Create a new state machine, choose Author with code snippets and set the type to Standard.

6. Under Definition delete everything and paste the following
{
"Comment": "An AWS Step Function State Machine to train, build and deploy an Amazon SageMaker model endpoint",
"StartAt": "Create Training Job",

The above commands provide a comment describing the purpose of this AWS Step Function state machine and sets the first state name as Create Training Job.

For a full list of Amazon SageMaker APIs supported by AWS Step Functions, please refer to https://docs.aws.amazon.com/step-functions/latest/dg/connect-sagemaker.html

7. Use the following code to create the first state (these are the training parameters described in the above-mentioned Amazon SageMaker tutorial).

"States": {
"Create Training Job": {
"Type": "Task",
"Resource": "arn:aws:states:::sagemaker:createTrainingJob.sync",
"Parameters": {
"TrainingJobName.$": "$$.Execution.Name",
"ResourceConfig": {
"InstanceCount": 1,
"InstanceType": "ml.m4.xlarge",
"VolumeSizeInGB": 5
},
"HyperParameters": {
"max_depth": "5",
"eta": "0.2",
"gamma": "4",
"min_child_weight": "6",
"silent": "0",
"objective": "multi:softmax",
"num_class": "10",
"num_round": "10"
},
"AlgorithmSpecification": {
"TrainingImage": "544295431143.dkr.ecr.ap-southeast-2.amazonaws.com/xgboost:1",
"TrainingInputMode": "File"
},
"OutputDataConfig": {
"S3OutputPath": "s3://bucketName/data/modelartifacts"
},
"StoppingCondition": {
"MaxRuntimeInSeconds": 86400
},
"RoleArn": "iam-role-arn",
"InputDataConfig": [
{
"ChannelName": "train",
"ContentType": "text/csv",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": "s3://bucketName/data/train",
"S3DataDistributionType": "FullyReplicated"
}
}
},
{
"ChannelName": "validation",
"ContentType": "text/csv",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": "s3://bucketName/data/validation",
"S3DataDistributionType": "FullyReplicated"
}
}
}
]
},
"Retry": [
{
"ErrorEquals": [
"SageMaker.AmazonSageMakerException"
],
"IntervalSeconds": 1,
"MaxAttempts": 1,
"BackoffRate": 1.1
},
{
"ErrorEquals": [
"SageMaker.ResourceLimitExceededException"
],
"IntervalSeconds": 60,
"MaxAttempts": 1,
"BackoffRate": 1
},
{
"ErrorEquals": [
"States.Timeout"
],
"IntervalSeconds": 1,
"MaxAttempts": 1,
"BackoffRate": 1
}
],
"Catch": [
{
"ErrorEquals": [
"States.ALL"
],
"ResultPath": "$.cause",
"Next": "Display Error"
}
],
"Next": "Create Model"
},

I would like to call out a few things from the above code

“Resource”: “arn:aws:states:::sagemaker:createTrainingJob.sync” refers to the Amazon SageMaker API for creating a Training Job. When this state task runs, you will be able to see this Training Job in the Amazon SageMaker console.

TrainingJobName is the name given to the Training Job and it must be unique within the AWS Region, in the AWS account. In my code, I am setting this to the Execution Name (internally referred to as $$.Execution.Name), which is an optional parameter that can be supplied when executing the AWS Step Function state machine. By default, this is set to a unique random string, however to make the Training Job name more recognisable, provide a more meaningful unique value when executing the state machine. I tend to use the current time in the format <training-algorithm>-<year><month><date>-<hour><minute><second>

If you have ever used Jupyter notebooks to run an Amazon SageMaker Training Job, you would have have used a line similar to the following:

        container = get_image_uri(boto3.Session().region_name, ‘xgboost’)

Yes, your guess is correct! Amazon SageMaker uses containers for running Training Jobs. The above assigns the xgboost training algorithm container from the region that the Jupyter notebook is running in.

These containers are hosted in Amazon Elastic Container Registry (Amazon ECR) and maintained by AWS. For each training algorithm that Amazon SageMaker supports, there is a specific container. Details for these containers can be found at https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-algo-docker-registry-paths.html.

When submitting a Training Job using AWS Step Functions, you must supply the correct container name, from the correct region (the region where you will be running Amazon SageMaker from). This information is passed using the parameter TrainingImage. To find the correct container path, use https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-algo-docker-registry-paths.html.

Another method for getting the value for TrainingImage is to manually submit a Training Job using the Amazon SageMaker console, using the same training algorithm that you will be using in the AWS Step Function state machine. Once the job has started, open it and have a look under the section Algorithm. You will find the Training Image for that particular training algorithm, for that region, listed there. You can use this value for TrainingImage.

S3OutputPath is the location where Amazon SageMaker will store the model artifacts after the Training Job has successfully finished.

RoleArn is the ARN of the AWS IAM Role that was created in Step 3 above

S3Uri under ChannelName: train is the Amazon S3 bucket path to the folder where the training data is located

S3Uri under ChannelName:validation is the Amazon S3 bucket path to the folder where the validation data is located

DON’T FORGET TO CHANGE bucketName TO THE AMAZON S3 BUCKET THAT WAS CREATED IN STEP 1 ABOVE

In the next AWS Step Function state, the model will be created using the artifacts generated from the Training Job.

8. An AWS Step Function state receives input parameters, does its processing and then produces an output. If there is another state next in the path, the output is provided as an input to that state. This is an elegant way for passing dynamic information between states.
Here is the code for the next AWS Step Functions state.
"Create Model": {
"Parameters": {
"PrimaryContainer": {
"Image": "544295431143.dkr.ecr.ap-southeast-2.amazonaws.com/xgboost:1",
"Environment": {},
"ModelDataUrl.$": "$.ModelArtifacts.S3ModelArtifacts"
},
"ExecutionRoleArn": "iam-role-arn",
"ModelName.$": "$.TrainingJobName"
},
"Resource": "arn:aws:states:::sagemaker:createModel",
"Type": "Task",
"ResultPath":"$.taskresult",
"Next": "Create Endpoint Config"
},

Image refers to the same container that was used in the Create Training Job state.

ModelDataUrl refers to the location where the model artifacts that were created in the previous state are stored. This value is part of the output (input to this state) from the previous state. To reference it, use $.ModelArtifacts.S3ModelArtifacts

ExecutionRoleArn is the ARN of the AWS IAM Role that was created in Step 3 above.

“Resource”: “arn:aws:states:::sagemaker:createModel” refers to the Amazon SageMaker API for creating a model

To keep things simple, the name of the generated model will be set to the TrainingJobName. This value is part of the output (input to this state) from the previous state. To reference it, use $.TrainingJobName

After this state finishes execution, you will be able to see the model in the Amazon SageMaker console.

The next state is for creating an Endpoint Configuration using the model that was just created.

Before we continue, I want to point out an additional parameter that I am using “ResultPath”:”$.taskresult”. Let me explain the reason for using this. In my next state, I must provide the name of the model that will be used to create the Endpoint Configuration. Unfortunately, this name is not part of the output of the current state Create Model, so I won’t be able to reference it. However, as you might remember, for simplicity, we set the model name to be the same as TrainingJobName and guess what, this is part of the current states input parameters! Now, if only there was a way for me to make the current state to include its input parameters in its output. Oh wait! There is a way. Using the command  “ResultPath”:”$.taskresult” instructs this AWS Step Function state to include its input parameters in its output.

9. Here is the code for the AWS Step Function state to create an Endpoint Config.

"Create Endpoint Config": {
"Type": "Task",
"Resource": "arn:aws:states:::sagemaker:createEndpointConfig",
"Parameters":{
"EndpointConfigName.$": "$.TrainingJobName",
"ProductionVariants": [
{
"InitialInstanceCount": 1,
"InstanceType": "ml.t2.medium",
"ModelName.$": "$.TrainingJobName",
"VariantName": "AllTraffic"
}
]
},
"ResultPath":"$.taskresult",
"Next":"Create Endpoint"
},

This state is pretty straight forward.

“Resource”: “arn:aws:states:::sagemaker:createEndpointConfig” refers to the Amazon SageMaker API to create an Endpoint Configuration

For simplicity, we will set the Endpoint Configuration name to be the same as the TrainingJobName. The Endpoint will be deployed initially using one  ml.t2.medium instance.

As in the previous state, we will use “ResultPath”:”$.taskresult” to circumvent the lack of parameters in the output of this state.

In the final state, I will instruct Amazon SageMaker to deploy the model endpoint.

10. Here is the code for the final AWS Step Function state.

"Create Endpoint":{
"Type":"Task",
"Resource":"arn:aws:states:::sagemaker:createEndpoint",
"Parameters":{
"EndpointConfigName.$": "$.TrainingJobName",
"EndpointName.$": "$.TrainingJobName"
},
"End": true
},

The Endpoint Configuration from the previous state is used to deploy the model endpoint using Amazon SageMaker Hosting Services.

“Resource”:”arn:aws:states:::sagemaker:createEndpoint” refers to the Amazon SageMaker API for deploying an endpoint using Amazon SageMaker Hosting Services. After this state completes successfully, the endpoint is visible in the Amazon SageMaker console.

The name of the Endpoint, for simplicity is set the same as TrainingJobName

To keep things tidy, it is nice to display an error when things don’t go as planned. There is an AWS Step Function state for that!

11. Here is the code for the state that displays the error message. This state only gets invoked if there is an error in the Create Training Job state.

"Display Error":{
"Type": "Pass",
"Result": "Finished with errors. Please check the individual steps for more information",
"End": true
}

The full AWS Step Function state machine code is available at  https://gist.github.com/nivleshc/a4a99a5c2bca1747b6da0d7da0e388c1

When creating the AWS Step Function state machine, you will be asked for an AWS IAM Role that will be used by the state machine to run the states. Unless you already have an AWS IAM Role that can carry out all the state tasks, choose the option to create a new AWS IAM Role.

To invoke the AWS Step Function state machine, just click on new execution and provide a name for the execution id. As each of the states are run, you will see the visual feedback in the AWS Step Function schematic. You will be able to see the tasks in the Amazon SageMaker console as well.

To take the above one step further, you could invoke the AWS Step Function state machine whenever new training and validation data is available in the Amazon S3 bucket. The new model can then be used to update the existing model endpoint.

Thats it folks! This is how you can automatically train, build and deploy an Amazon SageMaker model!

Once you are finished, don’t forget to clean-up, to avoid any unnecessary costs.

The following must be deleted using the Amazon SageMaker console

  • The model endpoint
  • The Endpoint Configuration
  • The model
  • Any Jupyter Notebook instances you might have provisioned and don’t need anymore
  • Any Jupyter notebooks that are not needed anymore

If you don’t have any use for the following, these can also be deleted.

  • The contents of the Amazon S3 bucket and the bucket itself
  • The AWS IAM Role that was created and the custom policy to access the Amazon S3 bucket and its contents
  • The AWS Step Function state machine

Till the next time, Enjoy!

Create A Web Chatbot For Generating Life Insurance Quotes Using Amazon Lex

Background

A few weeks back, I was asked to create a proof of concept web based chatbot for one of our clients. The web chatbot was to be used for generating life insurance quotes. The requirements were quite simple: ask a customer a few critical questions, use the responses to approximate their yearly premium and then display the premium on a webpage. Simple!

I don’t like reinventing the wheel and where possible, I leverage existing AWS services. For the task at hand, I decided to use Amazon Lex.

This blog provides the instructions for creating a web-based life insurance quote generating chatbot. It also highlights some of the challenges I faced while going from ideation to the finished product.

Let’s begin.

High Level Architecture

Below is a high-level overview of what I built.

  1. The customer will browse to the chatbot website.
  2. The customer will invoke the Amazon Lex Bot.
  3. The Amazon Lex Bot will ask a few questions and then pass the responses to an AWS Lambda function, to approximate the yearly premium for the customer.
  4. The response from the AWS Lambda function will be passed back to the Amazon Lex Bot.
  5. The Amazon Lex Bot will display the yearly premium estimate on the chatbot website.

Implementation

Let’s build the various components, as shown in the high-level overview.

AWS Lambda Function

When the Amazon Lex Bot invokes AWS Lambda, it actually calls the lambda_handler function and passes all the relevant parameters. The AWS Lambda will then use the supplied information to calculate the yearly premium and return the result.

I have pasted below the AWS Lambda Python 3.7 code that I used (getLifeInsuranceQuote). Do pay attention to the format of the return value from the AWS Lambda function. This is the format that Amazon Lex expects. To estimate the yearly premium, my AWS Lambda function called a machine learning model that had been pre-trained with life insurance data.

import json
from botocore.vendored import requests
from dateutil.relativedelta import relativedelta
from datetime import datetime
def lambda_handler(event, context):
print("event:"+str(event))
print("context:"+str(context))
customer_state = event['currentIntent']['slots']['State']
customer_firstname = event['currentIntent']['slots']['FirstName']
customer_lastname = event['currentIntent']['slots']['LastName']
customer_dob_str = event['currentIntent']['slots']['DOB']
customer_coverlevel = event['currentIntent']['slots']['CoverLevel']
customer_smoker = event['currentIntent']['slots']['Smoker']
customer_gender = event['currentIntent']['slots']['Gender']
print(customer_state)
print(customer_firstname)
print(customer_lastname)
print(customer_dob_str)
print(customer_coverlevel)
print(customer_smoker)
print(customer_gender)
date_now = datetime.now()
date_now_year = date_now.year
customer_dob_year = int(customer_dob_str)
customer_age = date_now_year customer_dob_year
print("Customer YOB:" + customer_dob_str)
print("Customer age:" + str(customer_age))
if customer_gender == "Female":
sex = 0
else:
sex = 1
if customer_smoker == "NO":
smoker = 0
else:
smoker = 1
url = "urlformlmodelapi
data = {"age": customer_age, “state”: customer_state, "sex": sex, "smoker": smoker}
r = requests.post(url,json=data)
premium = r.json()['claim_pred']
print("premium: " + str(premium))
message = customer_firstname + " from what you have told me, your monthly premiums will be approximately $" + str(round(premium/12))
return {
"sessionAttributes": {},
"dialogAction": {
"type": "Close",
"fulfillmentState": "Fulfilled",
"message": {
"contentType": "PlainText",
"content": message
}
}
}

Amazon Lex Bot

In this section, I will take you through the steps to create the Amazon Lex bot.

  1. Sign into the AWS console and then browse to the Amazon Lex service page
  2. On the left-hand side of the screen, click on Bots and then from the right-hand side, click Create.
  3. In the next screen, click Custom bot.
  4. Give the bot a name (I called mine LifeInsuranceBot) and set Output voice to None. This is only a text-based application.
  5. Set the Session timeout to 5 minutes.
  6. Leave Sentiment Analysis set to No. Leave the IAM role set to the default settings. Set COPPA to No.
  7. Click Create. The Amazon Lex bot will now be created for you.
  8. In the next screen, click on the Editor tab from the top menu.

    Before we continue, let’s go over some terminology that is used by Amazon Lex.

    Intents – an intent, in its simplest form, encapsulates what you are trying to achieve. In our case, the intent is to generate a life insurance quote.
    Utterances – this describes the possible phrases that a user could use to invoke an intent. Amazon Lex uses utterances to identify which intent it should pass the request to. In our situation, a possible utterance would be “I would like to get a life insurance quote”.
    Slots – these can be thought of as variables. You would ask the user a question and the response will be held in a slot. Like variables, a slot must have a type. The slot type is used by Amazon Lex to convert the user’s response into the correct format. For example, if you ask the user for their date of birth, the slot that will capture their response must have a type of AMAZON.DATE. This ensures that the date of birth is stored as a date.

  9. From the left-hand side menu, click on the plus sign beside Intents and then click Create Intent. You will be asked for a unique name for your intent. In my case, I set the intent name to generateLifeInstanceQuote.
  10. In the right-hand side, under Sample utterances enter phrases that will invoke this intent. I set this to I would like to get a life insurance quote.
  11. Amazon Lex comes with a lot of built-in slot types, however if they don’t match your use case, you can easily create custom slot types. For our intent, we will create three custom slot types.

    From the left-hand side, click on the plus beside Slot types and then create new slot types as per the following screenshots

  12. On to the Slots! As I mentioned previously, slots are used by Amazon Lex to get responses from the user. Each slot has a name, a type and a prompt. The prompt is what Amazon Lex will ask the user, and the response is stored in that particular slot. The prompts are asked in the order of priority assigned to them, from lowest to highest. I prefer to give some “character” to my prompts, to keep users engaged. ProTip: You can reference other slots in your prompt by enclosing the slot name within {} For example, if you are capturing the user’s name in the slot name FirstName, then you can prompt the user with Hello {FirstName}, how are you today?. When Amazon Lex prompts the user, it will insert the user’s name in place of FirstName. A touch of personalisation with minimal effort!
    Create slots as per the following screenshot.The slot type for FirstName is AMAZON.US_FIRST_NAME and the prompt is “Ok, I can help you with that. Let me get some details first. What is your first name?”

    The slot type for LastName is AMAZON.US_LAST_NAME

    The prompt for DOB is “Thanks {FirstName}. What year were you born in?”

    The prompt for CoverLevel is “Thank you for answering the questions {FirstName}. What amount do you want to take out the life insurance for?”

  13. The responses from the user will be passed to the AWS Lambda function, the result provided to the user.

    To enable this, in the right-hand side, under Fulfillment select AWS Lambda function and choose the AWS Lambda function that was created from the drop down beside Lambda function. Choose the appropriate version or alias.

  14. Click Save Intent.
  15. To get the Bot ready, click on Build from the top right-hand side of the screen.
  16. After the build is complete, you can test the Bot by using the Test Chatbot console from the top right-hand side of the screen.

Time to Panic!!!

Having successfully tested the Amazon Lex Bot, I was quite impressed with myself. But wait! I couldn’t find any way to “publish” it to a website! I didn’t want to showcase this Bot by using the “Test Chatbot” console! This is when I started panicking!

A Life Saver!

After searching frantically, I came across https://aws.amazon.com/blogs/machine-learning/greetings-visitor-engage-your-web-users-with-amazon-lex/, this article had exactly what I needed, a way to integrate my Amazon Lex bot with a html front end! Yay!

Amazon Cognito Identity Pool

    1. Go to the Amazon Cognito service page and then click on Manage Identity Pools. Then click on Create new identity pool.
    2. Provide a name for the Identity pool (I named mine LifeInsuranceBotPool) and tick the option Enable access to unauthenticated identities and click Create Pool.
    3. In the next screen, you will be asked to assign an IAM role. Click on View Details and note down the name of the roles that will be created. Then click Allow.
    4. The identity pool will be created and in the next screen, a sample code with the IdentityPoolId will be shown. Change the platform to Javascript and note down the IdentityPoolId and the region.
    5. Go to the AWS IAM service page and locate the two IAM roles that Amazon Cognito had created. Open each one of them and attach the following additional policies:
      • AmazonLexRunBotsOnly
      • AmazonPollyReadOnlyAccess

A front-end for our Amazon Lex Bot

The front end will be a static html page, served from an Amazon S3 bucket.

To make things easier, I have extracted the html code for the static website from  https://aws.amazon.com/blogs/machine-learning/greetings-visitor-engage-your-web-users-with-amazon-lex/ .

It is available at https://gist.github.com/nivleshc/bff75e30cc4f0133aab3abde8248814f

Save the above file as index.html and then carry out the following modifications.

Locate the following lines of code in index.html (lines 68 – 97)

// Initialize the Amazon Cognito credentials provider
AWS.config.region = 'us-east-1'; // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
// Provide your Pool Id here
IdentityPoolId: 'us-east-1:XXXXX',
});
var lexruntime = new AWS.LexRuntime();
var lexUserId = 'chatbot-demo' + Date.now();
var sessionAttributes = {};
function pushChat() {
// if there is text to be sent…
var wisdomText = document.getElementById('wisdom');
if (wisdomText && wisdomText.value && wisdomText.value.trim().length > 0) {
// disable input to show we're sending it
var wisdom = wisdomText.value.trim();
wisdomText.value = '…';
wisdomText.locked = true;
// send it to the Lex runtime
var params = {
botAlias: '$LATEST',
botName: 'BookTrip',
inputText: wisdom,
userId: lexUserId,
sessionAttributes: sessionAttributes
};

Change the values for AWS.config.region and AWS.config.credentials to what was displayed in the sample code when the Amazon Cognito Identity pool was created.

Replace chatbot-demo in the variable lexUserId to something more descriptive. This will be the user created within your Amazon Cognito Identity pool whenever the static website is accessed (for my deployment, I set this to lifeinsurancebot).

Change the botName to the name of your Amazon Lex Bot (in my case, my Amazon Lex Bot was called LifeInsuranceBot). If you have multiple versions of your Amazon Lex Bot and you are not using the latest version, then change the variable botAlias to the version you are using.

You might have noticed that index.html contains a lot of references to the demo chatbot that was created in https://aws.amazon.com/blogs/machine-learning/greetings-visitor-engage-your-web-users-with-amazon-lex/. I would suggest going through the html code and changing these references so that they refer to your own Amazon Lex Bot.

Next, we need a html page that will be returned when an error occurs with our static website. As good chefs do, I prepared one earlier. Download the contents of https://gist.github.com/nivleshc/853c7efc7979bdff6b5cc1a49074b9ce and save it as error.html.

Follow the steps below to create an Amazon S3 hosted static website

  1. Create an Amazon S3 bucket in a region closest to your Amazon Lex Bot (it is highly recommended to have the Amazon Lex Bot in an AWS region that is closest to your users)
  2. Upload the two files from above (index.html and error.html) to the Amazon S3 bucket. Change the permissions on these two files so that they are publicly accessible.
  3. Enable the Amazon S3 bucket for static website hosting. Note down the endpoint address shown in the Static website hosting section.This is the website’s address (URL).

Thats it folks! The Life Insurance Bot will now be alive!. To access it, open your favourite internet browser and go to the static website’s endpoint address.

The final product!

I must admit, a lot of work went into making this Amazon Lex Bot, however it is easily justified by the end result! One thing I would like to state is that, this prototype didn’t take more than 2 days to build. The speed at which you can create proof-of-concepts in AWS gives you a great advantage over your competitors.

Below is a screenshot of what my LifeInsuranceBot looks like in action. If you followed through, yours would be similar.

I hope this blog was useful and comes in handy when you are trying to create your own web chatbots.

Till the next time, Enjoy!

Creating a Contact Center in minutes using Amazon Connect

Background

In my previous blog (https://nivleshc.wordpress.com/2019/10/09/managing-amazon-ec2-instances-using-amazon-ses/), I showed how we can manage Amazon EC2 instances using emails. However, what if you wanted to go further than that? What if, instead of sending an email, you instead wanted to dial in and check the status of or start/stop your Amazon EC2 instances?

In this blog, I will show how I used the above as a foundation to create my own Contact Center. I enriched the experience by including an additional option for the caller, to be transferred to a human agent. All this in minutes! Still skeptical? Follow on and I will show you how I did all of this using Amazon Connect.

High Level Solution Design

Below is the high-level solution design for the Contact Center I built.

The steps (as denoted by the numbers in the diagram above) are explained below

  1. The caller dials the Direct Inward Dial (DID) number associated with the Amazon Connect instance
  2. Amazon Connect answers the call
  3. Amazon Connect invokes the AWS Lambda function to authenticate the caller.
  4. The AWS Lambda function authenticates the caller by checking their callerID against the entries stored in the authorisedCallers DynamoDB table. If there is a match, the first name and last name stored against the callerID is returned to Amazon Connect. Otherwise, an “unauthorised user” message is returned to Amazon Connect.
  5. If the caller is unauthorised, Amazon Connect informs them of this and hangs up the call.
  6. If the caller is authorised, Amazon Connect uses the first name and last name provided by AWS Lambda function to personalise a welcome message for them. Amazon Connect then provides the caller with two options:
      •  (6a) press 1 to get the status of the Amazon EC2 instances. If this is pressed, Amazon Connect invokes an AWS Lambda function to get the status of the Amazon EC2 instances and plays the results to the caller
      • (6b) press 2 to talk to an agent. If this is pressed, Amazon Connect places the call in a queue,  where it will be answered by the next available agent

     

Preparation

My solution requires the following components

  • Amazon DynamoDB table to store authorised callers (an item in this table will have the format phonenumber, firstname,  lastname)
  • AWS Lambda function to authenticate callers
  • AWS Lambda function to get the status of all Amazon EC2 instances in the region

I created the following AWS CloudFormation template to provision the above resources.

AWSTemplateFormatVersion: "2010-09-09"
Description: Template for deploying Amazon DynamoDB and AWS Lambda functions that will be used by the Amazon Connect instance
Parameters:
authorisedUsersTablename:
Description: Name of the Amazon DynamoDB Table that will be created to store phone numbers for approved callers to Amazon Connect
Type: String
Default: amzn-connect-authorisedUsers
DynamoDBBillingMode:
Description: Billing mode to be used for authorisedUsers Amazon DynamoDB Table
Type: String
AllowedValues: [PAY_PER_REQUEST]
Resources:
authoriseCallerLambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
Effect: Allow
Principal:
Service:
lambda.amazonaws.com
Action:
sts:AssumeRole
Path: "/"
Policies:
PolicyName: logsStreamAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
Effect: Allow
Action:
logs:CreateLogGroup
logs:CreateLogStream
logs:PutLogEvents
Resource: arn:aws:logs:*:*:*
PolicyName: DynamoDBAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
Effect: Allow
Action:
dynamodb:Query
Resource: !GetAtt authorisedUsersTable.Arn
getInstanceStatusLambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
Effect: Allow
Principal:
Service:
lambda.amazonaws.com
Action:
sts:AssumeRole
Path: "/"
Policies:
PolicyName: logsStreamAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
Effect: Allow
Action:
logs:CreateLogGroup
logs:CreateLogStream
logs:PutLogEvents
Resource: arn:aws:logs:*:*:*
PolicyName: EC2DescribeAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
Effect: Allow
Action:
"ec2:Describe*"
Resource: "*"
authoriseCallerFunctionPolicy:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt
authoriseCaller
Arn
Principal: connect.amazonaws.com
getInstanceStatusFunctionPolicy:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt
getInstanceStatus
Arn
Principal: connect.amazonaws.com
authorisedUsersTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Ref authorisedUsersTablename
AttributeDefinitions:
AttributeName: phoneNumber
AttributeType: S
KeySchema:
AttributeName: phoneNumber
KeyType: HASH
BillingMode: !Ref DynamoDBBillingMode
authoriseCaller:
Type: AWS::Lambda::Function
Properties:
FunctionName: "amzn-connect-authoriseCaller"
Description: "This function checks if the caller is authorised to use the Amazon Connect Service"
Handler: index.lambda_handler
Runtime: python3.6
Role: !GetAtt 'authoriseCallerLambdaExecutionRole.Arn'
Environment:
Variables:
AUTHORISEDUSERSTABLE: !Ref authorisedUsersTable
Code:
ZipFile: |
import boto3
import os
from boto3.dynamodb.conditions import Key, Attr
def lambda_handler(event, context):
print("event:",event)
print("context:",context)
authorisedUsersTable = os.environ['AUTHORISEDUSERSTABLE']
callerID = event["Details"]["ContactData"]["CustomerEndpoint"]["Address"]
#Establish connection to dynamoDB and retrieve table
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(authorisedUsersTable)
response = table.query(KeyConditionExpression=Key('phoneNumber').eq(callerID))
if (len(response['Items']) > 0):
firstName = response['Items'][0]['firstName']
lastName = response['Items'][0]['lastName']
else:
firstName = 'unauthorised'
lastName = 'unauthorised'
callerDetails = {
'phoneNumber' : callerID,
'firstName' : firstName,
'lastName' : lastName
}
print("CallerDetails:",str(callerDetails))
return callerDetails
getInstanceStatus:
Type: AWS::Lambda::Function
Properties:
FunctionName: "amzn-connect-getInstanceStatus"
Description: "This function checks and reports the number of EC2 instances that are running and stopped in the AWS region where this AWS Lambda function is running"
Handler: index.lambda_handler
Runtime: python3.6
Role: !GetAtt 'getInstanceStatusLambdaExecutionRole.Arn'
Code:
ZipFile: |
import boto3
def lambda_handler(event, context):
print("event:",event)
print("context",context)
ec2 = boto3.client("ec2")
ec2_status_running = ec2.describe_instances(
Filters=[
{
'Name':'instance-state-name',
'Values':['running']
}
]
)
ec2_status_running = ec2.describe_instances(
Filters=[
{
'Name':'instance-state-name',
'Values':['running']
}
]
)
ec2_status_stopped = ec2.describe_instances(
Filters=[
{
'Name':'instance-state-name',
'Values':['stopped']
}
]
)
num_ec2_running = len(ec2_status_running['Reservations'])
num_ec2_stopped = len(ec2_status_stopped['Reservations'])
result = {
'numberEC2Running': num_ec2_running,
'numberEC2Stopped': num_ec2_stopped
}
print("Number of EC2 instances running:",num_ec2_running)
print("Number of EC2 instances stopped:",num_ec2_stopped)
return result

The above AWS CloudFormation template can be downloaded from https://gist.github.com/nivleshc/926259dbbab22dd4890e0708cf488983

Implementation

Currently AWS CloudFormation does not support Amazon Connect. The implementation must be done manually.

Leveraging on my own experience with setting up Amazon Connect solutions,  I observed that there are approximately three stages that are required to get a Contact Center up and running. These are:

  • Provisioning an Amazon Connect instance – this is straight forward and essentially is where an Amazon Connect instance is provisioned and made ready for your use
  • Configuring the Amazon Connect instance – this contains all the tasks to customise the Amazon Connect instance. It includes the configuration of the Direct Inward Dial (DID), hours or operations for the Contact Center, Routing profiles, users etc
  • Creating a custom Contact flow – a Contact flow defines the customer experience of your Contact Center, from start to finish. Amazon Connect provides a few default Contact flows however it is highly recommended that you create one that aligns with your own business requirements.

Follow along and I will show you how to go about setting up each of the above mentioned stages.

Provision the Amazon Connect Instance

  1. From the AWS Console, open the Amazon Connect service. Select the Sydney region (or a region of your choice, however do keep in mind that at the moment, Amazon Connect is only available in a few regions)
  2. Enter an Access URL for your Amazon Connect Instance. This URL will be used to access the Amazon Connect instance once it has been provisioned.
  3. In the next screen, create an administrator account for this Amazon Connect instance
  4. The next prompt is for Telephony options. For my solution, I selected the following:
    1. Incoming calls: I want to handle incoming calls with Amazon Connect
    2. Outgoing calls: I want to make outbound calls with Amazon Connect
  5. In the next screen, Data Storage options are displayed. For my solution, I left everything as default.
  6. In the next screen, review the configuration and then click Create instance

Configure the Amazon Connect Instance

After the Amazon Connect instance has been successfully provisioned, use the following steps to configure it:

  1. Claim a phone number for your Amazon Connect Instance. This is the number that users will be calling to interact with your Amazon Connect instance (for claiming non toll free local numbers, you must open a support case with AWS, to prove that you have a local business in the country where you are trying to claim the phone number. Claiming a local toll-free number is easier however it is more expensive)
  2. Create some Hour of operation profiles. These will be used when creating a queue
  3. Create a queue. Each queue can have different hours of operation assigned
  4. Create a routing profile. A user is associated with a routing profile, which defines their inbound and outbound queues.
  5. Create users. Once created, assign the users to a predefined security profile (administrator, agent etc) and also assign them to a specific routing profile

Create a custom Contact flow

A Contact flow defines the customer experience of your Contact Center, from start to finish. By default, Amazon Connect provides a few Contact flows that you can use. However, it is highly recommended that you create one that suits your own business requirements.

To create a new Contact flow, follow these steps:

  • Login to your Amazon Connect instance using the Access URL and administrator account (you can also access your Amazon Connect instance using the AWS Console and then click on Login as administrator)
  • Once logged in, from the left-hand side menu, go to Routing and then click on Contact flows
  • In the next screen, click on Create contact flow
  • Use the visual editor to create your Contact flow

Once the Contact flow has been created, attach it to your Direct Inward Dial (DID) phone number by using the following steps:

  • from the left-hand side menu, click on Routing and then Phone numbers.
  • Click on the respective phone number and change its Contact flow / IVR to the Contact flow you want to attach to this phone number.

Below is a screenshot of the Contact flow I created for my solution. It shows the flow logic I used and you can easily replicate it for your own environment. The red rectangles show where the AWS Lambda functions (mentioned in the pre-requisites above) are used.

This is pretty much all that is required to get your Contact Center up and running. It took me approximately thirty minutes from start to finish (this does not include the time required to provision the Amazon DynamoDB tables and AWS Lambda functions). However, I would recommend spending time on your Contact flows as this is brains of the operation. This must be done in conjunction with someone who understands the business really well and knows the outcomes that must be achieved by the Contact Center solution. There is a lot that can be done here and the more time you invest in your Contact flow, the better outcomes you will get.

The above is just a small part of what Amazon Connect is capable of. For its full set of capabilities, refer to https://aws.amazon.com/connect/

So, if you have been dreaming of building your own Contact Center, however were worried about the cost or effort required? Wait no more! You can now easily create one in minutes using Amazon Connect and pay for only what you use and tear it down if you don’t need it anymore. However, before you start, I would strongly recommend that you get yourself familiar with the Amazon Connect pricing model. For example – you get charged a daily rate for any claimed phone numbers that are attached to your Amazon Connect Instance (this is similar to a phone line rental charge). Full pricing is available at https://aws.amazon.com/connect/pricing/).

I hope the above has given you some insights into Amazon Connect. Till the next time, Enjoy!

Managing Amazon EC2 Instances using Amazon SES

Background

Most people know Amazon Simple Email Service (SES) just as a service for sending out emails. However, did you know that you can use it to receive emails as well? If this interests you, more information is available at https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email.html.

In this blog I will show how I provisioned a solution to manage my Amazon EC2 instances using emails. The solution uses Amazon SES and AWS Lambda. Now, some of you might be saying, can’t you just use the AWS console or app for this? Well, yes you can, however for me personally, logging into an AWS console just to get the status of my Amazon EC2 instances, or to start/stop them was more effort than I deemed necessary. The app surely makes this task trivial, however the main purpose of this blog is to showcase the capabilities of Amazon SES

Solution Architecture

Below is the high-level design for my solution.

The individual steps (labelled using numbers) are described below

  1. The admin sends an email to an address attached to an Amazon SES rule
  2. Amazon SES receives the email, performs a spam and virus check. If the email passes the check, Amazon SES invokes the manageInstances AWS Lambda function, passing the contents of the email to it (unfortunately the contents of the body are not passed)
  3. The manageInstances AWS Lambda function authenticates the sender based on the from address (this is a very rudimentary authentication system. A stronger authentication mechanism must be used if this solution is to be deployed in a production environment – maybe include a multi-factor authentication system). It extracts the command from the email’s subject and executes it
  4. The manageInstances AWS Lambda function uses Amazon SES to send the response of the command back to the admin
  5. Amazon SES delivers the email containing the command’s output to the admin

Prerequisites

To use Amazon SES for receiving incoming emails, first verify your domain within it and then point your domain’s DNS MX entry to your region’s Amazon SES endpoint. Full Instructions to carry this out can be found at https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-getting-started.html

Implementation

Lambda Function

The Lambda function is created first as it is required for the Amazon SES Rules.

The Lambda function carries out the following tasks

  • authenticates the sender by comparing the email’s from address with a predefined list of approved senders. To prevent a situation where the Lambda function can be inadvertently used as a spam bot, all emails from senders not on the approved list will be dropped.
  • checks if the specified command is in the list of commands that is currently supported. If yes, then the command is executed, and the output sent back to the admin. If the command is unsupported, a reply stating that an invalid command was specified is sent back to the admin

Here are the attributes of the Lambda function I created

Function name: manageInstances
Runtime:             Python 3.6
Region:                North Virginia (us-east-1) This is to ensure that the Lambda function and the Amazon SES rules are in the same region
Role:                     The role that is used by the Lambda function must have the following permissions attached to it

             ec2:DescribeInstances
             ec2:StartInstances
             ec2:StopInstances
             SES:SendEmail

Here is the code for the AWS Lambda function (set the approvedSenders list to contain the email address of approved senders)

import boto3
def provideHelp(params):
message = "Set the subject of the email to one of the following\n"
message += "help – provides this help\n"
message += "status – provides the status of all ec2 instances in the region\n"
message += "start {instance-id} – starts the ec2 instance with with the specified instance-id\n"
message += "stop {instance-id} – stops the ec2 instance with the specified instance id"
return message
def getStatus(params):
#get a list of all ec2 instances
print("getStatus:Params:",params)
#if a parameter is provided, it is the aws region to check
if (len(params) >= 1):
ec2 = boto3.client("ec2", params[0])
else:
ec2 = boto3.client("ec2")
response = ec2.describe_instances()
instances = response['Reservations']
number_instances = len(instances)
print("NumInstances:",number_instances)
message = ""
for instance in instances:
print("Instance:",str(instance))
instance_id = instance['Instances'][0]['InstanceId']
message += instance_id + "\t"
try:
if (instance['Instances'][0]['Tags'][0]['Key'] == 'Name'):
instance_name = instance['Instances'][0]['Tags'][0]['Value']
if (instance_name == ""):
message += "[No Name Found]\t"
else:
message += instance_name + "\t"
except:
message += "[No Name Found]\t"
instance_state = instance['Instances'][0]['State']['Name']
message += instance_state + "\t"
try:
instance_privateip = instance['Instances'][0]['PrivateIpAddress']
message += instance_privateip + "\t"
except:
message += "[No Private IP]\t"
try:
instance_publicip = instance['Instances'][0]['PublicIpAddress']
message += instance_publicip + "\t"
except:
message += "[No Public IP]\t"
message += "\n"
return message
def startInstance(params):
if (len(params) > 1):
instanceId = params[0]
aws_region = params[1]
ec2 = boto3.client("ec2", aws_region)
else:
instanceId = params[0]
ec2 = boto3.client("ec2")
try:
response = ec2.start_instances(
InstanceIds=[instanceId]
)
message = "Starting instance " + str(instanceId) + " Please check status in a couple of minutes\n" + str(response)
except Exception as e:
message = "Error starting instance(s) :" + str(instanceId) + " " + str(e)
print(message)
return message
def stopInstance(params):
if (len(params) > 1):
instanceId = params[0]
aws_region = params[1]
ec2 = boto3.client("ec2", aws_region)
else:
instanceId = params[0]
ec2 = boto3.client("ec2")
try:
response = ec2.stop_instances(
InstanceIds=[instanceId]
)
message = "Stopping instance " + str(instanceId) + " Please check status in a couple of minutes\n" + str(response)
except Exception as e:
message = "Error stopping instance(s) " + str(instanceId) + " " + str(e)
print(message)
return message
def sendEmail(fromAddress,recipientAddress,subject,body):
#sending email
print("sending email")
client = boto3.client('ses')
response = client.send_email(
Destination={
'ToAddresses': [recipientAddress],
},
Message={
'Body': {
'Text': {
'Charset': 'UTF-8',
'Data': body
},
},
'Subject': {
'Charset': 'UTF-8',
'Data': subject
},
},
ReplyToAddresses=[fromAddress],
ReturnPath=fromAddress,
Source=fromAddress
)
print("Response from SES:",response)
def lambda_handler(event, context):
approvedSenders = ['john@example.com','tom@example.com','jane@example']
print("Event:",event)
print("Context",context)
emailSender = event["Records"][0]["ses"]["mail"]["source"]
emailSubject = event["Records"][0]["ses"]["mail"]["commonHeaders"]["subject"]
command_split = emailSubject.split(" ")
command = command_split[0].lower()
if (len(command_split) > 1):
commandParams = command_split[1:len(command_split)]
else:
commandParams = "" #if there are no command params, then just set it to blank
print("From:",emailSender)
print("Subject:",emailSubject)
print("Command:",command)
#authenticate the sender based on fromAddress
if emailSender in approvedSenders:
switcher = {
"help": provideHelp,
"status": getStatus,
"start": startInstance,
"stop": stopInstance
}
#get the command that was specified in the email
functionToRun = switcher.get(command, lambda params: "invalid command")
body = functionToRun(commandParams)
sendEmail("admin@managedinstances.com",emailSender,"Execution result for command:"+ emailSubject, str(body))
else:
print("Sender ",emailSender," not approved for executing commands. Ignore")

view raw
manageInstances.py
hosted with ❤ by GitHub

The AWS Lambda function code can be downloaded from https://gist.github.com/nivleshc/f9b32a14d9e662701c3abcbb8f264306

Amazon SES Email Receiving Rule

Next, the Amazon SES Email Receiving rule that handles the incoming emails must be created. Please note that currently Amazon SES is supported in a few regions only. For my solution, I used the North Virginia (us-east-1) region.

Below are the steps to create the rule

  • Open Simple Email Service service page from within the AWS console (ensure you are in the correct AWS region)
  • From the left-hand side menu, navigate down to the Email Receiving section and then click Rule Sets.
  • The right-hand side of the screen will show the currently defined rule sets. I used the predefined default-rule-set.
  • Click on View Active Rule Set and then in the next screen click Create Rule.
  • In the next screen, for the recipient address, enter the email address to which emails will be sent to, to carry out the commands (the email domain has to correspond to the domain that was verified with Amazon SES, as part of the prerequisites mentioned above)
  • In the next screen, for actions, select Lambda.
  • Select the name of the Lambda function that was created to manage the instances from the drop down (for me, this was manageInstances)
  • Ensure the Invocation type is set to Event.
  • You do not need to set the SNS topic, however if you need to know when this Amazon SES action is carried out, select the appropriate SNS topic (you will need to create an SNS topic and subscribe to it using your email address)
  • Click Next Step.
  • In the next screen, provide a name for the rule. Ensure the options Enabled and Enable spam and virus scanning are ticked.
  • Click Next Step and then review the settings.
  • Click Create Rule.

Usage

The solution, once implemented supports the following commands

help   - provides information about the commands and their syntax
status - provides the status of all Amazon EC2 instances in the region that the Lambda function is running in. It lists the instance-id and name of those instances (name is derived from the tag with the key Name)
start {instance-id} - starts the Amazon EC2 instance that has the specified instance-id
stop {instance-id}  - stops the Amazon EC2 instance that has the specified instance-id

To use, send an email from an approved sender’s email to the email address attached to Amazon SES.

The table below shows, what the subject must be, for each command.

Command Subject
Help help
Status for instances in us-east-1 status
Start an instance with instance-id i-0e7e011b42e814465 start i-0e7e011b42e814465
Stop an instance with instance-id i-0e7e011b42e814465 stop i-0e7e011b42e814465

The output of the status command is in the following format

<instance-id> <instance-name> <status> <private-ip> <public-ip>

for example
i-03a1ab124f554z805 LinuxServer01 Running 172.16.31.10 52.10.100.34

The only problem with the solution is that all commands are performed on Amazon EC2 instances running in the same AWS region as the Lambda function. What if you wanted to carry out the commands on another region?

For the keen eyed, you would have spotted the Easter egg I hid in the Lambda function code. Here is what the subject must be if the command is to be carried out in an AWS region different to where the Lambda function is running (simply provide the AWS region at the end of the command)

Command Subject
Help help
Status for instances in ap-southeast-2 (Sydney) status ap-southeast-2
Start an instance with instance-id i-0e7e011b42e814465 in ap-southeast-2 (Sydney) region start i-0e7e011b42e814465 ap-southeast-2
Stop an instance with instance-id i-0e7e011b42e814465 in ap-southeast-2 (Sydney) region stop i-0e7e011b42e814465 ap-southeast-2

There you go! Now you can keep an eye on and control your Amazon EC2 instances with just your email.

A good use case can be when you are commuting and need to RDP into your Windows Amazon EC2 instance from your mobile (I am guilty of doing this at times). You can quickly start the Amazon EC2 instance, get its public ip address, and then connect using RDP.  Once finished, you can shut down the instance to ensure you don’t get charged after that.

I hope this blog was useful to you. Till the next time, Enjoy!

A scenario-based tutorial for Azure Kubernetes Service – Part 2

Introduction

In this blog, we will dig a little deeper into Azure Kubernetes Service (AKS). What better way to do this than by building an AKS cluster ourselves! Just a heads-up, I will be using terminology that was introduced in part 1 of this mini-blog series. If you haven’t read it, or need a refresher, you can access it at https://nivleshc.wordpress.com/2019/03/04/a-scenario-based-tutorial-for-azure-kubernetes-service-part-1

Let’s start by describing the AKS cluster architecture. The diagram below provides a great overview.

(Image copied from https://docs.microsoft.com/en-au/azure/aks/media/concepts-clusters-workloads/cluster-master-and-nodes.png)

The AKS Cluster is made up of two components. These are described below

  • cluster master node is an Azure managed service, which takes care of the Kubernetes service and ensures all the application workloads are properly running.
  • node is where the application workloads run.

The cluster master node is comprised of the following components

  • kube-apiserver – this api server provides a way to interface with the underlying Kubernetes API. Management tools such as kubectl or Kubernetes dashboard interact with this to manage the Kubernetes cluster.
  • etcd – this provides a key value store within Kubernetes, and is used for maintaining state of the Kubernetes cluster and state
  • kube-scheduler – the role of this component is to decide which nodes the newly created or scaled up application workloads can run on, and then it starts these workloads on them.
  • kube-controller-manager – the controller manager looks after several smaller controllers that perform actions such as replicating pods and handing node operations

The node is comprised of the following

  • kubelet – this is an agent that handles the orchestration requests from the cluster master node and also takes care of scheduling the running of the requested containers
  • kube-proxy – this component provides networking services on each node. It takes care of routing network traffic and managing IP addresses for services and pods
  • container runtime – this allows the container application workloads to run and interact with other resources within the node.

For more information about the above, please refer to https://docs.microsoft.com/en-au/azure/aks/concepts-clusters-workloads

Now that you have a good understanding of the Kubernetes architecture, lets move on to the preparation stage, after which we will deploy our AKS cluster.

Preparation

AKS subnet size

AKS uses a subnet to host nodes, pods, and any other Kubernetes and Azure resources that are created for the AKS cluster. As such, it is extremely important that the subnet is appropriately sized, to ensure it can accommodate the resources that will be initially created, and still have enough room for any future updates.

There are two networking methods available when deploying an Azure Kubernetes Service cluster

  • Kubenet
  • Azure Container Networking Interface (CNI)

AKS uses kubnet by default, and in doing so, it automatically creates a virtual network and subnets that are required to host the pods in. This is a great solution if you are learning about AKS, however if you need more control, it is better to go with Azure CNI. With Azure CNI, you get the option to use an existing virtual network and subnet or you can create a custom one. This is a much better option, especially when deploying into a production environment.

In this blog, we will use Azure CNI.

The formula below provides a good estimate on how large your subnet must be, in order to accommodate your AKS resources.

Subnet size = (number of nodes + 1) + ((number of nodes + 1) * maximum number of pods per node that you configure)

When using Azure CNI, by default each node is setup to run 30 pods. If you need to change this limit, you will have to deploy your AKS cluster using Azure CLI or Azure Resource Manager templates.

Just as an example, for a default AKS cluster deployment, using Azure CNI with 4 nodes, the subnet size at a minimum must be

IPs required = (4 + 1) + ((4+ 1) * (30 pods per node)) = 5 + (5 * 30) = 155

This means that the subnet must be at least a /24.

For this blog, create a new resource group called myAKS-resourcegroup. Within this new resource group, create a virtual network called AKSVNet with an address space of 10.1.0.0/16. Inside this virtual network, create a subnet called AKSSubnet1 with an address range of 10.1.3.0/24.

Deploying an Azure Kubernetes Service Cluster

Let’s proceed on to deploying our AKS cluster.

  1. Login to your Azure Portal and add Kubernetes Service
  2. Once you click on Create, you will be presented with a screen to enter your cluster’s configuration information
  3. Under Basics
  • Choose the subscription into which you want to deploy the AKS cluster
  • Choose the resource group into which you want to deploy the AKS cluster. One thing to point out here is that the cluster master node will be deployed in this resource group, however a new resource group with a name matching the naming format MC_<AKS master node resource group name>_<AKS cluster name>_region will be created to host the nodes where the containers will run (if you use the values specified in this blog, your node resource group will be named MC_myAKS-resourcegroup_mydemoAKS01_australiaeast)
  • Provide the Kubernetes cluster name (for this blog, let’s call this mydemoAKS01)
  • Choose the region you want to deploy the AKS cluster in (for this blog, we are deploying in australiaeast region)
  • Choose the Kubernetes version you want to deploy (you can choose the latest version, unless there is a reason to choose a specific version)
  • DNS name prefix – for simplicity, you can set this to the same as the cluster name
  • Choose the Node size. (for this blog, lets choose D2s v3 (2 vcpu, 8 GB memory)
  • Set the Node count to 1 (the Node count specifies the number of nodes that will be initially created for the AKS cluster)
  • Leave the virtual nodes to disabled

Under Authentication

  • Leave the default option to create a service principal (you can also provide an existing service principal, however for this blog, we will let the provisioning process create a new one for us)
  • RBAC allows you to control who can view the Kubernetes configuration (kubeconfig) information and to limit the permissions that they have. For now, leave RBAC turned off

Under Networking

  • Leave HTTP application routing set to No
  • As previously mentioned, by default AKS uses kubenet for networking. However, we will use Azure CNI. Change the Network configuration from Basic to Advanced
  • Choose the virtual network and subnet that was created as per the prerequisites (AKSVNet and AKSSubnet1)
  • Kubernetes uses a separate address range to allocate IP addresses to internal services within the cluster. This is referred to as Kubernetes service address range. This range must NOT be within the virtual network range and must not be used anywhere else. For our purposes we will use the range 10.2.4.0/24. Technically, it is possible to use IP addresses for the Kubernetes service address range from within the cluster virtual network, however this is not recommended due to potential of IP address overlaps which could potentially cause unpredictable behaviour. To read more about this, you can refer to https://docs.microsoft.com/en-au/azure/aks/configure-azure-cni.
  • Leave the Kubernetes DNS service IP address as the default 10.2.4.10 (the default is set to the tenth IP address within the Kubernetes service address range)
  • Leave the Docker bridge address as the default 172.17.0.1/16. The Docker Bridge lets AKS nodes communicate with the underlying management platform. This IP address must not be within the virtual network IP address range of your cluster, and shouldn’t overlap with other address ranges in use on your network

Under Monitoring

  • Leave enable container monitoring set to Yes
  • Provide an existing Log Analytics workspace or create a new one

Under Tags

  • Create any tags that need to be attached to this AKS cluster
     4.  Click on Next: Review + create to get the settings validated.
After validation has successfully passed, click on Create.
Just be aware that it can take anywhere from 10 – 15 minutes to complete the AKS cluster provisioning.

While you are waiting

During the AKS cluster provisioning process, there are a number of things that are happening under the hood. I managed to track down some of them and have listed them below.

  • Within the resource group that you specified for the AKS cluster to be deployed in, you will now see a new AKS cluster with the name mydemoAKS01
  • If you open the virtual network that the AKS cluster has been configured to use and click on Connected devices, you will notice that a lot of IP addresses that have been already allocated.

    I have noticed that the number of IP addresses equals

    ((number of pods per node) + 1) * number of nodes

   FYI – for the AKS cluster that is being deployed in this blog, it is 31

  • A new resource group with the name complying to the naming format MC_<AKS master node resource group name>_<AKS cluster name>_region will be created. In our case it will be called MC_myAKS-resourcegroup_mydemoAKS01_australiaeast. This resource group will contain the virtual machine for the node (not the cluster master node), including all the resources that are needed for the virtual machines (availability set, disk, network card, network security group)

What will this cost me?

The cluster master node is a managed service and you are not charged for it. You only pay for the nodes on which the application workloads are run (these are those resources inside the new resource group that gets automatically created when you provision the AKS cluster).

In the next blog, we will delve deeper into the newly deployed AKS cluster, exposing its configuration using command line tools.

Happy sailing and till the next time, enjoy!

Replacing your Secure FTP Server with Amazon Simple Storage Service

Introduction

What if I told you that you could get rid of most of your servers, however still consume the services that you rely on them for? No longer will you have to worry about ensuring the servers are up all the time, that they are regularly patched and updated. Would you be interested?

To quote Werner Vogel “No server is easier to manage than no server”.

In this blog, I will show you how you can potentially replace your secure ftp servers by using Amazon Simple Storage Service (S3). Amazon S3 provides additional benefits, for instance, lifecycle policies which can be used to automatically move older files to a cheaper storage, which could potentially save you lots of money.

Architecture

The solution is quite simple and is illustrated in the following diagram.

Replacing Secure FTP with Amazon S3 - Architecture

We will create an Amazon S3 bucket, which will be used to store files. This bucket will be private. We will then create some policies that will allow our users to access the Amazon S3 bucket, to upload/download files from it. We will be using the free version of CloudBerry Explorer for Amazon S3, to transfer the files to/from the Amazon S3 bucket. CloudBerry Explorer is an awesome tool, its interface is quite intuitive and for those that have used a gui version of a secure ftp client, it looks very similar.

With me so far? Perfect. Let the good times begin 😉

Lets first configure the AWS side of things and then we will move on to the client configuration.

AWS Configuration

In this section we will configure the AWS side of things.

  1. Login to your AWS Account
  2. Create a private Amazon S3 bucket (for the purpose of this blog, I have created an S3 bucket in the region US East (North Virginia) called secureftpfolder)
  3. Use the JSON below to create an AWS Identity and Access Management (IAM) policy called secureftp-policy. This policy will allow access to the newly created S3 bucket (change the Amazon S3 bucket arn in the JSON to your own Amazon S3 bucket’s arn)
  4. {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Sid": "SecureFTPPolicyBucketAccess",
                "Effect": "Allow",
                "Action": "s3:ListBucket",
                "Resource": [
                    "arn:aws:s3:::secureftpfolder"
                ]
            },
            {
                "Sid": "SecureFTPPolicyObjectAccess",
                "Effect": "Allow",
                "Action": "s3:*",
                "Resource": [
                    "arn:aws:s3:::secureftpfolder/*"
                ]
            }
        ]
    }

    4. Create an AWS IAM group called secureftp-users and attach the policy created above (secureftp-policy) to it.

  5. Create AWS IAM Users with Programmatic access and add them to the AWS IAM group secureftp-users. Note down the access key and secret access key for the user accounts as these will have to be provided to the users.

Thats all that needs to be configured on the AWS side. Simple isn’t it? Now lets move on to the client configuration.

Client Configuration

In this section, we will configure CloudBerry Explorer on a computer, using one of the usernames created above.

  1. On your computer, download CloudBerry Explorer for Amazon S3 from https://www.cloudberrylab.com/explorer/amazon-s3.aspx. Note down the access key that is provided during the download as this will be required when you install it.
  2. Open the downloaded file to install it, and choose the free version when you are provided a choice between the free version and the trial for the pro version.
  3. After installation has completed, open CloudBerry Explorer.
  4. Click on File from the top menu and then choose New Amazon S3 Account.
  5. Provide a meaningful name for the Display Name (you can set this to the username that will be used)
  6. Enter the Access key and Secret key for the user that was created for you in AWS.
  7. Ensure Use SSL is ticked and then click on Advanced and change the Primary region to the region where you created the Amazon S3 bucket.
  8. Click OK  to close the Advanced screen and return to the previous screen.
  9. Click on Test Connection to verify that the entered settings are correct and that you can access the AWS Account using the the access key and secret access key.
  10. Once the settings have been verified, return to the main screen for CloudBerry Explorer. The main screen is divided into two panes, left and right. For our purposes, we will use the left-hand side pane to pick files in our local computer and the right-hand side pane to correspond to the Amazon S3 bucket.
  11. In the right-hand side pane, click on Source and from the drop down, select the name you gave the account that was created in step 4 above.
  12. Next, in the right-hand side pane, click on the green icon that corresponds to External bucket. In the window that comes up, for Bucket or path to folder/subfolder enter the name of the Amazon S3 bucket you had created in AWS (I had created secureftpfolder) and then click OK.
  13. You will now be returned to the main screen, and the Amazon S3 bucket will now be visible in the right-hand side pane. Double click on the Amazon S3 bucket name to open it. Viola! You have successfully created a connection to the Amazon S3 bucket.
  14. To copy files/folders from your local computer to the Amazon S3 bucket, select the file/folder in the left-hand pane and then drag and drop it to the right-hand pane.
  15. To copy files/folders from the Amazon S3 bucket to your local computer, drag and drop the files/folder from the right-hand pane to the appropriate folder in the left-hand pane.

 

So, tell me honestly, was that easy or what?

Just to ensure I have covered all bases (for now), here are few questions I would like to answer

A. Is the transfer of files between the local computer and Amazon S3 bucket secure?

Yes, it is secure. This is due to the Use SSL setting that we saw when configuring the account within CloudBerry Explorer.

B. Can I protect subfolders within the Amazon S3 bucket, so that different users have different access to the subfolders?

Yes, you can. You will have to modify the AWS IAM policy to do this.

C. Instead of a GUI client, can I access the Amazon S3 bucket via a script?

Yes, you can. You can download AWS tools to access the Amazon S3 bucket using the command line interface or PowerShell. AWS tools are available from https://aws.amazon.com/tools/

I hope the above comes in handy to anyone thinking of moving their secure ftp (or normal ftp) servers to a serverless architecture.