Create a setting in terraform to send a message from AWS Lambda Python3.8 to Slack

[Personal memorandum] Simple setting to send a message from lambda to slack

Overview

Terraform settings

├── .terraform
│   ├── plugins
│   │   └── darwin_amd64
│   │       └── terraform-provider-aws_v2.48.0_x4
├── post-slack.tf
└── source_code
    └── post-slack
        └── main.py

post-slack.tf


data "archive_file" "post-slack" {
  type        = "zip"
  source_dir  = "./source_code/post-slack"
  output_path = "./source_code/post-slack.zip"
}
resource "aws_lambda_function" "post-slack" {
  filename         = "${data.archive_file.post-slack.output_path}"
  function_name    = "post-slack"
  role             = "arn:aws:iam::※※※※※※※※※※※※:role/service-role/lambda-basic-execution"
  handler          = "main.lambda_handler"
  source_code_hash = "${data.archive_file.post-slack.output_base64sha256}"
  runtime          = "python3.8"
  memory_size      = 128
  timeout          = 300
    environment {
    variables = {
      SLACK_CHANNEL = "#hogehoge"
      SLACK_TEXT = "Slack notification test"
      SLACK_USER_NAME = "Anonymous"
      SLACK_ICON_EMOJI = ":fearful:"
      SLACK_COLOR = "warning"
      SLACK_WEBHOOK_URL = "https://hooks.slack.com/services/※※※※※※※※※/※※※※※※※※※/※※※※※※※※※※※※※※※※※※※※※※※※"
    }
  }
}

lambda-basic-execution


data "aws_iam_policy_document" "lambda-assume-role-policy" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["lambda.amazonaws.com"]
    }
  }
}
resource "aws_iam_role" "role_lambda-basic-execution" {
  name               = "lambda-basic-execution"
  assume_role_policy = data.aws_iam_policy_document.lambda-assume-role-policy.json
  path               = "/service-role/"
}
resource "aws_iam_role_policy_attachment" "AWSLambdaBasicExecutionRole" {
  role       = aws_iam_role.role_lambda-basic-execution.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}

source_code/post-slack/main.py


import os
import json
from urllib.request import Request, urlopen

slackChannel = os.environ['SLACK_CHANNEL']
slackUserName = os.environ['SLACK_USER_NAME']
slackText = os.environ['SLACK_TEXT']
slackWebhookURL = os.environ['SLACK_WEBHOOK_URL']
slackIconEmoji = os.environ['SLACK_ICON_EMOJI']
slackColor = os.environ['SLACK_COLOR']

def lambda_handler(event, context):
    post_slack()

def post_slack():
    message = {
        'channel': slackChannel,
        'username': slackUserName,
        'text': slackText,
        'icon_emoji': slackIconEmoji,
        'attachments': [
            {
                "color": slackColor,
                "text": "what a day··"
            }
        ]
    }
    data = json.dumps(message).encode('utf-8')
    request = Request(slackWebhookURL, data)
    urlopen(request).read()

terraform plan

** If you get the following error when you run the terraform plan for the first time, **

$ terraform plan

Error: Could not satisfy plugin requirements

Plugin reinitialization required. Please run "terraform init".

Plugins are external binaries that Terraform uses to access and manipulate resources. The configuration provided requires plugins which can't be located, don't satisfy the version constraints, or are otherwise incompatible.

Terraform automatically discovers provider requirements from your configuration, including providers used in child modules. To see the requirements and constraints from each module, run "terraform providers".

Error: provider.archive: no suitable version installed version requirements: "(any version)" versions installed: none

** Run terraform init **

$ terraform init
Initializing the backend...

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "archive" (hashicorp/archive) 2.0.0...

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.archive: version = "~> 2.0"

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

** terraform-provider-aws_v2.48.0_x4 has been downloaded to the plugins directory **

├── .terraform
│   ├── plugins
│   │   └── darwin_amd64
│   │       ├── terraform-provider-archive_v2.0.0_x5
│   │       └── terraform-provider-aws_v2.48.0_x4

terraform apply

$ terraform apply

** Post-slack.zip will be created in the source_code directory after execution **

└── source_code
    ├── post-slack
    │   └── main.py
    └── post-slack.zip

Check in the AWS Management Console

** Lambda function "post-slack" settings **

image.png

** Test run **

Recommended Posts

Create a setting in terraform to send a message from AWS Lambda Python3.8 to Slack
Send a message from Python to Slack
Send a message from Slack to a Python server
Post a message from IBM Cloud Functions to Slack in Python
I want to send a message from Python to LINE Bot
Send a request from AWS Lambda to Amazon Elasticsearch Service
Tweet in Chama Slack Bot ~ How to make a Slack Bot using AWS Lambda ~
How to get a value from a parameter store in lambda (using python)
Edit Excel from Python to create a PivotTable
Send a message to LINE with Python (LINE Notify)
Sample to send slack notification with python lambda
[Python] Throw a message to the slack channel
Terraform configured to launch AWS Lambda from Amazon SQS
Create a plugin to run Python Doctest in Vim (2)
Create a plugin to run Python Doctest in Vim (1)
Create a Layer for AWS Lambda Python with Docker
Python script to create a JSON file from a CSV file
How to create a kubernetes pod from python code
Post from Python to Slack
Create a function in Python
Create a dictionary in Python
[Python] Scraping in AWS Lambda
Post to Slack in Python
How to install NPI + send a message to line with python
I tried to create API list.csv in Python from swagger.yaml
How to slice a block multiple array from a multiple array in Python
How to launch AWS Batch from a python client app
Create a tool to check scraping rules (robots.txt) in Python
A quick explanation from creating AWS Lambda Layers to linking
How to create an instance of a particular class from dict using __new__ () in python
I wrote a script to create a Twitter Bot development environment quickly with AWS Lambda + Python 2.7
Let's use AWS Lambda to create a mechanism to notify slack when the value monitored by CloudWatch is exceeded on Python
Create a DI Container in Python
Create folders from '01' to '12' with python
[Lambda] [Python] Post to Twitter from Lambda!
Write AWS Lambda function in Python
Create a binary file in Python
Create a Kubernetes Operator in Python
5 Ways to Create a Python Chatbot
Create a random string in Python
[Python] Create API to send Gmail
A story that I was addicted to calling Lambda from AWS Lambda.
Create an instance of a predefined class from a string in Python
Created a package to support AWS Lambda development in Go language
How to get a string from a command line argument in python
How to create a heatmap with an arbitrary domain in Python
[Python / AWS Lambda layers] I want to reuse only module in AWS Lambda Layers
From installing Ansible to building a Python environment in Vagrant's virtual environment
Slack --APIGateway --Lambda (Python) --How to make a RedShift interactive app
Various ways to create an array of numbers from 1 to 10 in Python.
[For Python] Quickly create an upload file to AWS Lambda Layer
How to create a serverless machine learning API with AWS Lambda
How to generate a new loggroup in CloudWatch using python within Lambda
How to create a clone from Github
Use print in a Python2 lambda expression
[AWS] Create a Python Lambda environment with CodeStar and do Hello World
How to send a visualization image of data created in Python to Typetalk
Create a simple GUI app in Python
Send email to multiple recipients in Python (Python 3)
Create a tool to automatically furigana with html using Mecab from Python3
Create a JSON object mapper in Python