3
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

[JAWS-UG CLI] Lambda:#17 Lambda cloudwatch-alarm-to-slack (Python版)

Lambdaのブループリントのうちcloudwatch-alarm-to-slackを利用して、Lambda関数を作成してみます。

今回は、KMSを使わないこととします。

前提条件

Lambdaへの権限

Lambdaに対してフル権限があること。

AWS CLI

以下のバージョンで動作確認済

  • AWS CLI 1.10.49
コマンド
aws --version
結果(例)
      aws-cli/1.10.49 Python/2.7.11 Darwin/15.6.0 botocore/1.4.39

IAM Role

'lambdaBasicExecution'ロールが存在すること。

変数の設定
IAM_ROLE_NAME='lambdaBasicExecution'
コマンド
aws iam get-role \
         --role-name ${IAM_ROLE_NAME}
結果(例)

      {
          "Role": {
            "AssumeRolePolicyDocument": {
                "Version": "2012-10-17",
                "Statement": [
                    {
                        "Action": "sts:AssumeRole",
                        "Principal": {
                            "Service": "lambda.amazonaws.com"
                        },
                        "Effect": "Allow",
                        "Sid": ""
                    }
                ]
            },
            "RoleId": "AROAXXXXXXXXXXXXXXXXX",
            "CreateDate": "2015-10-26T01:55:54Z",
            "RoleName": "lambdaBasicExecution",
            "Path": "/",
            "Arn": "arn:aws:iam::XXXXXXXXXXXX:role/lambdaBasicExecution"
          }
      }

0. 準備

0.1. リージョンの決定

変数の設定
export AWS_DEFAULT_REGION='\ |AWS_DEFAULT_REGION|\ '

0.2. 変数の確認

プロファイルが想定のものになっていることを確認します。

変数の確認
aws configure list
結果(例)
            Name                    Value             Type    Location
            ----                    -----             ----    --------
         profile       lambdaFull-prjz-mbp13        env    AWS_DEFAULT_PROFILE
      access_key     ****************XXXX shared-credentials-file
      secret_key     ****************XXXX shared-credentials-file
          region        ap-northeast-1        env    AWS_DEFAULT_REGION

0.3. IAM RoleのARN取得

変数の設定
IAM_ROLE_NAME='lambdaBasicExecution'
コマンド
IAM_ROLE_ARN=$( \
        aws iam get-role \
          --role-name ${IAM_ROLE_NAME} \
          --query 'Role.Arn' \
          --output text \
) \
        && echo ${IAM_ROLE_ARN}
結果(例)
      arn:aws:iam::XXXXXXXXXXXX:role/lambdaBasicExecution

0.4. SLACKの設定

変数の設定
SLACK_HOOK_URL="hooks.slack.com/services/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"
SLACK_CHANNEL_NAME="#20160725"

1. 事前作業

1.1. Lambda関数名の決定

変数の設定
LAMBDA_FUNC_NAME="cloudwatch-alarm-to-slack-nokms-$( date '+%Y%m%d' )" \
        && echo ${LAMBDA_FUNC_NAME}

同名のLambda関数の不存在確認

コマンド
aws lambda get-function \
        --function-name ${LAMBDA_FUNC_NAME}
結果(例)
      A client error (ResourceNotFoundException) occurred when calling the GetFunction operation: Function not found: arn:aws:lambda:ap-northeast-1:XXXXXXXXXXXX:function:cloudwatch-alarm-to-slack-nokms-20160725

1.2. Lambda関数

変数の設定
FILE_LAMBDA_FUNC="${LAMBDA_FUNC_NAME}.py"
PY_FUNC_NAME='lambda_handler'
変数の確認
cat << ETX

          FILE_LAMBDA_FUNC:   ${FILE_LAMBDA_FUNC}
          PY_FUNC_NAME:       ${PY_FUNC_NAME}
          SLACK_HOOK_URL:     ${SLACK_HOOK_URL}
          SLACK_CHANNEL_NAME: ${SLACK_CHANNEL_NAME}

ETX
コマンド
cat << EOF > ${FILE_LAMBDA_FUNC}
from __future__ import print_function

import boto3
import json
import logging

from base64 import b64decode
from urllib2 import Request, urlopen, URLError, HTTPError


HOOK_URL = "https://${SLACK_HOOK_URL}"
#ENCRYPTED_HOOK_URL = '${ENCRYPTED_HOOK_URL}'
SLACK_CHANNEL = '${SLACK_CHANNEL_NAME}'

