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?


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 (and no, you can't target multiple resources in one command).

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?).

  • Use a script to temporarily isolate the file.

    Given you're using --auto-approve I'm guessing you might be running this in automation. So, you could potentially do something like this in your CI script:

    ls *.tf | grep -v security-groups.tf | xargs -I % mv % %.bak
    terraform apply --auto-approve

    That would make all of your *.tf files, except for the security groups, 'invisible' to Terraform for that run, as they'll have the .bak extension. Of course, you might also need to exclude your config.tf (or wherever you have your provider configured) and any other files that the security groups rely on.

  • 1
    Haha I actually just had a need for this and went to implement my second suggestion... and then realised, duh, Terraform is now going to want to destroy all resources in the other files! I'll keep thinking, but a solution might need to just rely on parsing a file and building several terraform apply -target=... commands from it... – Tim Malone Jun 18 '18 at 22:21
  • Good point! You might want to update your answer before someone applies that solution in too much of a hurry! – Max Murphy Dec 17 '18 at 12:41

Doesn't look like it's possible. Here is the code to load config files and it loads all *.tf files from current directory (or a specified one) and there is nothing there to limit the configuration to a single file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.