DEV Community

Joseph D. Marhee
Joseph D. Marhee

Posted on

Develop new Terraform module resources using targets

A feature of the Terraform CLI is the ability to apply or destroy or plan a specific resource within your module. For example, take an example set of operations in a module like:

resource "null_resource" "file1" {
    environment = {
       resource = "file1"
    }
    provisioner "local-exec" {
       command = "echo $(date) ${resource} | tee -a dates.log"
    }
}

resource "null_resource" "file2" {
    environment = {
       resource = "file2"
    }
    provisioner "local-exec" {
       command = "echo $(date) ${resource} | tee -a dates.log"
    }
}
Enter fullscreen mode Exit fullscreen mode

This would just apply as echoing two dates and the name of the resource, some number of seconds apart into the log. However, let's assume these must become discrete steps; for example, maybe null_resource.file2 only needs to be applied a second time as a check on a running environment, but none of the other steps in the plan do. You can use -target to operate only on null_resource.file2 using this format, which works for any resource type:

terraform {plan,apply,destroy} -target=${resource_type}.${resource_name}
Enter fullscreen mode Exit fullscreen mode

so to plan for null_resource named file2:

terraform plan -target=null_resource.file2
Enter fullscreen mode Exit fullscreen mode

This feature is commonly used for operations like modifying an instance of a module (-target=module.name.resource.name) or applying partial changes to a subset of interdependent resources in your plan (for example, if you create a new volume, or import one not managed by Terraform, you can update a resource for a VM to attach that volume, and then apply the resource for the volume, then the VM resource using this method), but it's also helpful for developing modules:

Using this feature of the Terraform CLI, you can partially execute your plan as you add or remove resources-- this can save you time in extending your module's plans.

Top comments (0)