https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/gettingstarted-images.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 docker インストール
sudo amazon-linux-extras install docker -y
sudo systemctl start docker
sudo systemctl enable docker
sudo systemctl status docker
sudo usermod -a -G docker ec2-user
ターミナルを再起動
id
{
"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. コンテナイメージを作成する
mkdir test
cd test
vim app.js
exports.handler = async (event) => {
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
vim Dockerfile
FROM public.ecr.aws/lambda/nodejs:14
# Copy function code
COPY app.js ${LAMBDA_TASK_ROOT}
# Set the CMD to your handler
CMD [ "app.handler" ]
docker build -t hello-world:v1 .
docker run -p 9000:8080 hello-world:v1
-- 別セッションから確認
docker container ls -a
curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{}'
docker container rm -f 461722a434f3
-- 5. Amazon ECR リポジトリへのイメージのアップロード
aws ecr get-login-password --region ap-northeast-1 | \
docker login --username AWS --password-stdin 999999999999.dkr.ecr.ap-northeast-1.amazonaws.com
aws ecr create-repository \
--repository-name ecr01 \
--image-scanning-configuration scanOnPush=false \
--image-tag-mutability IMMUTABLE
aws ecr describe-repositories
docker image tag hello-world:v1 999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/ecr01:v1
docker image ls -a
docker image push 999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/ecr01:v1
aws ecr list-images --repository-name ecr01
-- 6. コンテナイメージとして定義された Lambda 関数を作成する
aws lambda create-function \
--function-name func01 \
--package-type Image \
--code '{"ImageUri" : "999999999999.dkr.ecr.ap-northeast-1.amazonaws.com/ecr01:v1"}' \
--role arn:aws:iam::999999999999:role/role01
aws lambda get-function --function-name func01
-- 7. Lambda 関数の呼び出し
aws lambda invoke \
--function-name func01 \
--log-type Tail \
out
-- 8. クリーンアップ
-- 関数の削除
aws lambda list-functions |grep FunctionName
aws lambda delete-function --function-name func01
-- ECRリポジトリの削除
aws ecr describe-repositories
aws ecr delete-repository \
--repository-name ecr01 \
--force
-- ロールの削除
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