I have searched the mailing list and the documentation for how to do this but couldn't find anything.
Here's my use case: I have a fairly simple architecture on AWS. Sometimes I want to test one-off things, such as whether the security group configuration is right.
To do that, I spin up two instances. Because I don't like clicking (and because those instances need to be set up in different parts of the VPC), I have defined those in a terraform .tf
file.
I would like those two instances to be spun up only when I explicitly require them. In other words, when I do terraform apply
, I don't want those instances to be created.
Here are a couple things I tried:
- Put them in a
temp
subdirectory, and execute only this file (e.g. withterraform plan -out=disposable.plan -target=temp/disposable.tf
). Problem: it does not detect any change ("No changes. Infrastructure is up-to-date."). - I had tried something else with a subdir (don't remember exactly why), and terraform complained about undefined variables and resources. Problem: I need access to the variables and resources I define in the main directory (e.g. the subnet ids, security groups, etc.)
- I tried also applying the file directly (not sure if that should work) with
terraform apply temp/disposable.tf
. Problem: it complains about the file not being valid with "not a valid plan file" (the file is indeed valid). - Rename the file to something else, e.g.
.tf.temp
, and rename it to.tf
when I need the resource. This works fine, but then you have to remember not to commit this change. I would prefer something that can be done on the command line (e.g. running a single.tf
file).
Best Answer
This is achievable using count and a conditional:
Set up a variable with a default value of
false
invariables.tf
:Use this when defining your instances by setting the count property with a conditional like this:
Since the variable is
false
by default it will set the count to 0 and not create the instance. You can then optionally set it up by setting this variable to true during anapply
:Using the above conditional, this will now be true, therefore setting the count to 1.