'Terraform Create Multiple Resources Without Duplicate Resource Names
I'm trying to use Terraform to create a number of GitHub repositories. I have the following:
terraform {
required_providers {
github = {
source = "integrations/github"
version = "~> 4.0"
}
}
}
# Configure the GitHub Provider
provider "github" {
token = var.gitub_token
}
# Create the repo
resource "github_repository" "new_repo" {
name = var.repo_name
visibility = "public"
}
This worked perfectly the first time. The 2nd time I run it, with a different repo_name, though, rather than create a new repo, it's trying to modify the 1st one. That seems to be because of the new_repo resource name. I don't want to have to edit that every time though?
I just want a single .tf I can run whenever I want a new repo. How can I do that with multiple resource names?
Solution 1:[1]
This happens because you keep modify the same instance of github_repository.new_repo. If you really don't want to separate the projects into different folders, you could use workspaces, or use for_each or count where repo_name would be a list. For example:
terraform {
required_providers {
github = {
source = "integrations/github"
version = "~> 4.0"
}
}
}
variable "repo_name" {
default = ["name1", "name2", "name3"]
}
# Configure the GitHub Provider
provider "github" {
token = var.gitub_token
}
# Create the repo
resource "github_repository" "new_repo" {
for_each = toset(var.repo_name)
name = each.key
visibility = "public"
}
This way when ever you add new repo, or remove it, you have to update the var.repo_name.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marcin |
