DEV Community

William Collins for AWS Community Builders

Posted on • Originally published at

The Best Terraform Feature Yet?

Optional attributes for object type constraints is almost here! I've been waiting for this feature to come along for a while. I have tested it extensively in -alpha, and I can confidently confirm that it is a game changer. This feature is long in the making, being discussed as far back as this thread in 2018. Today, it is now in beta, so the official release could be any day now. Let's demonstrate how this is useful and build some common AWS infrastructure.

Why it is Useful

Before this feature, you could resort to using tricks to make arguments in object variables optional. This usually included providing a null value for optional parameters and then doing some fancy lookup or conditional like so:

Now, we can make that individual attribute optional without any hackery involved. The first thing to know here is that when setting optional(string) without a default value as shown below, the default value is null.

While having the default value automatically set to null is helpful, it only solves half of the problem. What happens if we have a scenario where we still want to provide a value in the logic, even if one isn't supplied at runtime? Then we can set a default value with a second argument like this:

Building some Infrastructure in AWS

This feature comes in handy when building complex data types. Let's look at something as simple as building an AWS VPC. Your organization could be using VPC IPAM but may still need the option to pass in custom CIDRs at runtime. Or, other standard defaults may need to be set if not provided at runtime. Take the following example:

If only the cidr_block attribute is provided at runtime, then the IPAM attributes will be nullified. This simplifies our resource configuration as follows:

Test it Yourself!

Want to start testing? Grab v1.3.0-beta1 and setup your like this:


AWS VPC is a simple example. This feature really shines when building reusable infrastructure-as-code for Network Firewall or even Network ACLs. Anything that simplifies something and reduces or eliminates any hacks required to reach a logical outcome is super valuable. Great work finally driving this one home HashiCorp.

Top comments (0)