Custom Hooks

Custom hooks are used to customize the core Terraform and OpenTofu workflow. It is a common requirement to have to run a command, script, or API call before or after the Terraform plan and/or apply events. For example, many customers run lint tests before the plan to ensure the Terraform code is formatted correctly or install software before the apply if it is needed for the Terraform code to execute correctly.

If a command is being used in the hook, nothing else is needed except typing the command into the text box, shell variables can be referenced if required.

If a script is being used, whether it is a VCS or CLI based workspace, the script must be in the directory that the workspace is pointed to. Optionally, the script can also be downloaded (i.e. wget https://script.sh | sh ). Please ensure the script has execute permissions (i.e. chmod +x <filename>).

If you are using pip to install a binary, the binary will be installed under /tmp/.local/bin.

Terraform outputs can be used as part of the input for a command or script as Terraform and the hooks are executed in the same container. Use terraform output -json to pull the output in JSON format and then use it in your script.

Custom hooks are added as part of the workspace creation or after a workspace is created by going into the workspace settings:

1166

The output of the hooks can be seen directly in the console output for the plan and apply.

Hook Examples

Import Resources

A common use case we see with the pre-plan hooks is to import resources into Terraform state. Rather than downloading the state, manipulating it, and pushing it back into Scalr, you can do all of this directly in a pre-plan hook:

terraform import aws_instance.example <Instance ID>

Pulling Plan Details

In the case where the Terraform plan might need to be exported and used externally, it can be pulled by using the command below before the plan or apply, or after apply:

terraform show -json /opt/data/terraform.tfplan.bin