68
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TerraformでLambdaをデプロイするときの小技

Posted at

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.
68
33
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
68
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?