|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "strconv" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/scaleway/scaleway-sdk-go/api/instance/v1" |
| 12 | + "github.com/scaleway/scaleway-sdk-go/scw" |
| 13 | +) |
| 14 | + |
| 15 | +const ( |
| 16 | + envOrgID = "SCW_DEFAULT_ORGANIZATION_ID" |
| 17 | + envAccessKey = "SCW_ACCESS_KEY" |
| 18 | + envSecretKey = "SCW_SECRET_KEY" |
| 19 | + envProjectID = "SCW_PROJECT_ID" |
| 20 | + envZone = "SCW_ZONE" |
| 21 | + |
| 22 | + // envDeleteAfter name of env variable to deleter older images. |
| 23 | + envDeleteAfter = "SCW_DELETE_AFTER_DAYS" |
| 24 | + |
| 25 | + // defaultDaysDeleteAfter is the default days value for older images to be deleted. |
| 26 | + defaultDaysDeleteAfter = int(90) |
| 27 | +) |
| 28 | + |
| 29 | +func main() { |
| 30 | + fmt.Println("cleaning instances snapshots...") |
| 31 | + |
| 32 | + // Create a Scaleway client with credentials from environment variables. |
| 33 | + client, err := scw.NewClient( |
| 34 | + // Get your organization ID at https://console.scaleway.com/organization/settings |
| 35 | + scw.WithDefaultOrganizationID(os.Getenv(envOrgID)), |
| 36 | + |
| 37 | + // Get your credentials at https://console.scaleway.com/iam/api-keys |
| 38 | + scw.WithAuth(os.Getenv(envAccessKey), os.Getenv(envSecretKey)), |
| 39 | + |
| 40 | + // Get more about our availability |
| 41 | + // zones at https://www.scaleway.com/en/docs/console/my-account/reference-content/products-availability/ |
| 42 | + scw.WithDefaultRegion(scw.RegionFrPar), |
| 43 | + ) |
| 44 | + if err != nil { |
| 45 | + panic(err) |
| 46 | + } |
| 47 | + |
| 48 | + // Create SDK objects for Scaleway Instance product |
| 49 | + instanceAPI := instance.NewAPI(client) |
| 50 | + |
| 51 | + deleteAfterDays := defaultDaysDeleteAfter |
| 52 | + |
| 53 | + deleteAfterDaysVar := os.Getenv(envDeleteAfter) |
| 54 | + |
| 55 | + if deleteAfterDaysVar != "" { |
| 56 | + deleteAfterDays, err = strconv.Atoi(deleteAfterDaysVar) |
| 57 | + if err != nil { |
| 58 | + panic(err) |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + if err := cleanSnapshots(deleteAfterDays, instanceAPI); err != nil { |
| 63 | + var precondErr *scw.PreconditionFailedError |
| 64 | + |
| 65 | + if errors.As(err, &precondErr) { |
| 66 | + fmt.Println("\nExtracted Error Details:") |
| 67 | + fmt.Println("Precondition:", precondErr.Precondition) |
| 68 | + fmt.Println("Help Message:", precondErr.HelpMessage) |
| 69 | + |
| 70 | + // Decode RawBody (if available) |
| 71 | + if len(precondErr.RawBody) > 0 { |
| 72 | + var parsedBody map[string]interface{} |
| 73 | + if json.Unmarshal(precondErr.RawBody, &parsedBody) == nil { |
| 74 | + fmt.Println("RawBody (Decoded):", parsedBody) |
| 75 | + } else { |
| 76 | + fmt.Println("RawBody (Raw):", string(precondErr.RawBody)) |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + panic(err) |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +// cleanSnapshots when called will clean snapshots in the project (if specified) |
| 85 | +// that are older than the number of days. |
| 86 | +func cleanSnapshots(days int, instanceAPI *instance.API) error { |
| 87 | + // Get the list of all snapshots |
| 88 | + snapshotsList, err := instanceAPI.ListSnapshots(&instance.ListSnapshotsRequest{ |
| 89 | + Zone: scw.Zone(os.Getenv(envZone)), |
| 90 | + Project: scw.StringPtr(os.Getenv(envProjectID)), |
| 91 | + }, |
| 92 | + scw.WithAllPages()) |
| 93 | + if err != nil { |
| 94 | + return fmt.Errorf("error while listing snapshots %w", err) |
| 95 | + } |
| 96 | + |
| 97 | + const hoursPerDay = 24 |
| 98 | + |
| 99 | + currentTime := time.Now() |
| 100 | + |
| 101 | + // For each snapshot, check conditions |
| 102 | + for _, snapshot := range snapshotsList.Snapshots { |
| 103 | + // Check if snapshot is in ready state and if it's older than the number of days definied. |
| 104 | + if snapshot.State == instance.SnapshotStateAvailable && (currentTime.Sub(*snapshot.CreationDate).Hours()/hoursPerDay) > float64(days) { |
| 105 | + fmt.Printf("\nDeleting snapshot <%s>:%s created at: %s\n", snapshot.ID, snapshot.Name, snapshot.CreationDate.Format(time.RFC3339)) |
| 106 | + |
| 107 | + // Delete snapshot found. |
| 108 | + err := instanceAPI.DeleteSnapshot(&instance.DeleteSnapshotRequest{ |
| 109 | + SnapshotID: snapshot.ID, |
| 110 | + Zone: snapshot.Zone, |
| 111 | + }) |
| 112 | + if err != nil { |
| 113 | + return fmt.Errorf("error while deleting snapshot: %w", err) |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + return nil |
| 119 | +} |
| 120 | + |
| 121 | +// Check for mandatory variables before starting to work. |
| 122 | +func init() { |
| 123 | + mandatoryVariables := [...]string{envOrgID, envAccessKey, envSecretKey, envZone, envProjectID} |
| 124 | + |
| 125 | + for idx := range mandatoryVariables { |
| 126 | + if os.Getenv(mandatoryVariables[idx]) == "" { |
| 127 | + panic("missing environment variable " + mandatoryVariables[idx]) |
| 128 | + } |
| 129 | + } |
| 130 | +} |
0 commit comments