#HOOK_URL = "https://" + boto3.client('kms').decrypt(CiphertextBlob=b64decode(ENCRYPTED_HOOK_URL))['Plaintext']

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


def lambda_handler(event, context):
          logger.info("Event: " + str(event))
          message = json.loads(event['Records'][0]['Sns']['Message'])
          logger.info("Message: " + str(message))

          alarm_name = message['AlarmName']
          #old_state = message['OldStateValue']
          new_state = message['NewStateValue']
          reason = message['NewStateReason']

          slack_message = {
              'channel': SLACK_CHANNEL,
              'text': "%s state is now %s: %s" % (alarm_name, new_state, reason)
          }

          req = Request(HOOK_URL, json.dumps(slack_message))
          try:
              response = urlopen(req)
              response.read()
              logger.info("Message posted to %s", slack_message['channel'])
          except HTTPError as e:
              logger.error("Request failed: %d %s", e.code, e.reason)
          except URLError as e:
              logger.error("Server connection failed: %s", e.reason)
EOF

cat ${FILE_LAMBDA_FUNC}
コマンド
zip ${LAMBDA_FUNC_NAME}.zip ${FILE_LAMBDA_FUNC}
結果(例)
      adding: cloudwatch-alarm-to-slack-nokms-20160725.py (deflated 43%)

2. Lambda関数の作成

変数の設定
LAMBDA_FUNC_DESC='New function using blueprint cloudwatch-alarm-to-slack-python'
LAMBDA_RUNTIME='python2.7'
LAMBDA_HANDLER="${LAMBDA_FUNC_NAME}.${PY_FUNC_NAME}"
FILE_LAMBDA_ZIP="${LAMBDA_FUNC_NAME}.zip"
変数の確認
cat << ETX

        LAMBDA_FUNC_NAME:  ${LAMBDA_FUNC_NAME}
        LAMBDA_FUNC_DESC: "${LAMBDA_FUNC_DESC}"
        LAMBDA_RUNTIME:    ${LAMBDA_RUNTIME}
        FILE_LAMBDA_ZIP    ${FILE_LAMBDA_ZIP}
        IAM_ROLE_ARN:      ${IAM_ROLE_ARN}
        LAMBDA_HANDLER:    ${LAMBDA_HANDLER}

ETX
コマンド
aws lambda create-function \
        --function-name ${LAMBDA_FUNC_NAME} \
        --description "${LAMBDA_FUNC_DESC}" \
        --zip-file fileb://${FILE_LAMBDA_ZIP} \
        --runtime ${LAMBDA_RUNTIME} \
        --role ${IAM_ROLE_ARN} \
        --handler ${LAMBDA_HANDLER}
結果(例)

      {
        "CodeSha256": "WnGd6iPBS0rGCJor4zyuOaGBtzQ3I/OgHerXWqZzbL8=",
        "FunctionName": "cloudwatch-alarm-to-slack-nokms-20160725",
        "CodeSize": 350,
        "MemorySize": 128,
        "FunctionArn": "arn:aws:lambda:ap-northeast-1:XXXXXXXXXXXX:function:cloudwatch-alarm-to-slack-nokms-20160725",
        "Version": "$LATEST",
        "Role": "arn:aws:iam::XXXXXXXXXXXX:role/lambdaBasicExecution",
        "Timeout": 3,
        "LastModified": "2015-10-26T02:08:11.949+0000",
        "Handler": "cloudwatch-alarm-to-slack-nokms-20160725.lambda_handler",
        "Runtime": "python2.7",
        "Description": "New function using blueprint cloudwatch-alarm-to-slack-python"
      }
コマンド
aws lambda list-functions 
結果(例)

      {
          "Functions": [
            {
                "Version": "$LATEST",
                "CodeSha256": "WnGd6iPBS0rGCJor4zyuOaGBtzQ3I/OgHerXWqZzbL8=",
                "FunctionName": "cloudwatch-alarm-to-slack-nokms-20160725",
                "MemorySize": 128,
                "CodeSize": 350,
                "FunctionArn": "arn:aws:lambda:ap-northeast-1:XXXXXXXXXXXX:function:cloudwatch-alarm-to-slack-nokms-20160725",
                "Handler": "cloudwatch-alarm-to-slack-nokms-20160725.lambda_handler",
                "Role": "arn:aws:iam::XXXXXXXXXXXX:role/lambdaBasicExecution",
                "Timeout": 3,
                "LastModified": "7月 24, 2016T02:08:11.949+0000",
                "Runtime": "python2.7",
                "Description": "New function using blueprint cloudwatch-alarm-to-slack-python"
            }
          ]
      }
