0
votes

I want to make a simple copy of file that is located in one module folder to another module folder, but it seems that terraform do not have such kind of resource. I tried to do this with null_resource, but interpreter looses all environment through execution. With local_file it also do not work properly. Can you advice how to do this?

Tried this, but "data" source is searching for file before apply and this failes:

data "local_file" "code" {
  filename = "${path.module}/code.zip"
  depends_on = [null_resource.build_package]
}

# copy package to module root directory
resource "local_file" "code" {
    content_base64  = data.local_file.code.content_base64
    filename        = "${path.root}/resources/code_elasticsearch_proxy.zip"
}

Also tried:

resource "null_resource" "code" {
  provisioner "local-exec" {
    command = "cp ./${path.module}/code.zip ./code_elasticsearch_proxy.zip"
    interpreter = ["bash"]
    environment = {
      PWD = path.root
    }
  }
}

But this one looses all environment and i could not have the full path to files

1

1 Answers

0
votes

Managing files on the local system is not an intended use-case for Terraform, so I'd encourage you to consider other potential solutions to this problem, but since Terraform is open system where you can write a provider for anything in principle there is a way to get a result like what you want, though it'll probably have some drawbacks compared to other options.

The solution I thought about when considering your problem was to use the local_file resource type from the hashicorp/local provider:

terraform {
  required_providers {
    local = {
      source = "hashicorp/local"
    }
  }
}

resource "local_file" {
  content_base64 = filebase64("${path.module}/code.zip")
  filename       = "${path.cwd}/code_elasticsearch_proxy.zip"
}

One drawback of this approach I can identify immediately is that it will cause Terraform to load the whole content of this file into memory and pass it as a string to the provider. If the file is large then this might be slow, use more RAM than you'd like, and it might even hit internal limits of Terraform's plugin mechanism which is designed for the more typical use-case of sending small data attributes rather than large file contents.

You didn't mention why it's important to create a copy of this file in a different location, but I'd strongly recommend considering alternative approaches where you can just pass the original location of the file to whatever subsystem is ultimately going to be reading it, rather than creating a copy. Both of these files are at different places in your local filesystem, so hopefully the system consuming this should be able to read directly from ${path.module}/code.zip just as it is able to read from ${path.cwd}/code_elasticsearch_proxy.zip.