-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
clone_kms_encrypted_disk.go
81 lines (70 loc) · 2.42 KB
/
clone_kms_encrypted_disk.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package snippets
// [START compute_disk_clone_encrypted_disk_kms]
import (
"context"
"fmt"
"io"
compute "cloud.google.com/go/compute/apiv1"
computepb "cloud.google.com/go/compute/apiv1/computepb"
"google.golang.org/protobuf/proto"
)
// Creates a zonal non-boot persistent disk in a project with the copy of data from an existing disk.
// The encryption key must be the same for the source disk and the new disk.
// The disk type and size may differ.
func createDiskFromKmsEncryptedDisk(
w io.Writer,
projectID, zone, diskName, diskType string,
diskSizeGb int64,
diskLink, kmsKeyLink string,
) error {
// projectID := "your_project_id"
// zone := "us-west3-b" // should match diskType below
// diskName := "your_disk_name"
// diskType := "zones/us-west3/diskTypes/pd-ssd"
// diskSizeGb := 120
// diskLink := "projects/your_project_id/global/disks/disk_name"
// kmsKeyLink := "projects/your_kms_project_id/locations/us-central1/keyRings/your_key_ring/cryptoKeys/your_key"
ctx := context.Background()
disksClient, err := compute.NewDisksRESTClient(ctx)
if err != nil {
return fmt.Errorf("NewDisksRESTClient: %w", err)
}
defer disksClient.Close()
req := &computepb.InsertDiskRequest{
Project: projectID,
Zone: zone,
DiskResource: &computepb.Disk{
Name: proto.String(diskName),
Zone: proto.String(zone),
Type: proto.String(diskType),
SizeGb: proto.Int64(diskSizeGb),
SourceDisk: proto.String(diskLink),
DiskEncryptionKey: &computepb.CustomerEncryptionKey{
KmsKeyName: &kmsKeyLink,
},
},
}
op, err := disksClient.Insert(ctx, req)
if err != nil {
return fmt.Errorf("unable to create disk: %w", err)
}
if err = op.Wait(ctx); err != nil {
return fmt.Errorf("unable to wait for the operation: %w", err)
}
fmt.Fprintf(w, "Disk created\n")
return nil
}
// [END compute_disk_clone_encrypted_disk_kms]