[JAWS-UG CLI] Lambda:#6 Lambda関数の変更

前提条件
========


Lambdaへの権限
--------------

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


AWS CLI
-------

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

* AWS CLI 1.9.0

```bash:コマンド:
aws --version
```

```text:結果(例):
      aws-cli/1.9.0 Python/2.7.5 Darwin/13.4.0 botocore/1.3.0
```


0. 準備
=======


変数の確認
----------

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

```bash:変数の確認:
aws configure list
```

```text:結果(例):
            Name                    Value             Type    Location
            ----                    -----             ----    --------
         profile       administrator-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
```

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


1. 事前作業
===========


1.1. Lambda関数名の決定
-----------------------

```bash:コマンド:
aws lambda list-functions \
        --query 'Functions[].FunctionName'
```

```json:結果(例):
      [
        "HelloWorld"
      ]
```

```bash:変数の設定:
LAMBDA_FUNC_NAME='HelloWorld'
```


1.2. Lambda関数
---------------

```bash:変数の設定:
FILE_LAMBDA_FUNC="${LAMBDA_FUNC_NAME}.js"
```

```bash:変数の確認:
cat << ETX

        FILE_LAMBDA_FUNC: ${FILE_LAMBDA_FUNC}

ETX
```

```bash:コマンド:
cat << EOF > ${FILE_LAMBDA_FUNC}
console.log('Loading function');

exports.handler = function(event, context) {
        console.log('value1 =', event.key2);
        console.log('value2 =', event.key3);
        console.log('value3 =', event.key1);
        context.succeed(event.key2);  // Echo back the first key value
        // context.fail('Something went wrong');
};
EOF

cat ${FILE_LAMBDA_FUNC}
```

```bash:コマンド:
zip ${LAMBDA_FUNC_NAME}-new.zip ${FILE_LAMBDA_FUNC}
```

```text:結果:
      adding: HelloWorld.js (deflated 43%)
```


2. Lambda関数の更新
===================


2.1. Lambda関数の更新
---------------------

```bash:変数の設定:
FILE_LAMBDA_ZIP="${LAMBDA_FUNC_NAME}-new.zip"
```

```bash:変数の確認:
cat << ETX

        LAMBDA_FUNC_NAME:  ${LAMBDA_FUNC_NAME}
        FILE_LAMBDA_ZIP:   ${FILE_LAMBDA_ZIP}

ETX
```

```bash:コマンド:
aws lambda update-function-code \
        --function-name ${LAMBDA_FUNC_NAME} \
        --zip-file fileb://${FILE_LAMBDA_ZIP} \
        --publish
```

```json:結果(例):

      {
        "CodeSha256": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=",
        "FunctionName": "HelloWorld",
        "CodeSize": 349,
        "MemorySize": 128,
        "FunctionArn": "arn:aws:lambda:ap-northeast-1:XXXXXXXXXXXX:function:HelloWorld:2",
        "Version": "2",
        "Role": "arn:aws:iam::XXXXXXXXXXXX:role/lambdaBasicExecution",
        "Timeout": 2,
        "LastModified": "2015-10-26T01:23:45.678+0000",
        "Handler": "HelloWorld.handler",
        "Runtime": "nodejs",
        "Description": "Hello World with AWS Lambda function."
      }
```


2.2. Lambda関数の確認
---------------------

```bash:コマンド:
aws lambda get-function \
        --function-name ${LAMBDA_FUNC_NAME}
```

