Programmatically spin up an Amazon Connect Instance with new APIs.

What is Amazon Connect?

Amazon Connect is an omnichannel cloud contact center. Omnichannel contact centers offer customers the same experience across all channels (phone, chat, email, text (SMS), and social media) providing customer service agents a more straightforward interface and richer data set.

We can set up a contact center in a few steps, add agents from anywhere across the world, and start engaging with our customers.

With the power of the Amazon Connect Contact flows, and Integrations with 

  • Enterprise applications like Salesforce, 
  • Custom Lambda functions,
  • Azure Active Directory for user management,
  • Lex Bot, Amazon Polly, Amazon Transcribe, and 
  • Amazon Kinesis Streams for real-time sentiment analysis & agent metrics.

We can enhance the customer experiences with personalized greeting messages by validating the customer’s identity in the background. Agents, meanwhile, conveniently handle all customers from just one interface.

Amazon Connect Setup

At the time of writing this article, Amazon Connect is not on a list of Cloudformation supported services. To launch an Amazon Connect instance programmatically we are leveraging AWS SDK for Python (Boto3). Link to the code repository – https://github.com/avasisht/amazon-connect/tree/main/ac-base

Code Explanation and Usage

The Solution consists of

  • A wrapper Script – connect.sh, The purpose of a wrapper script is to
    • Conditionally pass the parameter values to the Cloudformation template, 
    • Create a S3 bucket to hold the lambda function code, 
    • Launch the Cloudformation template, and 
    • Invoke the Amazon Connect Lambda function.
    echo “Usage: bash connect.sh        “
    echo “Example: bash connect.sh  <SAML|CONNECT_MANAGED>   “
    • The Amazon Connect Lambda function,
    • The Amazon Connect Lambda IAM role, and
    • A SecretManager key for Amazon Connect admin user.
  • A lambda code – index.zip , the lambda function is provisioning
    • An Amazon Connect instance,
    • An Amazon Connect Admin User,
    • An S3 bucket, for storing CHAT_TRANSCRIPTS, CALL_RECORDINGS, SCHEDULED_REPORTS, and
    • Amazon Connect approved origin.

Decoding the Lambda Function

We are utilizing the power of Amazon Connect Boto3 SDK API for launching and configuring the Amazon Connect Instance.

Step 1 – Importing Python modules

				
					import uuid
import json
import time
import sys
import os
import json
# import boto3
from pip._internal import main
# These will hopefully not be required soon as the boto3 version at time of writing didn't include what I needed.
main(['install', '-I', '-q', 'boto3', '--target', '/tmp/', '--no-cache-dir', '--disable-pip-version-check'])
sys.path.insert(0,'/tmp/')

import boto3
from botocore.exceptions import ClientError
				
			

Step2 – Define the Lambda Handler , generate a random unique number used for S3 bucket naming, and create Amazon Connect Instance utilizing create_instance method. Store the Amazon Connect ARN and ID in a variable, we need it later.

				
					def lambda_handler(event, context):
    #generate a uuid
        print(boto3.__version__)
        uuId = str(uuid.uuid4())
        uuidSplit = uuId.split("-")[4]
        bucketName = os.environ['ConnectInstanceName'] + uuidSplit
        instanceAlias = os.environ['ConnectInstanceName']
        conClient = boto3.client('connect') #we will need to specify region on this
        smClient = boto3.client('secretsmanager')
        
        #create a connect instance
        conResponse = conClient.create_instance(
            ClientToken=uuId,
            IdentityManagementType=os.environ['Identity'],
            InstanceAlias=instanceAlias, #generates a random instance alias
            InboundCallsEnabled=True,
            OutboundCallsEnabled=True
            )
            
        #get the arn and ID, we will need those later
        arn = conResponse['Arn']
        connectId = conResponse['Id']
    
        #Wait maybe? This would be better accomplished with a Step Function
        time.sleep(90)
				
			

Step 3 – Create an S3 bucket required for storing chat transcriptscall recording, and scheduled reports. And Associate storage to the Amazon Connect Instance by utilizing associate_instance_storage_config method.

				
					    # Create S3 Bucket
    s3Client = boto3.client('s3')
    s3response = s3Client.create_bucket(
        ACL='private',
        Bucket=bucketName,
        CreateBucketConfiguration={
            'LocationConstraint': 'ap-southeast-2'
    },
    ObjectLockEnabledForBucket=False
    )

    # get the ARN of AWS issued KMS Key for Connect
    kmsClient = boto3.client('kms')
    kmsResponse = kmsClient.describe_key(
        KeyId='alias/aws/connect'
        )

    print(kmsResponse)
    kmsKeyId = kmsResponse['KeyMetadata']['Arn']
    time.sleep(15)
    
    # Associate Storage, these must be done one at a time
    conStorageResponse = conClient.associate_instance_storage_config(
        InstanceId=connectId,
        ResourceType='CHAT_TRANSCRIPTS',
        StorageConfig={
            'StorageType': 'S3',
            'S3Config': {
                'BucketName': bucketName,
                'BucketPrefix': 'ChatTranscripts',
                'EncryptionConfig': {
                    'EncryptionType': 'KMS',
                    'KeyId': kmsKeyId
                },
            }, 
        }
    )
    conStorageResponse = conClient.associate_instance_storage_config(
        InstanceId=connectId,
        ResourceType='CALL_RECORDINGS',
        StorageConfig={
            'StorageType': 'S3',
            'S3Config': {
                'BucketName': bucketName,
                'BucketPrefix': 'CallRecordings',
                'EncryptionConfig': {
                    'EncryptionType': 'KMS',
                    'KeyId': kmsKeyId
                },
            },
        }
    )
    conStorageResponse = conClient.associate_instance_storage_config(
        InstanceId=connectId,
        ResourceType='SCHEDULED_REPORTS',
        StorageConfig={
            'AssociationId': 'string',
            'StorageType': 'S3',
            'S3Config': {
                'BucketName': bucketName,
                'BucketPrefix': 'Reports',
                'EncryptionConfig': {
                    'EncryptionType': 'KMS',
                    'KeyId': kmsKeyId
                },
            },
        }
    )
				
			

Step 4 – To allow integration with third party services like salesforce, we need to add the domain to the Approved Origin list. To add the origin programmatically we are utilizing associate_approved_origin Amazon connect boto3 SDK API method.

				
					    conAddOrigin = conClient.associate_approved_origin(
        InstanceId=connectId,
        Origin= os.environ['Origin1']
    )
				
			

Validation

To validate your deployment, check the

  • Cloudformation stack status.

 

  • Amazon Connect Lambda function Cloudwatch logs.

  • Amazon Connect Instance status, and 

  • Finally, access the connect instance URL with the “connectadmin” user (grab the password from the AWS Secret Manager).

Conclusion

In this post, I shared

  • How to deploy an Amazon Connect Instance using Python Boto3 AWS SDK,
  • How to create and map S3 Bucket to the Amazon Connect instance for call recordings, call transcripts, and scheduled reports storage. 
  • One GitHub repository – to clone and deploy the code to realize the full benefits of this solution first hand.
(Visited 105 times, 1 visits today)