Launch EC2 instances from Slack - AWS Chatbot
Tags: launchec2fromslack, awschatbot, slackandawschatbot
Published: 2020-10-18 14:30:37

Few days back I had this thought in my mind that it will be so cool if I can do some small AWS operations from the chat window rather than having to log into any of my instance or AWS console. Thus, I came across this AWS service called [AWS Chatbot](https://docs.aws.amazon.com/chatbot/latest/adminguide/what-is.html) which can integrate with Slack and you can then use AWS commands on slack to trigger the API calls on AWS. Through this post, I would like to, if you have not already known, introduce how you can use AWS Chatbot for a very simple operation to launch an EC2 instance. To achieve this, I have created a lambda function which will then be executed from Slack and it is a very simple python code just to show you how you would be launching an instance from Slack. You can make modifications/additions to this code or even write a totally different code that satisfies your use case and then run it in slack as explained below. 

I will list the steps below to integrate slack and use the lambda function to trigger launch of EC2 instance:

**A. Configure Slack as a client in AWS Chatbot**
This is a pretty straightforward process and AWS Documentation to [Setup Chat Clients](https://docs.aws.amazon.com/chatbot/latest/adminguide/getting-started.html#chat-client-setup) covers it completely so I will not be providing the steps explicitly here. 

> Note: 
> a. In step 9 while defining IAM permissions, please ensure to add these permissions in the **Policy Templates" which includes - **Read-only command permissions, Lambda-invoke command permissions, Notification permissions** otherwise the invocation of lambda from Slack will not work.


> b. You can choose not to configure SNS as we do not require it at the moment. SNS topic is useful if you want to send alerts in Slack channel like if you would like to be notified if a new EC2 instance is launched or if S3 bucket has some activity and all this can be done using the cloudwatch events and SNS but that is a topic for another day.

**B. Lambda function to launch a new instance**
Below is a simple code in python for the lambda function and you can modify it according to your use case. In this function, I have purposely kept 2 attributes to be entered at runtime and the reason is that I wanted to show you how you will be adding input values while invoking the lambda function from slack. You can create a new lambda function with python 2.7 as runtime and copy the code into the section **Function Code**

```
import boto3

#Ami = 'ami-0f96495a064477ffb' ### Commented out to use them as inputs while executing the lambda function and you can remove this line
#InstanceType = 't2.micro'     ### Commented out to use them as inputs while executing the lambda function and you can remove this line
KeyName = 'xxxxxxx'            ### SSH Key name you have created earlier or create a new SSH keypair in EC2 console and use it here
SubnetId = 'subnet-xxxxxxx'    ### Input the subnet of your VPC where you want to launch the instance
Region = 'ap-southeast-2'      ### Input the subnet of your VPC where you want to launch the instance

ec2 = boto3.client('ec2', region_name=Region)

def lambda_handler(event, context):

    instance = ec2.run_instances(
        ImageId=event['Ami'],
        InstanceType=event['InstanceType'],
        KeyName=KeyName,
        SubnetId=SubnetId,
        MaxCount=1,
        MinCount=1
    )

    instance_id = instance['Instances'][0]['InstanceId']
    print instance_id
    return instance_id
```

**C. Add AWS Chatbot on Slack**
To run any commands on Slack, you will have to add AWS Chatbot app in your channel and you can follow the steps in Slack documentation to [add an app](https://slack.com/intl/en-au/help/articles/202035138-Add-an-app-to-your-workspace#add-an-app).

**D. Invoke Lambda through Slack**
The last step is to invoke the lambda through Slack and the command which can help you to do this is shown below:

```
@aws  invoke StartEC2Instance --region ap-southeast-2 --payload {"AMI": "ami-0f96495a064477ffb", "INSTANCE_TYPE": "t2.micro"}
```

The above command will first ask you to confirm if the AWS chatbot can run this command, so you will have to press either **yes or no** and then AWS Chatbot will run the command and show the output as something like this which means the instance is launched successfully:

```
ExecutedVersion: $LATEST
Payload: \"i-xxxxxxxxx\"
StatusCode: 200
```

> An important point to note is that the required input values are passed to the lambda function by using the attribute --payload which accepts a JSON format for key value pairs and if you have to input multiple parameters, you can just use the "comma" as delimiter to separate different attributes as I have shown in the command above.

I hope the above will pave the way for you to enter the world of chatops and introduce you to a whole new way of automation especially when bots are so much in demand nowdays.

If you have any feedback on this article, please do let me know and I will be happy to incorporate them after review.