Create a periodical program with Ruby x AWS Lambda x CloudWatch Events

Configuration aimed at in this article

rubyLambdaClowdWach.png Launch Lambda triggered by CloudWatch Events and send a message to Slack.

スクリーンショット 2020-10-10 17.25.07.png

↑ It will be automatically executed regularly like this.

Target audience

--People who want to create a periodical execution program in Ruby --People who want to touch Lambda

specification

Language: Ruby 2.5 series Infrastructure: Lambda, ClowdWatch Events

See also: Creating a bot for your workspace (https://slack.com/intl/ja-jp/help/articles/115005265703-%E3%83%AF%E3%83%BC%E3%82% AF% E3% 82% B9% E3% 83% 9A% E3% 83% BC% E3% 82% B9% E3% 81% A7% E5% 88% A9% E7% 94% A8% E3% 81% 99% E3% 82% 8B% E3% 83% 9C% E3% 83% 83% E3% 83% 88% E3% 81% AE% E4% BD% 9C% E6% 88% 90)

Completed form

periodic-slack-bot-on-aws-lambda

Create a program

Create a program to send messages to Slack.

Create directory

$ mkdir periodic-slack-bot-on-aws-lambda
$ cd periodic-slack-bot-on-aws-lambda

Set Git

$ git init
$ touch .gitignore

:./.gitignore


.bundle
/vendor/bundle

Describe what you don't want to manage with Git.

Specify Ruby version

$ rbenv local 2.5.1 
# 2.5 series recommended

Install Gem

$ bundle init

Create a Gemfile with the ↑ command and edit it as follows.

./Gemfile


# frozen_string_literal: true

source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

ruby '2.5.1'

gem 'async-websocket'
gem 'slack-ruby-bot'

Then install the required Gem.

$ bundle install --path vendor/bundle

Create app.rb

$ touch app.rb

ruby:./app.rb


require 'slack-ruby-client'

Slack.configure do |conf|
  conf.token = ENV['SLACK_BOT_TOKEN']
end

def post_to_slack(event:, context:)
  client = Slack::Web::Client.new
  client.chat_postMessage(channel: ENV['SLACK_CHANNEL_NAME'], text: 'Test submission from AWS Lambda', as_user: true)
end

Deploy to Lambda

After creating the program, prepare to deploy it to Lambda.

Install AWS CLI

This time, we will deploy using a tool called "AWS CLI", so if you haven't installed it yet, install it.

$ brew install awscli

Create an IAM user

Create an IAM user for deployment. スクリーンショット 2020-09-21 22.11.08.png First, go to "IAM"-> "Policy"-> "Create Policy" and paste the following statement from the JSON tab. スクリーンショット 2020-09-21 22.13.26.png

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "apigateway:*",
                "cloudformation:*",
                "dynamodb:*",
                "events:*",
                "iam:*",
                "lambda:*",
                "logs:*",
                "route53:*",
                "s3:*"
             ],
            "Resource": [
                "*"
            ]
        }
    ]
}