```json:結果(例):

      {
        "Code": {
          "RepositoryType": "S3",
          "Location": "https://awslambda-ap-ne-1-tasks.s3-ap-northeast-1.amazonaws.com/snapshots/XXXXXXXXXXXX/HelloWorld-38950242-86bb-4cbb-bab7-27dfdec7f362?x-amz-security-token=AQoDYXdzEDwa8AMILEth%2BKa19K9tePesujMLPz9zX2%2Fglxg9xU%2BPwvLP8ZMoogywweINkAhFta2lr88GEKJwk8x077DnoOmYeXmD2XE2bXbYPgNAFJU2JYgpnxckoXt2qrNAQKUpCtWqeCwHm34d%2FRhoVDXIbhHpn4iMkg%2BCFfU5%2BtjYsZQzp6CfcDUd3fZXYgSBjCJdpTIc222P6zcusHt%2FPc9ob016zlAkIuEi5ZZhXwZFouF7wwURvSo0QbZ1e1M2DwqNfL1bpC3oEPGrKM43XtwEvVSpMu%2FwdDQHBi1f8B7xJbmjNXA7zg%2BLybhUHioDdLPlS2NDgSXUO4QP3BMmTDeLN5Z6rx0ddjl1JJpLczIl6Plzln0NMQ14dkkIKriteFL09Ei0DJQ7Y%2BiXPNMStM66vsN%2F9yAHGNxCrFKEH0t9lgV2Od6%2Fny3MmNQiNSaaqCHsnKpLbabLSy82dsQwhW35XPCJPShwbgXPB9RPXjx%2FqBCnyGztXE7s6vsBy3AmJbctcDcgte2cpvcoEkg4H%2BrDTaBRvDYlqxEj71C3WLLI62z6OLS5fxkYmYfDZzhDQ5oLg5eyvXxlwugkvh%2Fo7pKuo%2B48liADEZDyLKHqFPH0j924OYRJrtr2b1iw4nrwyMAE7VnQBLAFfPWnWeiD3lfDKARvUpFeINW2trEF&AWSAccessKeyId=ASIAJDZ6MUQCOK4OEDVQ&Expires=1445835375&Signature=uzNTBfSjf1kwixwHBT5LsRtQowo%3D"
        },
        "Configuration": {
          "Version": "$LATEST",
          "CodeSha256": "+EAYs8jMYFRBdnsMdFUt2bv//KHE2tkovql6ls+gXoM=",
          "FunctionName": "HelloWorld",
          "MemorySize": 128,
          "CodeSize": 349,
          "FunctionArn": "arn:aws:lambda:ap-northeast-1:XXXXXXXXXXXX:function:HelloWorld",
          "Handler": "HelloWorld.handler",
          "Role": "arn:aws:iam::XXXXXXXXXXXX:role/lambdaBasicExecution",
          "Timeout": 3,
          "LastModified": "2015-10-26T04:41:36.261+0000",
          "Runtime": "nodejs",
          "Description": "\ |LAMBDA_FUNC_DESC|\ "
        }
      }
```


2.3. バージョン番号の取得
-------------------------

```bash:変数の設定:
LAMBDA_FUNC_VER=$( \
        hash=$( \
          aws lambda list-versions-by-function \
            --function-name ${LAMBDA_FUNC_NAME} \
            --query 'Versions[?Version == `$LATEST`].CodeSha256' \
            --output text \
        ) \
        && aws lambda list-versions-by-function \
          --function-name ${LAMBDA_FUNC_NAME} \
          --query "Versions[?CodeSha256 == \`${hash}\` && Version != \`\$LATEST\`].Version[]" \
          --output text \
      ) \
        && echo ${LAMBDA_FUNC_VER}
```

```text:結果(例)
2
```

3. Lambda関数の動作確認
=======================


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

```bash:変数の設定:
FILE_DATA_LAMBDA="${LAMBDA_FUNC_NAME}-data.json" \
        && echo ${FILE_DATA_LAMBDA}
```

```bash:サンプルデータ:
cat << EOF > ${FILE_DATA_LAMBDA}
{
          "key1": "val1",
          "key2": "val2",
          "key3": "val3"
}
EOF

cat ${FILE_DATA_LAMBDA}
```

```bash:コマンド:
jsonlint -q ${FILE_DATA_LAMBDA}
```

