Terraformで既存のLambdaを実行する

Terraformで既存のLambdaを実行する

新規ディレクトリでmain.tf作成します。

main.tf

resource "aws_lambda_invocation" "aaa" {
  function_name = "test-lambda"

  input = jsonencode({
    key1 = "value1"
    key2 = "value2"
  })
}

output "result_entry" {
  value = jsondecode(aws_lambda_invocation.aaa.result)
}

Lambda名はべた書きで「test-lambda」としています。既存のLambdaになります。

初期化し、適用します。

$ terraform init
$ terraform apply
...
...
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.

Enter a value: yes

aws_lambda_invocation.aaa: Creating...
aws_lambda_invocation.aaa: Creation complete after 1s [id=test-lambda_$LATEST_ff45cc3835165307ef414c23ca2c6f67]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Outputs:

result_entry = {
"body" = "\"Hello from Lambda!!!!\""
"statusCode" = 202
}

Lambdaの実行結果が返ってきています。

$ terraform output
result_entry = {
"body" = "\"Hello from Lambda!!!!\""
"statusCode" = 202
}

マネジメントコンソールからLambdaの修正を行う

This resource only invokes the function when the arguments call for a create or update. In other words, after an initial invocation on apply, if the arguments do not change, a subsequent apply does not invoke the function again. To dynamically invoke the function, see the triggers example below. To always invoke a function on each apply, see the aws_lambda_invocation data source.

Terraform Registry

この注意書きがある通り、マネジメントコンソールからLambdaの戻り値を修正して、terraform applyコマンドを実行しても戻り値はLambda修正前のままで変わりません。

引数を変更すれば再度Lambdaが呼ばれるようです。

main.tf

resource "aws_lambda_invocation" "aaa" {
  function_name = "test-lambda"

  input = jsonencode({
    key1 = "value"
  }) // intputを変更した
}

output "result_entry" {
  value = jsondecode(aws_lambda_invocation.aaa.result)
}

これで、terraform applyコマンドを実行します。

$ terraform output
result_entry = {
"body" = "\"Hello from Lambda\""
"statusCode" = 200
}

Lambdaが呼ばれたことが確認できました。

Terraformで既存のLambdaを実行する

コメント

タイトルとURLをコピーしました