TerraformでLambdaをデプロイするとき、ローカルでzipファイルを作成しておくか、あらかじめS3にアップしておく必要があります。
resource "aws_lambda_function" "sample_function" {
filename = "lambda/upload/sample_function.zip"
function_name = "sample_function"
role = "${aws_iam_role.lambda_sample_function.arn}"
handler = "lambda_function.lambda_handler"
source_code_hash = "${base64sha256(file("lambda/sample_function/upload.zip"))}"
runtime = "python3.6"
memory_size = 128
timeout = 30
}
手動、もしくはなんらかのツールでzipを作成してもいいのですがArchive Provider
を使用すればTerraformがZIPファイルを作成してくれるようになります。
https://www.terraform.io/docs/providers/archive/d/archive_file.html
data "archive_file" "sample_function" {
type = "zip"
source_dir = "lambda/sample_function"
output_path = "lambda/upload/sample_function.zip"
}
resource "aws_lambda_function" "sample_function" {
filename = "${data.archive_file.sample_function.output_path}"
function_name = "sample_function"
role = "${aws_iam_role.lambda_sample_function.arn}"
handler = "lambda_function.lambda_handler"
source_code_hash = "${data.archive_file.sample_function.output_base64sha256}"
runtime = "python3.6"
memory_size = 128
timeout = 30
}
Lambdaのコードを変更してterraform plan
を実行するとzipが作成され差分が出るのでapply
でそのままデプロイできます。
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
~ update in-place
Terraform will perform the following actions:
~ aws_lambda_function.sample_function
last_modified: "2018-04-13T06:00:00.000+0000" => <computed>
source_code_hash: "C2gsFZgweCbQ88wjZk9+TmH+Beo+/FDPTrkRIn8mEfg=" => "PCJ/UxjA1evwRUUwxD9OI5mXWXWEmfSShCKC8LcaDD/Ak="
Plan: 0 to add, 1 to change, 0 to destroy.