Chat Bot ( Lex ) For - Start Stop ( Ec2 )

Taissery SuhaibTaissery Suhaib
2 min read

NOTE : BOT AND INSTANCE SHOULD BE IN THE SAME REGION

CREATE A EC2:

< MAKE THE NECESSARY CHANGES TO THE BELOW CODE AS NEEDED >
---- LIKE INTENT NAME AND THE LOGIC TO START AND STOP EC2---

LAMBDA CODE :

-- run time : python 3:11

import boto3
import logging
import os
import time

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

def lambda_handler(event, context):
    os.environ['TZ'] = 'Asia/Kolkata'
    time.tzset()
    logger.debug('Received event: %s', event)
    return dispatch(event)

def dispatch(intent_request):
    intent_name = intent_request['sessionState']['intent']['name']

    if intent_name == 'stopinstance':
        return stop_ec2(intent_request)
    elif intent_name == 'start-Server':
        return start_ec2(intent_request)

    raise Exception('Intent with name ' + intent_name + ' not supported')

def stop_ec2(intent_request):
    output_session_attributes = {}
    slots = intent_request['sessionState']['intent']['slots']
    instance_value = slots['instance']['value']['interpretedValue']

    ec2 = boto3.client('ec2', region_name='us-east-1')
    response = ec2.describe_instances()

    insId = []
    instance_found = False

    for reservation in response["Reservations"]:
        for instance in reservation["Instances"]:
            for tag in instance.get("Tags", []):
                if tag["Value"] == instance_value:
                    insId.append(instance["InstanceId"])
                    instance_found = True
                    break
            if instance_found:
                break

    if instance_found:
        ec2.stop_instances(InstanceIds=insId)
        message = {
            'contentType': 'PlainText',
            'content': 'Stopping instance {} successfully'.format(instance_value)
        }
        return close(output_session_attributes, 'Fulfilled', message)
    else:
        message = {
            'contentType': 'PlainText',
            'content': 'Instance {} not found.'.format(instance_value)
        }
        return close(output_session_attributes, 'Fulfilled', message)


def start_ec2(intent_request):
    output_session_attributes = {}
    slots = intent_request['sessionState']['intent']['slots']
    long_instance_value = slots['instance']['value']
    instance_value = long_instance_value['originalValue']
    region_name = 'us-east-1'  # Set your desired region

    ec2 = boto3.client('ec2', region_name=region_name)
    response = ec2.describe_instances()

    insId = []
    instance_found = False

    for reservation in response["Reservations"]:
        for instance in reservation["Instances"]:
            for tag in instance.get("Tags", []):
                if tag["Value"] == instance_value:
                    insId.append(instance["InstanceId"])
                    instance_found = True
                    break
            if instance_found:
                break

    if instance_found:
        ec2.start_instances(InstanceIds=insId)
        message = {
            'contentType': 'PlainText',
            'content': 'Starting instance {} successfully'.format(instance_value)
        }
    else:
        message = {
            'contentType': 'PlainText',
            'content': 'Instance {} not found.'.format(instance_value)
        }
    return close(output_session_attributes, 'Fulfilled', message)

def close(session_attributes, fulfillment_state, message):
    response = {
        'sessionAttributes': session_attributes,
        'dialogAction': {
            'type': 'Close',
            'fulfillmentState': fulfillment_state,
            'message': message
        }
    }
    return response

INSTALL APACHE 2 :

Install Apache 2 in one of the vm and change the HTML code with random code

CREATE A LOAD BALANCER

target group :

CREATING OF LEX BOT

Make an intent :

start the instance and stop the instance

____write a logic of conversation flow of BOT ___

STRUCTURE OF BOT AND INVOCATION OF LAMBDA

CHANGE THE UI OF BOT

kommunicate is the platform \==== Specfiy the AMAZON BOT and REGION IN WHICH BOT IS CREATED

FINAL TEST

_DO FOLLOW FOR MORE__

0
Subscribe to my newsletter

Read articles from Taissery Suhaib directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Taissery Suhaib
Taissery Suhaib