{Lambda}チュートリアル: スケジュールされたイベントでの AWS Lambda の使用

https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/services-cloudwatchevents-tutorial.html


-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

aws --version

-- 1.2 jqインストール
sudo yum -y install jq

 

-- 2. IAMロール作成
vim role01.json

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

aws iam create-role \
--role-name role01 \
--assume-role-policy-document file://role01.json


-- 3. ポリシーをロールにアタッチ
aws iam attach-role-policy \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole \
--role-name role01

-- 4. Lambda関数作成

vim test.py

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

SITE = os.environ['site']  # URL of the site to check, stored in the site environment variable
EXPECTED = os.environ['expected']  # String expected to be on the page, stored in the expected environment variable


def validate(res):
    '''Return False to trigger the canary

    Currently this simply checks whether the EXPECTED string is present.
    However, you could modify this to perform any number of arbitrary
    checks on the contents of SITE.
    '''
    return EXPECTED in res


def lambda_handler(event, context):
    print('Checking {} at {}...'.format(SITE, event['time']))
    try:
        req = Request(SITE, headers={'User-Agent': 'AWS Lambda'})
        if not validate(str(urlopen(req).read())):
            raise Exception('Validation failed')
    except:
        print('Check failed!')
        raise
    else:
        print('Check passed!')
        return event['time']
    finally:
        print('Check complete at {}'.format(str(datetime.now())))


chmod 755 test.py
zip test.zip test.py

aws lambda create-function \
--function-name func01 \
--zip-file fileb://test.zip \
--handler test.lambda_handler \
--runtime python3.7 \
--role arn:aws:iam::999999999999:role/role01 \
--environment '{"Variables": {"site": "https://docs.aws.amazon.com/lambda/latest/dg/welcome.html","expected": "What is AWS Lambda?"}}'


aws lambda list-functions | grep func01

aws lambda get-function --function-name func01


-- 5. Lambda 関数をテストする

aws lambda invoke \
--function-name func01 \
--payload '{
  "id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c",
  "detail-type": "Scheduled Event",
  "source": "aws.events",
  "account": "123456789012",
  "time": "1970-01-01T00:00:00Z",
  "region": "us-east-1",
  "resources": [
    "arn:aws:events:us-east-1:123456789012:rule/ExampleRule"
  ],
  "detail": {}
}' \
response.txt \
--cli-binary-format raw-in-base64-out

cat response.txt

 


-- 6. ルールの作成

aws events put-rule \
--name rule01 \
--schedule-expression "rate(1 minute)" \
--state ENABLED \
--description rule01

 

aws events list-rules

aws events describe-rule --name rule01

-- 7. ターゲットの作成

aws events put-targets \
--rule rule01 \
--targets "Id"="1","Arn"="arn:aws:lambda:ap-northeast-1:999999999999:function:func01"

aws events list-targets-by-rule \
--rule rule01

 

-- 8. Lambda関数に権限を追加する

aws lambda add-permission \
--function-name func01 \
--statement-id events \
--action lambda:InvokeFunction \
--principal events.amazonaws.com \
--source-arn arn:aws:events:ap-northeast-1:999999999999:rule/rule01

aws lambda get-policy \
--function-name func01 | jq -r .Policy  | jq .


-- 9. SNSトピック作成

aws sns list-topics
aws sns list-subscriptions

aws sns create-topic --name topic01

aws sns subscribe \
--topic-arn arn:aws:sns:ap-northeast-1:999999999999:topic01 \
--protocol email \
--notification-endpoint hoge@example.com


-- 10. アラームの設定

aws cloudwatch put-metric-alarm \
--alarm-name alarm01 \
--alarm-description alarm01 \
--actions-enabled \
--alarm-actions "arn:aws:sns:ap-northeast-1:999999999999:topic01" \
--metric-name Errors \
--namespace AWS/Lambda \
--statistic Sum \
--dimensions "Name=FunctionName,Value=func01" \
--period 120 \
--evaluation-periods 1 \
--datapoints-to-alarm 1 \
--threshold 1.0 \
--comparison-operator GreaterThanOrEqualToThreshold \
--treat-missing-data missing


aws cloudwatch describe-alarms


-- 11. アラームのテスト

aws lambda update-function-configuration \
--function-name func01 \
--environment '{"Variables": {"site": "https://docs.aws.amazon.com/lambda/latest/dg/welcome.html","expected": "404"}}'


aws lambda get-function --function-name func01


-- 12. クリーンアップ

-- アラームの削除

aws cloudwatch describe-alarms


aws cloudwatch delete-alarms \
--alarm-names alarm01

 

-- SNSトピック削除

aws sns unsubscribe --subscription-arn arn:aws:sns:ap-northeast-1:999999999999:topic01:11111111-2222-3333-4444-555555555555
aws sns delete-topic --topic-arn arn:aws:sns:ap-northeast-1:999999999999:topic01

aws sns list-topics
aws sns list-subscriptions

-- ターゲットの削除
aws events list-targets-by-rule \
--rule rule01

aws events remove-targets \
--rule rule01 \
--ids 1


-- ルールの削除

aws events list-rules

aws events delete-rule \
--name rule01

 

-- Lambda関数の削除
aws lambda get-function --function-name func01
aws lambda delete-function --function-name func01


-- ロールの削除
aws iam list-roles | grep role01

aws iam detach-role-policy \
--role-name role01 \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

aws iam delete-role --role-name role01