I'm using the Terraform GitHub provider to define GitHub repositories for an internal GitHub Enterprise instance (although the question isn't provider-specific).
The existing github_repository
resource works fine, but I'd like to be able to set non-standard defaults for some of its arguments, and easily group other arguments under a single new argument.
e.g.
github_repository
's private
value defaults to false
but I'd like to default to true
squash_merge_only
parameter which sets allow_squash_merge = true, allow_rebase_merge = false, allow_merge_commit = false
There are more cases but these illustrate the point. The intention is to make it simple for people to configure new repos correctly and to avoid having large amounts of config repeated across every repo.
I can achieve this by passing variables into a custom module, e.g. something along the lines of:
Foo/custom_repo/main.tf
:
resource "github_repository" "custom_repo" {
name = ${var.repo_name}
private = true
allow_squash_merge = true
allow_merge_commit = ${var.squash_merge_only ? false : true}
allow_rebase_merge = ${var.squash_merge_only ? false : true}
}
Foo/main.tf
:
provider "github" {
...
}
module "MyRepo_module" {
source = "./custom_repo"
repo_name = "MyRepo"
squash_merge_only = true
}
This is a bit rubbish though, as I have to add a variable for every other argument on github_repository
that people using the custom_repo
module might want to set (which is basically all of them - I'm not trying to restrict what people are allowed to do) - see name
and repo_name
on the example. This all then needs documenting separately, which is also a shame given that there are good docs for the existing provider.
Is there a better pattern for reusing existing resources like this but having some control over how arguments get passed to them?
We created an opinionated module (terraform 0.12+) for this at https://github.com/mineiros-io/terraform-github-repository
We set all the defaults to values we think fit best, but basically you can create a set of local defaults and reuse them when calling the module multiple times.
fun fact... your desired defaults are already the module's default right away, but to be clear how to set those explicitly here is an example (untested):
locals {
my_defaults = {
# actually already the modules default to create private repositories
private = true
# also the modules default already and
# all other strategies are disabled by default
allow_squash_merge = true
}
}
module "repository" {
source = "mineiros-io/repository/github"
version = "0.4.0"
name = "my_new_repository"
defaults = local.my_defaults
}
not all arguments are supported as defaults yet, buts most are: https://github.com/mineiros-io/terraform-github-repository#defaults-object-attributes