コマンド
aws lambda get-function \
        --function-name ${LAMBDA_FUNC_NAME}
結果(例)

      {
        "Code": {
          "RepositoryType": "S3",
          "Location": "https://awslambda-ap-ne-1-tasks.s3-ap-northeast-1.amazonaws.com/snapshots/XXXXXXXXXXXX/HelloWorld-2979ba79-b08f-495d-9ee6-46397c95ba13?x-amz-security-token=AQoDYXdzEDoa8AMR6t8h66eOXhN3%2Fx7XpuRxvf7pVn7IuWV4cEmwx0CtZT6yxCJ1%2BWmigYXqGoyQHuBYOWnxbhmwEcTg839qMuhSu1fk0fXpXf0oJOLkhKMudNqhdElyFQpzyT6Q8GDfhAsfbX9wvwCDTty4imxz7MczF%2FQl6tgvTYdip08ap5fAyrknZGV1%2B1Ggnp5w6JOjydYxuUsWwhoxoEWzi7SoVTmpRQQA91c4VW9lNotOAHACFxo6klzDPM8mxR9RJl66WxFugL0wQJyLUpmtjS9XoArD86sEWWiIccMpV2BQipTPQlzL%2F1Hoy%2BDF6QUxyPUihlDjPBoJTISTP8W1wxmzW%2BLbilAfFQRPY7CFjzR0k%2FA%2FIX5x9iyz52Pu1Q0ASTw1l%2Fq%2Fo3pRbvzWR79QS%2BpxXrwbYzoQHKiK62DSTsQo5tqKPsiDCYzrPxbq8lm7pNBPG%2FsxjePRWBVJeRl08WxEjSjoRRwBOPX5mz1BCUoUBPGG5tEENp87A%2FCdDgibFWM5DdYhwtaYPY7FTmi8DvqjQHL9jOmP8YuVteBTBcv8nFW6UbErPjwwn79FKG1u5M9HoTWUqUMBByz6D4tTRSEw6iJU7XdCujFnhnHe5V8imZ1KGI7fDWpciJhrhml0wnKPCK%2Fe9lK1P2kO7ldSWc7zn5hcIOD2tbEF&AWSAccessKeyId=ASIAJFVALOKV5SJVYPPA&Expires=1445825978&Signature=bvwu1Ny34LgTmZeOO3q4sn7x3Fg%3D"
        },
        "Configuration": {
          "Version": "$LATEST",
          "CodeSha256": "WnGd6iPBS0rGCJor4zyuOaGBtzQ3I/OgHerXWqZzbL8=",
          "FunctionName": "cloudwatch-alarm-to-slack-nokms-20160725",
          "MemorySize": 128,
          "CodeSize": 350,
          "FunctionArn": "arn:aws:lambda:ap-northeast-1:XXXXXXXXXXXX:function:cloudwatch-alarm-to-slack-nokms-20160725",
          "Handler": "cloudwatch-alarm-to-slack-nokms-20160725.lambda_handler",
          "Role": "arn:aws:iam::XXXXXXXXXXXX:role/lambdaBasicExecution",
          "Timeout": 3,
          "LastModified": "2015-10-26T02:08:11.949+0000",
          "Runtime": "python2.7",
          "Description": "New function using blueprint cloudwatch-alarm-to-slack-python"
        }
      }
コマンド
aws lambda get-function-configuration \
        --function-name ${LAMBDA_FUNC_NAME}
結果(例)

      {
        "CodeSha256": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=",
        "FunctionName": "cloudwatch-alarm-to-slack-nokms-20160725",
        "CodeSize": 350,
        "MemorySize": 128,
        "FunctionArn": "arn:aws:lambda:ap-northeast-1:XXXXXXXXXXXX:function:cloudwatch-alarm-to-slack-nokms-20160725",
        "Version": "$LATEST",
        "Role": "arn:aws:iam::XXXXXXXXXXXX:role/lambdaBasicExecution",
        "Timeout": 3,
        "LastModified": "2015-10-26T01:23:45.678+0000",
        "Handler": "cloudwatch-alarm-to-slack-nokms-20160725.lambda_handler",
        "Runtime": "nodejs",
        "Description": "New function using blueprint cloudwatch-alarm-to-slack-python"
      }

