Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a git repository as an AWS Lambda source within Terraform?

I'm working within Terraform to configure an AWS Lambda - and initially, I've had the JS file that is the entirety of the lambda function within my Terraform directory:

data "archive_file" "auth_requests" {
  type        = "zip"
  source_file = "${path.module}/auth_requests/index.js"
  output_path = "${path.module}/auth_requests.zip"
}

resource "aws_lambda_function" "auth_requests" {
  function_name    = "auth_requests"
  filename         = "${data.archive_file.auth_requests.output_path}"
  role             = "${aws_iam_role.auth_requests.arn}"
  handler          = "index.handler"
  source_code_hash = "${data.archive_file.auth_requests.output_base64sha256}"
  runtime          = "nodejs8.10"
}

However, it's clear that the Lambda function should get its own git repo, rather than living within our broader Terraform repo. Is there a way to use Terraform to source files from a git repo (and then brought into the generated archive)?

I could define the lambda's GitHub repo as a resource, but then what would be the next steps for getting it cloned/updated so the archive_file can refer to it? Or can a Terraform module be repurposed for something like this?

like image 621
pat Avatar asked Nov 07 '22 04:11

pat


1 Answers

Assuming you use a Github repository to store your JS function, you can make use of the Github Content API to download a zip of the repo using curl:

curl -L -o <output zip filename> https://<github repo url>/zipball/master

You can achieve this in Terraform using the External provider instead of the Archive provider:

data "external" "download_function" {
  program = ["curl", "-L", "-o", 
"${path.module}/auth_requests.zip", "${var.github_repo_url}"]
}

The downside is that you now have an external dependency (curl).

like image 89
moebius Avatar answered Nov 14 '22 02:11

moebius