I have two app
resources with some common attributes as shown below:
resource "app" "example1" {
name = "sample1"
domain = "test.com"
is_secure = true
address = "6th Street"
}
resource "app" "example2" {
name = "sample2"
domain = "test.com"
is_secure = true
address = "6th Street"
}
The domain
, is_secure
and address
attributes are the common in both the resources. Instead of repeating these attributes I would like to define them once in a common config and extend it for each resource.
I know that with the help of modules or variables we can pass shared values but my goal is to manage both the resources without repeating the common attributes. so I’m looking for a solution similar to inheritance in OOPs.
Something like this:
resource "app" "common_config" {
domain = "test.com"
is_secure = true
address = "6th Street"
}
# This is just to illustrate what I am trying to achieve
resource "app" "example1" extends "common_config" {
name = "sample1"
}
resource "app" "example2" extends "common_config" {
name = "sample2"
}
Is this feasible in Terraform or any other approach that avoids repeating the common attributes?
tujit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Terraform is a declarative DSL and not object-oriented. It is interpreted by Go which is also (strictly speaking by full feature set) not object-oriented (somewhat controversial statement). I also believe your specific pseudo-code pertains to syntax and functionality within the Java family which would be a different family of languages, and so you would have different expectations.
You would accomplish this functionality by defining distinct attributes in a Map or Set type (if only one attribute differs), and then iterating through the collection within the resource to assign unique values in the parameters:
variable "apps" {
type = set(string)
default = ["sample1", "sample2"]
}
resource "app" "common_config" {
for_each = var.apps
name = each.value
domain = "test.com"
is_secure = true
address = "6th Street"
}
More information can be found in the documentation.