Terraform: Conditional Deploy

1 minute read

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

  1. First, take a look at main and notice the count. See how if var.region is southcentralus the count will equal 1 and if false, it will equal 0? 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.

    • This can be seen here where I pass the value by letting its default value inside variables.tf deploy it.
    • Notice it deletes my older RG and deploys the new one.
    • This is because region is set to southcentralus by default in variables.tf, you have to pass in a different value if you want it to not be that value. That is how the default block works with variables.
  2. In an example where the condition will equal 0 and NOT deploy the resource, we simply pass any other value to variable region and let the condition fail the check:
    • This can be seen here where it doesn’t deploy it because I set the region to eastus at line 50 here and instead deletes the Resource Group that was deployed from my previous run.
    • Also take note that both module azure_learning_rg and resource azurerm_management_lock both have to make that same reference? This is because you can’t tie a lock to a resource that doesn’t exist silly :)
  3. See here for many examples of conditional deploys.

  4. 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.

  5. Also, this can also be done with for_each with dynamic blocks as mentioned in this post on a different blog.