Krishna
Krishna

Reputation: 621

How can I download git code by Terraform?

I am trying to checkout git repo code in Terraform and access a file (my_file.py) in it, I used below code,

module "my_git_repo" {
  source = "https://git.mycompany.org/my_repo.git"
}

output:

 "my_display" {
      value       = "${my_git_repo.source}/my_file.py"
    }

Error I get is, Error: Failed to download module downloading 'https://git.mycompany.org/my_repo.git': no source URL was returned

Note: I can checkout with "git clone" on command.

Upvotes: 6

Views: 8977

Answers (2)

Martin Atkins
Martin Atkins

Reputation: 74469

A module block in Terraform is for referring to a Terraform module, not to arbitrary code like Python files.

As Don mentioned, the correct syntax to tell Terraform to obtain a module using git from an HTTPS URL is to add the git:: prefix, overriding the default handling of HTTP URLs:

module "my_git_repo" {
  source = "git::https://git.mycompany.org/my_repo.git"
}

However, if you were to use this with a repository that doesn't contain any .tf files in the target directory then Terraform will complain that the source address doesn't refer to a valid Terraform module. To get something like what you described in your question you'd need to place at least a minimal Terraform module configuration in that directory too, such as the following outputs.tf file:

output "python_file" {
  value = "${path.module}/my_file.py"
}

Your calling module might then look like this, all together:

module "my_git_repo" {
  source = "git::https://git.mycompany.org/my_repo.git"
}

output "my_display" {
  value = module.my_git_repo.python_file
}

However, this is a very unusual thing to do with Terraform. You didn't mention what your underlying goal is here, but the way you've presented the question makes me suspect that you are trying to do use Terraform to solve a problem it isn't designed to solve. It may be worth asking a new question that is framed more around your underlying problem (why do you need this Python file from a remote git repository in your Terraform configuration), where those answering might be able to suggest other ways to solve that problem without forcing the remote repository to behave like a Terraform module.

Upvotes: 4

Don
Don

Reputation: 574

Change
source = "https://git.mycompany.org/my_repo.git"
to
source = "git::https://git.mycompany.org/my_repo.git"
to get the source code to download.

Upvotes: 1

Related Questions