@Summary Delete template by ID @ID delete-template-by-id @Security CoderSessionToken @Produce json @Tags Templates @Param template path string true "Template ID" format(uuid) @Success 200 {object} codersdk.Response @Router /api/v2/templates/{template} [delete]
(rw http.ResponseWriter, r *http.Request)
| 63 | // @Success 200 {object} codersdk.Response |
| 64 | // @Router /api/v2/templates/{template} [delete] |
| 65 | func (api *API) deleteTemplate(rw http.ResponseWriter, r *http.Request) { |
| 66 | var ( |
| 67 | apiKey = httpmw.APIKey(r) |
| 68 | ctx = r.Context() |
| 69 | template = httpmw.TemplateParam(r) |
| 70 | auditor = *api.Auditor.Load() |
| 71 | aReq, commitAudit = audit.InitRequest[database.Template](rw, &audit.RequestParams{ |
| 72 | Audit: auditor, |
| 73 | Log: api.Logger, |
| 74 | Request: r, |
| 75 | Action: database.AuditActionDelete, |
| 76 | OrganizationID: template.OrganizationID, |
| 77 | }) |
| 78 | ) |
| 79 | defer commitAudit() |
| 80 | aReq.Old = template |
| 81 | |
| 82 | // This is just to get the workspace count, so we use a system context to |
| 83 | // return ALL workspaces. Not just workspaces the user can view. |
| 84 | // nolint:gocritic |
| 85 | workspaces, err := api.Database.GetWorkspaces(dbauthz.AsSystemRestricted(ctx), database.GetWorkspacesParams{ |
| 86 | TemplateIDs: []uuid.UUID{template.ID}, |
| 87 | }) |
| 88 | if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| 89 | httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ |
| 90 | Message: "Internal error fetching workspaces by template id.", |
| 91 | Detail: err.Error(), |
| 92 | }) |
| 93 | return |
| 94 | } |
| 95 | // Allow deletion when only prebuild workspaces remain. Prebuilds |
| 96 | // are owned by the system user and will be cleaned up |
| 97 | // asynchronously by the prebuilds reconciler once the template's |
| 98 | // deleted flag is set. |
| 99 | for _, ws := range workspaces { |
| 100 | if ws.OwnerID != database.PrebuildsSystemUserID { |
| 101 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 102 | Message: "All workspaces must be deleted before a template can be removed.", |
| 103 | }) |
| 104 | return |
| 105 | } |
| 106 | } |
| 107 | err = api.Database.UpdateTemplateDeletedByID(ctx, database.UpdateTemplateDeletedByIDParams{ |
| 108 | ID: template.ID, |
| 109 | Deleted: true, |
| 110 | UpdatedAt: dbtime.Now(), |
| 111 | }) |
| 112 | if dbauthz.IsNotAuthorizedError(err) { |
| 113 | httpapi.Forbidden(rw) |
| 114 | return |
| 115 | } |
| 116 | if err != nil { |
| 117 | httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ |
| 118 | Message: "Internal error deleting template.", |
| 119 | Detail: err.Error(), |
| 120 | }) |
| 121 | return |
| 122 | } |
no test coverage detected