3. Lambda関数の動作確認

3.1. サンプルデータの作成

変数の設定
FILE_INPUT="${LAMBDA_FUNC_NAME}-data.json" \
          && echo ${FILE_INPUT}
サンプルデータ
cat << EOF > ${FILE_INPUT}
{
        "Records": [
          {
            "EventVersion": "1.0",
            "EventSubscriptionArn": "arn:aws:sns:EXAMPLE",
            "EventSource": "aws:sns",
            "Sns": {
              "SignatureVersion": "1",
              "Timestamp": "1970-01-01T00:00:00.000Z",
              "Signature": "EXAMPLE",
              "SigningCertUrl": "EXAMPLE",
              "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e",
              "Message": "{\"AlarmName\": \"testSlack\", \"NewStateValue\": \"NG\", \"NewStateReason\": \"test fot Slack\"}",
              "MessageAttributes": {
                "Test": {
                  "Type": "String",
                  "Value": "TestString"
                },
                "TestBinary": {
                  "Type": "Binary",
                  "Value": "TestBinary"
                }
              },
              "Type": "Notification",
              "UnsubscribeUrl": "EXAMPLE",
              "TopicArn": "arn:aws:sns:EXAMPLE",
              "Subject": "TestInvoke"
            }
          }
        ]
}
EOF

cat ${FILE_INPUT}

JSONファイルを作成したら、フォーマットが壊れてないか必ず確認します。

コマンド
jsonlint -q ${FILE_INPUT}

エラーが出力されなければOKです。

3.2. lambda関数の手動実行

変数の設定
FILE_OUTPUT_LAMBDA="${LAMBDA_FUNC_NAME}-out.txt"
FILE_LOG_LAMBDA="${LAMBDA_FUNC_NAME}-$(date +%Y%m%d%H%M%S).log"
変数の確認
cat << ETX

        LAMBDA_FUNC_NAME:   ${LAMBDA_FUNC_NAME}
        FILE_INPUT:         ${FILE_INPUT}
        FILE_OUTPUT_LAMBDA: ${FILE_OUTPUT_LAMBDA}
        FILE_LOG_LAMBDA:    ${FILE_LOG_LAMBDA}

ETX
コマンド
aws lambda invoke \
        --function-name ${LAMBDA_FUNC_NAME} \
        --log-type Tail \
        --payload file://${FILE_INPUT} \
        ${FILE_OUTPUT_LAMBDA} \
        > ${FILE_LOG_LAMBDA}
コマンド
cat ${FILE_LOG_LAMBDA} \
        | jp.py 'StatusCode'
結果(例)
      200

3.3. lambda関数の実行結果の確認

コマンド
cat ${FILE_OUTPUT_LAMBDA}
結果(例)
      1970-01-01T00:00:00Z

3.4. lambda関数のログの確認

コマンド
cat ${FILE_LOG_LAMBDA} \
        | jp.py 'LogResult' \
        | sed 's/"//' \
        | base64 --decode

結果(例):

4. permissionの追加

Lambda実行権限の付与

変数の設定
LAMBDA_STAT_ID='AllowSNS'
LAMBDA_PERMIT_ACTION='lambda:InvokeFunction'
LAMBDA_PERMIT_PRINCIPAL='sns.amazonaws.com'
変数の確認
cat << ETX

        LAMBDA_FUNC_NAME:        ${LAMBDA_FUNC_NAME}
        LAMBDA_STAT_ID:         "${LAMBDA_STAT_ID}"
        LAMBDA_PERMIT_ACTION:    ${LAMBDA_PERMIT_ACTION}
        LAMBDA_PERMIT_PRINCIPAL: ${LAMBDA_PERMIT_PRINCIPAL}

ETX
コマンド
aws lambda add-permission \
        --function-name ${LAMBDA_FUNC_NAME} \
        --statement-id "${LAMBDA_STAT_ID}" \
        --action ${LAMBDA_PERMIT_ACTION} \
        --principal ${LAMBDA_PERMIT_PRINCIPAL}
結果(例)

      {
        "Statement": "{"Action":["lambda:InvokeFunction"],"Resource":"arn:aws:lambda:ap-northeast-1:xxxxxxxxxxxx:function:cloudwatch-alarm-to-slack-nokms-20160725","Effect":"Allow","Principal":{"Service":"sns.amazonaws.com"},"Sid":"AllowSNS"}"
      }

完了

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
3
Help us understand the problem. What are the problem?