Skip to content

How to Delete Terraform Assets and Statefiles in a GitLab Pipeline Backend

In using the remote GitLab backend for your detached pipeline with **Terraform, you might wonder how one can clean up after running jobs. Here’s what needs doing:

The Challenge of Deletion

Currently, Terraform lacks a built-in function to delete statefiles in remote backends like GitLab directly through the tooling interface or CLI commands such as terraform destroy. There is an ongoing discussion about this feature request here.

Post-Pipeline Cleanup Steps:

To handle deletion post-pilot, you can follow these steps:

  1. Terragrunt State Removal
    Run gitlab terraform destroy, which will remove all resources specified in your state file during the Terragrunt configuration’s execution phase of destruction jobs (refer to GitLab’s documentation).

  2. State File Deletion using API
    For a more hands-on approach, you can remove the state file by utilizing:

    • The GitLab REST APIs with curl commands for those comfortable scripting or automating tasks; instructions are available here.
    • Or through GitHub API (GitHub-based solutions could be similar), especially if you prefer using a graphical interface like the GraphQL Explorer provided by GitLab:
      mutation RemoveStateFile($stateID: ID!) { deleteTerraformState(id: $stateID) } 
      variables: { stateID: "your_actual_statefile_identifier" }
      # Use the above GraphQL snippet as directed in GitLab’s documentation.
      

    Note that you will need proper permissions to execute such API calls, typically owned by repository maintainers or superusers with sufficient access rights within your project’s settings on their profile.

Remember always to handle deletions carefully and understand the implications of removing resources tied up in a statefile as they might be provisioned for important purposes like testing environments that should not simply vanish upon request. Ensure proper backups or rollback plans are available, especially when dealing with production assets!


Previous Post
Does glab glab cli Support Creating Project Acce
Next Post
Implications of Running Too Old Kubernetes k8s