```bash:変数の設定:
FILE_OUTPUT_LAMBDA="${LAMBDA_FUNC_NAME}-out.txt" \
        && echo ${FILE_OUTPUT_LAMBDA}
```

```bash:変数の確認:
cat << ETX

        LAMBDA_FUNC_NAME:   ${LAMBDA_FUNC_NAME}
        FILE_DATA_LAMBDA:   ${FILE_DATA_LAMBDA}
        FILE_OUTPUT_LAMBDA: ${FILE_OUTPUT_LAMBDA}

ETX
```

```bash:コマンド:
FILE_LOG_LAMBDA="${LAMBDA_FUNC_NAME}-$(date +%Y%m%d%H%M%S).log" \
        && echo ${FILE_LOG_LAMBDA}
```

```bash:コマンド:
aws lambda invoke \
        --function-name ${LAMBDA_FUNC_NAME} \
        --log-type Tail \
        --payload file://${FILE_DATA_LAMBDA} \
        ${FILE_OUTPUT_LAMBDA} \
        > ${FILE_LOG_LAMBDA}
```

```bash:コマンド:
cat ${FILE_LOG_LAMBDA} \
  | jp.py 'StatusCode'
```

```text:結果(例):
      200
```

```bash:コマンド:
cat ${FILE_OUTPUT_LAMBDA}
```

```text:結果:
      val2
```

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

```text:結果:
      START RequestId: 1dc6ae3a-7b9d-11e5-a29a-b93d2ad7eab9 Version: $LATEST
      2015-10-26T04:50:45.532Z    1dc6ae3a-7b9d-11e5-a29a-b93d2ad7eab9    value1 = val2
      2015-10-26T04:50:45.532Z    1dc6ae3a-7b9d-11e5-a29a-b93d2ad7eab9    value2 = val3
      2015-10-26T04:50:45.532Z    1dc6ae3a-7b9d-11e5-a29a-b93d2ad7eab9    value3 = val1
      END RequestId: 1dc6ae3a-7b9d-11e5-a29a-b93d2ad7eab9
      REPORT RequestId: 1dc6ae3a-7b9d-11e5-a29a-b93d2ad7eab9      Duration: 6.34 ms       Billed Duration: 100 ms         Memory Size: 128 MB     Max Memory Used: 27 MB
```


4. エイリアスの更新
===================


4.1. エイリアスの確認
---------------------

```bash:変数の設定:
LAMBDA_ALIAS_NAME='product'
```

```bash:コマンド:
aws lambda get-alias \
        --function-name ${LAMBDA_FUNC_NAME} \
        --name ${LAMBDA_ALIAS_NAME}
```

```json:結果(例):
      {
        "AliasArn": "arn:aws:lambda:ap-northeast-1:XXXXXXXXXXXX:function:HelloWorld:product",
        "FunctionVersion": "1",
        "Name": "product",
        "Description": "Released version on product env."
      }
```


4.2. エイリアスの更新
---------------------

```bash:コマンド:
aws lambda update-alias \
        --function-name ${LAMBDA_FUNC_NAME} \
        --function-version ${LAMBDA_FUNC_VER} \
        --name ${LAMBDA_ALIAS_NAME}
```

```json:結果(例):
      {
        "AliasArn": "arn:aws:lambda:ap-northeast-1:XXXXXXXXXXXX:function:HelloWorld:product",
        "FunctionVersion": "2",
        "Name": "product",
        "Description": "Released version on product env."
      }
```


4.3. エイリアスの確認
---------------------

```bash:コマンド:
aws lambda get-alias \
        --function-name ${LAMBDA_FUNC_NAME} \
        --name ${LAMBDA_ALIAS_NAME}
```

```json:結果(例):
      {
        "AliasArn": "arn:aws:lambda:ap-northeast-1:XXXXXXXXXXXX:function:HelloWorld:product",
        "FunctionVersion": "2",
        "Name": "product",
        "Description": "Released version on product env."
      }
```


完了
====