Introduction
Sometimes, Users have many HCP Terraform runs which are stuck due to anonymous reason , in some cases user need to cancel those RUNs to clear up the processing queue so that new runs can take place to process .
Solution
First, Please create a list of run-ids of all pending runs. This can be accomplished using the below mentioned commands, Please note below mentioned API cannot be accessed with organization tokens. You must access it with a user token or team token.
curl \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/vnd.api+json" \
https://app.terraform.io/api/v2/workspaces/<WS-ID>/runs | jq | grep -e '"status": "pending"' -e '"id":' | grep pending -B1 | grep id | awk -F '"' '{print $4}' > list_of_pending_runs.txt
The pending runs should be saved to list_of_pending_runs.txt
file in your local directory. Make sure those are the correct run-ids by comparing them to the UI.
Now from command line you can do a loop over the list of runs using the discard runs API call effectively canceling the pending runs in the workspace.
for i in `list_of_pending_runs.txt` ;
do curl \
--header "Authorization: Bearer $TOKEN" \
--header "Content-Type: application/vnd.api+json" \
--request POST \
--data @payload.json \
https://app.terraform.io/api/v2/runs/$i/actions/discard | jq;
done
A sample for the payload.json
can be:
{
"comment": "This run was discarded"
}
Additionally you can check the instructions on how to work with the runs API here.
Note :: The above example is based on UNIX based system, Please make necessary changes for other OS systems .