-
Notifications
You must be signed in to change notification settings - Fork 3
/
clone-linux.sh
97 lines (77 loc) · 2.01 KB
/
clone-linux.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
#!/usr/bin/env sh
set -e
getInstanceMetadata()
{
KEY=$1
echo $(curl -s -H "Metadata-Flavor: Google" "http://metadata/computeMetadata/v1/instance/$KEY")
}
getVmName()
{
echo $(getInstanceMetadata name)
}
getZone()
{
zone=$(getInstanceMetadata zone)
echo $zone | sed 's/.*\(zones\/\)\(europe-west4-a\).*/\2/'
}
getPatchJobId()
{
VM=$1
ZONE=$2
# Get running patch jobs
jobs=`gcloud compute os-config patch-jobs list --filter="state:patching" --format="value(ID)"`
# Iterating all jobs
for job in $jobs; do
# Check if this instance is targetted by the patch job
# and the job is in the RUNNING_PRE_PATCH_STEP
filter="name:$VM AND zone:$ZONE AND state:RUNNING_PRE_PATCH_STEP"
instance=`gcloud compute os-config patch-jobs list-instance-details $job --filter="$filter" --format="value(NAME)"`
if [ "$instance" = "$VM" ]; then
echo $job
return;
fi
done
echo -1
}
getDisks()
{
VM=$1
ZONE=$2
echo $(gcloud compute instances describe $VM --zone $ZONE --format="value[delimiter=\n](disks[].source)")
}
newClone()
{
DISKS=$1
VM=$2
JOBID=$3
for diskId in $DISKS; do
targetDiskId="$diskId-$JOBID"
gcloud compute disks create $targetDiskId \
--description="Clone before patching" \
--labels reason=patching,patchjob=$JOBID,vm=$VM \
--user-output-enabled false \
--source-disk $diskId
# Stop creating any additional clones
if [ $? -ne 0 ]; then
echo 1
return
fi
done
echo 0
}
vmName=$(getVmName);
zone=$(getZone);
echo -n "Determining patch job: "
jobId=$(getPatchJobId $vmName $zone)
echo $jobId;
echo -n "Retrieving disks associated with VM: "
disks=$(getDisks $vmName $zone)
echo "$(echo "$disks" | wc -w) disk(s) found"
echo -n "Creating clone(s): ";
result=$(newClone "$disks" $vmName $jobId)
if [ $result -eq 0 ]; then
echo "done"
else
echo "failed"
exit 1
fi