See also: Minimal Deploy IAM Policy (https://rubyonjets.com/docs/extras/minimal-deploy-iam/)

スクリーンショット 2020-09-21 22.15.47.png Enter the policy name and description as appropriate, and click "Create Policy".

スクリーンショット 2020-09-21 22.17.27.png Next, go to "IAM"-> "User"-> "Create User", give it an appropriate name, check "Access by Program", and proceed to the next.

スクリーンショット 2020-09-21 22.17.47.png Select the "Minimal Deploy IAM Policy" created earlier from "Attach existing policy directly" and proceed to the next.

スクリーンショット 2020-09-21 22.17.59.png

(Tags are optional) A confirmation screen will be displayed at the end, so if there are no problems, click "Create User".

スクリーンショット 2020-09-21 22.18.13_censored.jpg Then, two "access key ID" and "secret access key" will be issued, so keep it in a safe place as you download the csv file or make a note of it.

AWS CLI settings

$ aws configure --profile lambda (any profile name is OK)

AWS Access Key ID #Access key ID created earlier
AWS Secret Access Key #The secret access key you created earlier
Default region name # ap-northeast-1 
Default output format # json 

When you type "aws configure" in the terminal, you will be asked various things interactively, so enter the necessary information for each.

Create function

スクリーンショット 2020-10-10 18.12.38.png

Open "AWS Lambda" from the AWS console screen and click "Create Function".

--Function name (arbitrary name) --Runtime (Ruby2.5)

To create a function. (Others are OK with default values or blanks)

スクリーンショット 2020-10-10 18.17.53.png

From "Edit environment variables"

Set environment variables for each.

スクリーンショット 2020-10-10 18.23.04.png

Changed the handler name from "Edit basic settings" to "app.post_to_slack (file name.method name)".

Deploy

Package the created program as a zip file.

$ zip -r function.zip app.rb vendor

Deploy using aws cli.

$ aws lambda update-function-code --function-name PeriodicSlackBotOnAwsLambda --zip-file fileb://function.zip --profile lambda

{
    "FunctionName": "PeriodicSlackBotOnAwsLambda",
    "FunctionArn": "arn:aws:lambda:ap-northeast-1:**************:function:PeriodicSlackBotOnAwsLambda",
    "Runtime": "ruby2.5",
    "Role": "arn:aws:iam::**************:role/service-role/PeriodicSlackBotOnAwsLambda-role-**************",
    "Handler": "app.post_to_slack",
    "CodeSize": 12941753,
    "Description": "",
    "Timeout": 3,
    "MemorySize": 128,
    "LastModified": "2020-10-09T21:08:11.888+0000",
    "CodeSha256": "**************/**************=",
    "Version": "$LATEST",
    "Environment": {
        "Variables": {
            "SLACK_CHANNEL_NAME": "#**************",
            "SLACK_BOT_TOKEN": "xoxb-**************-**************-**************"
        }
    },
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "RevisionId": "********-****-****-****-********",
    "State": "Active",
    "LastUpdateStatus": "Successful"
}

Test run

スクリーンショット 2020-10-10 18.34.15.png Create an appropriate test from "Test event settings". (Hash can be left blank)

スクリーンショット 2020-10-10 18.38.29.png Click "Test" and if the message is sent to the specified Slack channel, it is successful. スクリーンショット 2020-10-10 18.40.17.png

Schedule management with CloudWatch Events

Trigger settings

スクリーンショット 2020-10-10 18.43.36.png

Click "Add Trigger".

スクリーンショット 2020-10-10 18.47.40.png

--Trigger name: CloudWatch Events --Rule: Create a new rule --Rule name: test_30minutes (optional) --Rule description: Run once every 30 minutes (optional) --Rule type: Schedule expression --Schedule expression: cron (* / 30 * * *? *)

The explanation of how to write a cron expression is omitted this time. Reference: Try touching cron

スクリーンショット 2020-10-10 17.25.07.png Wait for the passage of time, and if it is executed regularly, it will be successful.

スクリーンショット 2020-10-10 18.54.50.png

If it doesn't work, the log should be output in the CloudWatch log group, so debug it appropriately.

Afterword

Thank you for your hard work! If you proceed according to the article and there is a part that does not work well, I would appreciate it if you could point it out in the comment orchid.

Recommended Posts

Create a periodical program with Ruby x AWS Lambda x CloudWatch Events
Create a SlackBot with AWS lambda & API Gateway in Java
Try running SlackBot made with Ruby x Sinatra on AWS Lambda
Notify Slack of AWS bills daily with Lambda for Ruby
Create a playground with Xcode 12
Create a fortune using Ruby
Build AWS Lambda with Quarkus
Create and integrate Slack App and AWS Lambda (for ruby) in 30 minutes
Install gem in Serverless Framework and AWS Lambda with Ruby environment
Create a Vue3 environment with Docker!
Ruby: I made a FizzBuzz program!
Create a Servlet program in Eclipse
Create exceptions with a fluid interface
Create a Maven project with a command
Make a typing game with ruby
[Ruby on Rails] Create a pie chart for each column with Chartkick
How to build a Ruby on Rails development environment with Docker (Rails 6.x)
Create a program to post to Slack with GO and make it a container
Create a LINEnews-style tech news summary app with Rails x LineBot! [Part 1]
Getting Started with Micronaut 2.x ~ Native Build and Deploy to AWS Lambda ~
How to build a Ruby on Rails development environment with Docker (Rails 5.x)