Launch Lambda triggered by CloudWatch Events and send a message to Slack.
↑ It will be automatically executed regularly like this.
--People who want to create a periodical execution program in Ruby --People who want to touch Lambda
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)
periodic-slack-bot-on-aws-lambda
Create a program to send messages to Slack.
$ mkdir periodic-slack-bot-on-aws-lambda
$ cd periodic-slack-bot-on-aws-lambda
$ git init
$ touch .gitignore
:./.gitignore
.bundle
/vendor/bundle
Describe what you don't want to manage with Git.
$ rbenv local 2.5.1
# 2.5 series recommended
$ 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
$ 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
After creating the program, prepare to deploy it to Lambda.
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 for deployment. First, go to "IAM"-> "Policy"-> "Create Policy" and paste the following statement from the JSON tab.
{
"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/)
Enter the policy name and description as appropriate, and click "Create Policy".
Next, go to "IAM"-> "User"-> "Create User", give it an appropriate name, check "Access by Program", and proceed to the next.
Select the "Minimal Deploy IAM Policy" created earlier from "Attach existing policy directly" and proceed to the next.
(Tags are optional) A confirmation screen will be displayed at the end, so if there are no problems, click "Create User".
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 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.
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)
From "Edit environment variables"
Set environment variables for each.
Changed the handler name from "Edit basic settings" to "app.post_to_slack (file name.method name)".
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"
}
Create an appropriate test from "Test event settings". (Hash can be left blank)
Click "Test" and if the message is sent to the specified Slack channel, it is successful.
Click "Add Trigger".
--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
Wait for the passage of time, and if it is executed regularly, it will be successful.
If it doesn't work, the log should be output in the CloudWatch log group, so debug it appropriately.
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