1
votes

I have lambda invocation in our terraform-built environment:

data "aws_lambda_invocation" "this" {
  count = var.invocation == "true" ? 1 : 0
  function_name = aws_lambda_function.this.function_name
  input = <<JSON
{
  "Name": "Invocation"
}
JSON
}

The problem: the function is invoked not only during creation ("apply") but deletion ("destroy") too. How to invoke it during creation only? I thought about checking environment variables in the lambda (perhaps TF adds name of the process here or something like that) but I hope there's a better way.

1

1 Answers

2
votes
  • Worth checking if you can use the -var 'lambda_xxx=execute' option while running the terraform command to check if the lambda code needs to be executed or not terraform docs
  • Using that variable lambda_xxx passed in via the command line while executing the command, you can check in the terraform code whether you want to run the lambda code or not.
  • Below code creates a waf only if the count is 1
resource "aws_waf_rule" "wafrule" {
  depends_on  = ["aws_waf_ipset.ipset"]
  name        = "${var.environment}-WAFRule"
  metric_name = "${replace(var.environment, "-", "")}WAFRule"
  count = "${var.is_waf_enabled == "true" ? 1 : 0}"

  predicates {
    data_id = "${aws_waf_ipset.ipset.id}"
    negated = false
    type    = "IPMatch"
  }
}
  • Variable declared in variables.tf file
variable "is_waf_enabled" {
  type = "string"
  default = "false"
  description = "String value to indicate if WAF/API KEY is turned on or off (true/any_value)"
}
  • When you run the command any value other than true is considered false as we are just checking for string true.
  • Similarly you can do this for your lambda.