1
votes

I want to update a Lambda function Environment Variable after it is created in the same script.

I want to preserve the ARN, I would just like to update an environmental variable after it is created. In my situation, I had to setup the API Gateway configuration to get the URL, and I add that URL as an Environmental Variable. So, I need the lambda to setup the deployment, and I need the URL to go back into the integrated Lambda function.

Lambda->API Gateway-> (API Gateway URL)->Lambda Tada !

resource "aws_lambda_function" "lambda" {
  filename         = "${data.archive_file.zip.output_path}"
  source_code_hash = "${data.archive_file.zip.output_base64sha256}"
  function_name = "terraformLambdaWebsite"
  role          = "${aws_iam_role.role.arn}"
  handler       = "index.handler"
  runtime       = "nodejs10.x"
  tags = {
    Environment = "KeepQL"
  }
}

Then, after everything is setup, I want to change the Environment variable.

aws_lambda_function.lambda.tags.Environment = "KeepQL2"

I had hoped that Terraform was Smart enough to realize that it had already created that Lambda function, and since the Hash had not changed, it would just determine what was different and update that variable.

Much Thanks

1
If the lambda is called by the API Gateway, you can get the URL from the API Gateway integration. If it is proxy integration, then the lambda receives the Host header containing the URL, and if it is a custom integration, then you can get it from $context.domainName. This way, you don't need to pass it through environment variables. You could also get a custom domain for the API Gateway and pass the static domain name which is independent of the API Gateway deployment. I know these are not exactly solutions for your question, which is why they are a comment. - MadKarel

1 Answers

3
votes

At first, you are not updating lambda function ENV variables. ENV variables are in the code below example -

  resource "aws_lambda_function" "test_lambda" {
  filename      = "lambda_function_payload.zip"
  function_name = "lambda_function_name"
  role          = "${aws_iam_role.iam_for_lambda.arn}"
  handler       = "exports.test"
  source_code_hash = "${filebase64sha256("lambda_function_payload.zip")}"

  runtime = "nodejs12.x"

  environment {
    variables = {
      foo = "bar"
    }
  }
}

What you are doing is updating the tag variable, not ENV variable. Although if you change anything in lambda config, you need to redeploy lambda which will keep the ARN Same. Just the latest version will be updated. So make sure to refer arn of latest version of lambda.

Also in this flow Lambda->API Gateway-> (API Gateway URL)->Lambda. Is lambda same? If you really need to access the host(API-Gateway) link in lambda I think you need to handle or extract it from event.json Event->headers->host value, not from ENV variable. Check the event.json file at this link.

Thanks

Ashish