HiveBrain v1.2.0
Get Started
← Back to all entries
patternterraformCritical

Terraform: apply only one tf file

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
fileapplyoneonlyterraform

Problem

I have my security groups in a securitygroup.tf file.

In the same dir there are plenty of other resource descriptions (rds, ec2 etc).

Is there a way to perform a terraform apply --auto-approve only for my securitygroups.tf?

Solution

Not really. The standard way to work around this though is to use eg:

terraform apply -target=aws_security_group.my_sg


but that's only going to apply one security group at a time, so will get tedious if you have a lot of them. You can, however, target multiple resources in one command:

terraform apply -target=aws_security_group.my_sg -target=aws_security_group.my_2nd_sg


However, there are potentially a couple of workarounds:

-
The -target parameter respects dependencies.

This means if you were to eg. -target=aws_instance.my_server and that instance had, say, five security groups attached to it via interpolation, changes to those security groups should be included in the plan (I haven't thoroughly tested this, but I believe this is how it works).

That is a bit messy though, as you probably don't want to touch an instance. A safer alternative might be using something like a null_resource to provide a target for the security groups, but again I haven't tried this (there might be another 'safe' resource you could rely on, though?).

-
Create a module.

You can target a module just like you can target a plain resource (be sure to include the quotes around the target name):

terraform apply -target="module.my_security_groups"


Inside this module, you could define all of your security groups - just like you would have outside of the module. As well as being able to target it directly, this also makes it easier for you to re-use the same set of security groups for other infrastructure, if you ever need to.

Code Snippets

terraform apply -target=aws_security_group.my_sg
terraform apply -target=aws_security_group.my_sg -target=aws_security_group.my_2nd_sg
terraform apply -target="module.my_security_groups"

Context

StackExchange DevOps Q#4292, answer score: 58

Revisions (0)

No revisions yet.