Terraform: Conditional Deploy
Description:
So far, HCL has been an easy language to learn as you mostly just look at pointers and see what certain values are. I would say the hardest time I have had since starting is learning the count and for_each to deploying multiple reosurces and how to use them. In this post I will show how count is commonly not only used to deploy a group of resources, but conditionally deploy a resource based on any expression.
Note: You can see the code for this post on my Github repo.
To Resolve
-
First, take a look at main and notice the
count. See how ifvar.regionissouthcentralusthe count will equal1and if false, it will equal0? That means that if I pass that value to that var it will deploy the resource and if I pass any other value it won’t.- If I were to run this as is it will create the Resource Group because
regionis set tosouthcentralusby default invariables.tf. You have to pass in a different value if you don’t want it be that value, that is how thedefaultblock works with variables.
- If I were to run this as is it will create the Resource Group because
-
In an example where the condition will equal
0and NOT deploy the resource, we simply pass any other value to variableregionand let the condition fail the check (since it will only deploy is region issouthcentraluswhich is the default:- For example, if I set region to
eastusat line 50 here and run an apply, it will delete the Resource Group previously deployed because the count would now be0instead of1. - Also take note that both
module azure_learning_rgandresource azurerm_management_lockboth have to make that same reference. This is because you can’t tie a lock to a resource that doesn’t exist silly :)
- For example, if I set region to
-
See here for many examples of conditional deploys.
-
This is a common and core concept of Terraform so practice this alot because it is something you will be wanting to do often. I will try to come up with more posts with examples of this and link back to this one in the future.
-
Also, this can also be done with
for_eachwith dynamic blocks as mentioned in this post on a different blog.
Comments