If you set null to Terraform’s Optional attribute value, it will skip the process nicely.

Introduction
It’s been a long time since i wrote articles for personal reasons, i’ll try to be more active and share my tips with you .
When creating Terraform resources, there were cases where you wanted to skip or omit processing depending on the combination of settings while assigning values to Optional attributes.
In such a case, I was at a loss as to how to create a general-purpose module, so I will leave it on the blog.
Environmental config
$ terraform -v
Terraform v1.2.8
on linux_amd64
+ provider registry.terraform.io/hashicorp/aws v4.22.0
InvalidParameterCombination
What I encountered was aws_db_instance
the case of creating a resource that is an RDS DB instance.
modules/rds.tf
resource "aws_db_instance" "mysql" {
// ...
availability_zone = "eu-central-1"
multi_az = true
// ...
}
The following error will occur as it is.
Error creating DB Instance: InvalidParameterCombination: Requesting a specific availability zone is not valid for Multi-AZ instances.
If you enable Multi-AZ, specifying AZ will be disabled.
The CloudFormation documentation makes this clear.
AWS::RDS::DBInstance – AWS CloudFormation
MultiAZ
Specifies whether the database instance is a Multi-AZ DB instance deployment. You can’t set the AvailabilityZone parameter if the MultiAZ parameter is set to true.
multi_az
I want to ignore true
the specification when availability_zone
Workaround
You can omit it in Terraform null
by assigning it to the value of the Optional attribute.
defaults – Functions – Configuration Language | Terraform by HashiCorp
When you define an attribute as optional and the caller doesn’t provide an explicit value for it, Terraform will set the attribute to
null
to represent that it was omitted. If you want to use a placeholder value other thannull
when an attribute isn’t set, you can use thedefaults
function to concisely assign default values only where an attribute value was set tonull
.
When not to use Multi-AZ deployment
modules/rds.tf
resource "aws_db_instance" "mysql" {
// ...
availability_zone = "eu-central-1"
multi_az = false
// ...
}
For Multi-AZ deployment
modules/rds.tf
resource "aws_db_instance" "mysql" {
// ...
availability_zone = null
multi_az = true
// ...
}
If you want to write generically
modules/rds.tf
resource "aws_db_instance" "mysql" {
// ...
availability_zone = var.multi_az ? null : var.availability_zone
multi_az = var.multi_az
// ...
}
With this, you can specify the placement AZ of the DB instance in the case of single AZ, and avoid errors even when multi-AZ is enabled.
In conclusion
By using the example introduced this time, it seems possible to set the default value of the Optional variable to null and create a variable that does not require assignment if processing is not required.
I felt like i could get along well with Terraform’s null. I enjoy Terraform because it makes it easier to code the behavior I expect.