-
Notifications
You must be signed in to change notification settings - Fork 121
/
gcloud-snapshot.sh
executable file
·459 lines (372 loc) · 11.5 KB
/
gcloud-snapshot.sh
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
#!/usr/bin/env bash
#
# Take snapshots of Google Compute Engine disks
export PATH=$PATH:/usr/local/bin/:/usr/bin
###############################
## ##
## INITIATE SCRIPT FUNCTIONS ##
## ##
## FUNCTIONS ARE EXECUTED ##
## AT BOTTOM OF SCRIPT ##
## ##
###############################
#
# DOCUMENT ARGUMENTS
#
usage() {
echo -e "\nUsage: $0 [-d <days>] [-r <remote_instances>] [-f <gcloud_filter_expression>] [-p <prefix>] [-a <service_account>] [-n <dry_run>] [-j <project_id>] [-t <additional_labels>]" 1>&2
echo -e "\nOptions:\n"
echo -e " -d Number of days to keep snapshots. Snapshots older than this number deleted."
echo -e " Default if not set: 7 [OPTIONAL]"
echo -e " -r Backup remote instances - takes snapshots of all disks calling instance has"
echo -e " access to [OPTIONAL]."
echo -e " -f gcloud filter expression to query disk selection [OPTIONAL]"
echo -e " -g Guest Flush (VSS only for Windows VMs) [OPTIONAL]"
echo -e " -c Copy disk labels to snapshot labels [OPTIONAL]"
echo -e " -p Prefix to be used for naming snapshots."
echo -e " Max character length: 20"
echo -e " Default if not set: 'gcs' [OPTIONAL]"
echo -e " -a Service Account to use."
echo -e " Blank if not set [OPTIONAL]"
echo -e " -j Project ID to use."
echo -e " Blank if not set [OPTIONAL]"
echo -e " -l Snapshot storage location."
echo -e " Uses default storage location if not set [OPTIONAL]"
echo -e " -n Dry run: causes script to print debug variables and doesn't execute any"
echo -e " create / delete commands [OPTIONAL]"
echo -e " -t Additional labels to add to the created snapshots"
echo -e " labels should be formatted as \"label1=value1,label2=value2\""
echo -e "\n"
exit 1
}
#
# GET SCRIPT OPTIONS AND SETS GLOBAL VAR
#
setScriptOptions()
{
while getopts ":d:rf:gcp:a:j:l:nt:" opt; do
case $opt in
d)
opt_d=${OPTARG}
;;
r)
opt_r=true
;;
f)
opt_f=${OPTARG}
;;
g)
opt_g=true
;;
c)
opt_c=true
;;
p)
opt_p=${OPTARG}
;;
a)
opt_a=${OPTARG}
;;
j)
opt_j=${OPTARG}
;;
l)
opt_l=${OPTARG}
;;
n)
opt_n=true
;;
t)
opt_t=${OPTARG}
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
# Number of days to keep snapshots
if [[ -n $opt_d ]]; then
OLDER_THAN=$opt_d
else
OLDER_THAN=7
fi
# Backup remote Instances
if [[ -n $opt_r ]]; then
REMOTE_CLAUSE=$opt_r
fi
# gcloud Filter
if [[ -n $opt_f ]]; then
FILTER_CLAUSE=$opt_f
else
FILTER_CLAUSE=""
fi
# Snapshot Prefix
if [[ -n $opt_p ]]; then
# check if prefix is more than 20 chars
if [ ${#opt_p} -ge 20 ]; then
PREFIX=${opt_p:0:20}
else
PREFIX=$opt_p
fi
else
PREFIX="gcs"
fi
# gcloud Service Account
if [[ -n $opt_a ]]; then
OPT_ACCOUNT="--account $opt_a"
else
OPT_ACCOUNT=""
fi
# gcloud Project
if [[ -n $opt_j ]]; then
OPT_PROJECT="--project $opt_j"
else
OPT_PROJECT=""
fi
# Dry run
if [[ -n $opt_n ]]; then
DRY_RUN=$opt_n
fi
# Copy Disk Labels to Snapshots
if [[ -n $opt_c ]]; then
COPY_LABELS=$opt_c
fi
# Guest Flush (VSS for Windows)
if [[ -n $opt_g ]]; then
OPT_GUEST_FLUSH="--guest-flush"
else
OPT_GUEST_FLUSH=""
fi
# Snapshot storage location
if [[ -n $opt_l ]]; then
OPT_SNAPSHOT_LOCATION="--storage-location $opt_l"
else
OPT_SNAPSHOT_LOCATION=""
fi
# Additional labels
if [[ -n $opt_t ]]; then
ADDITIONAL_LABELS="--labels $opt_t"
else
ADDITIONAL_LABELS=""
fi
# Debug - print variables
if [ "$DRY_RUN" = true ]; then
printDebug "OLDER_THAN=${OLDER_THAN}"
printDebug "REMOTE_CLAUSE=${REMOTE_CLAUSE}"
printDebug "FILTER_CLAUSE=${FILTER_CLAUSE}"
printDebug "PREFIX=${PREFIX}"
printDebug "OPT_ACCOUNT=${OPT_ACCOUNT}"
printDebug "OPT_PROJECT=${OPT_PROJECT}"
printDebug "DRY_RUN=${DRY_RUN}"
printDebug "COPY_LABELS=${COPY_LABELS}"
printDebug "OPT_SNAPSHOT_LOCATION=${OPT_SNAPSHOT_LOCATION}"
printDebug "ADDITIONAL_LABELS=${ADDITIONAL_LABELS}"
fi
}
#
# RETURN INSTANCE NAME
#
getInstanceName()
{
if [ "$REMOTE_CLAUSE" = true ]; then
# return blank so that it gets disks for all instances
echo -e ""
else
# get the name for this vm
local instance_name="$(curl -s "http://metadata.google.internal/computeMetadata/v1/instance/hostname" -H "Metadata-Flavor: Google")"
# strip out the instance name from the fullly qualified domain name the google returns
echo -e "${instance_name%%.*}"
fi
}
#
# RETURNS LIST OF DEVICES
#
# input: ${INSTANCE_NAME}
#
getDeviceList()
{
# echo -e "$(gcloud $OPT_INSTANCE_SERVICE_ACCOUNT compute disks list --filter "users~instances/$1\$ $FILTER_CLAUSE" --format='value(name)')"
local filter=""
# if using remote instances (-r), then no name filter is required
if [ "$REMOTE_CLAUSE" = true ]; then
# check if $FILTER_CLAUSE exists
if [[ ! -z $FILTER_CLAUSE ]]; then
filter="${FILTER_CLAUSE}"
fi
else
# check if $FILTER_CLAUSE exists
if [[ ! -z $FILTER_CLAUSE ]]; then
filter="users~instances/$1\$ AND ${FILTER_CLAUSE}"
else
filter="users~instances/$1\$"
fi
fi
echo -e "$(gcloud $OPT_ACCOUNT compute disks list --filter "${filter}" --format='value(name,zone,id)' $OPT_PROJECT)"
}
#
# RETURNS SNAPSHOT NAME
#
# input: ${PREFIX} ${DEVICE_NAME} ${DATE_TIME}
#
createSnapshotName()
{
# create snapshot name
local name="$1-$2-$3"
# google compute snapshot name cannot be longer than 62 characters
local name_max_len=62
# check if snapshot name is longer than max length
if [ ${#name} -ge ${name_max_len} ]; then
# work out how many characters we require - prefix + timestamp
local req_chars="$1--$3"
# work out how many characters that leaves us for the device name
local device_name_len=`expr ${name_max_len} - ${#req_chars}`
# shorten the device name
local device_name=${2:0:device_name_len}
# create new (acceptable) snapshot name
name="$1-${device_name}-$3" ;
fi
echo -e ${name}
}
#
# CREATES SNAPSHOT AND RETURNS OUTPUT
#
# input: ${DEVICE_NAME}, ${SNAPSHOT_NAME}, ${DEVICE_ZONE}
#
createSnapshot()
{
if [ "$DRY_RUN" = true ]; then
printCmd "gcloud ${OPT_ACCOUNT} compute disks snapshot $1 --snapshot-names $2 --zone $3 ${OPT_PROJECT} ${OPT_SNAPSHOT_LOCATION} ${OPT_GUEST_FLUSH} ${ADDITIONAL_LABELS}"
else
$(gcloud $OPT_ACCOUNT compute disks snapshot $1 --snapshot-names $2 --zone $3 ${OPT_PROJECT} ${OPT_SNAPSHOT_LOCATION} ${OPT_GUEST_FLUSH} ${ADDITIONAL_LABELS})
fi
}
copyDiskLabels()
{
labels=$(gcloud $OPT_ACCOUNT compute disks describe $1 --zone $3 --format='value[delimiter=","](labels)' ${OPT_PROJECT})
if [ "$DRY_RUN" = true ]; then
printCmd "gcloud $OPT_ACCOUNT compute snapshots add-labels $2 --labels=$labels ${OPT_PROJECT}"
else
$(gcloud $OPT_ACCOUNT compute snapshots add-labels $2 --labels=$labels ${OPT_PROJECT})
fi
}
#
# RETURNS DELETION DATE FOR ALL SNAPSHOTS
#
# input: ${OLDER_THAN}
#
getSnapshotDeletionDate()
{
echo -e "$(date -d "-$1 days" +"%Y%m%d")"
}
#
# DELETE SNAPSHOTS FOR DISK
#
# input: ${SNAPSHOT_PREFIX} ${DELETION_DATE} ${DEVICE_ID}
#
deleteSnapshots()
{
# create empty array
local snapshots=()
# get list of snapshots from gcloud for this device
local gcloud_response="$(gcloud $OPT_ACCOUNT compute snapshots list --filter="name~'"$1"' AND creationTimestamp<'$2' AND sourceDiskId='$3'" --uri ${OPT_PROJECT})"
# loop through and get snapshot name from URI
while read line
do
# grab snapshot name from full URI
snapshot="${line##*/}"
# add snapshot to global array
snapshots+=(${snapshot})
done <<< "$(echo -e "$gcloud_response")"
# loop through array
for snapshot in "${snapshots[@]}"; do
# delete snapshot
deleteSnapshot ${snapshot}
done
}
#
# DELETES SNAPSHOT
#
# input: ${SNAPSHOT_NAME}
#
deleteSnapshot()
{
if [ "$DRY_RUN" = true ]; then
printCmd "gcloud ${OPT_ACCOUNT} compute snapshots delete $1 -q ${OPT_PROJECT}"
else
$(gcloud $OPT_ACCOUNT compute snapshots delete $1 -q ${OPT_PROJECT})
fi
}
logTime()
{
local datetime="$(date +"%Y-%m-%d %T")"
echo -e "[$datetime]: $1"
}
printDebug()
{
echo -e "$(tput setab 4)[DEBUG]:$(tput sgr 0) $(tput setaf 4)${1}$(tput sgr 0)"
}
printError()
{
echo -e "$(tput setab 1)[ERROR]:$(tput sgr 0) $(tput setaf 1)${1}$(tput sgr 0)"
}
printCmd()
{
echo -e "$(tput setab 3)$(tput setaf 0)[CMD]:$(tput sgr 0) $(tput setaf 3)${1}$(tput sgr 0)"
}
######################
## ##
## WRAPPER FUNCTION ##
## ##
######################
main()
{
# log time
logTime "Start of google-compute-snapshot"
# set script options
setScriptOptions "$@"
# get current datetime
DATE_TIME="$(date "+%s")"
# get deletion date for existing snapshots
DELETION_DATE=$(getSnapshotDeletionDate "${OLDER_THAN}")
# get local instance name (blank if using remote instances)
INSTANCE_NAME=$(getInstanceName)
# dry run: debug output
if [ "$DRY_RUN" = true ]; then
printDebug "DATE_TIME=${DATE_TIME}"
printDebug "DELETION_DATE=${DELETION_DATE}"
printDebug "INSTANCE_NAME=${INSTANCE_NAME}"
fi
# get list of all the disks that match filter
DEVICE_LIST=$(getDeviceList ${INSTANCE_NAME})
# check if any disks were found
if [[ -z $DEVICE_LIST ]]; then
printError "No disks were found - please check your script options / account permissions."
exit 1
fi
# dry run: debug disk output
if [ "$DRY_RUN" = true ]; then
printDebug "DEVICE_LIST=${DEVICE_LIST}"
fi
# loop through the devices
echo "${DEVICE_LIST}" | while read device_name device_zone device_id; do
logTime "Handling Snapshots for ${device_name}"
# build snapshot name
local snapshot_name=$(createSnapshotName ${PREFIX} ${device_name} ${DATE_TIME})
# delete snapshots for this disk that were created older than DELETION_DATE
deleteSnapshots "^$PREFIX-.*" "$DELETION_DATE" "${device_id}"
# create the snapshot
createSnapshot ${device_name} ${snapshot_name} ${device_zone}
if [ "$COPY_LABELS" = true ]; then
# Copy labels
copyDiskLabels ${device_name} ${snapshot_name} ${device_zone}
fi
done
logTime "End of google-compute-snapshot"
}
####################
## ##
## EXECUTE SCRIPT ##
## ##
####################
main "$@"