-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy-vm.sh
More file actions
executable file
·657 lines (640 loc) · 25.9 KB
/
Copy pathdeploy-vm.sh
File metadata and controls
executable file
·657 lines (640 loc) · 25.9 KB
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
#!/bin/bash
#
# https://github.com/adamaze/deploy-vm
script_version=1.18.0
#
# Vars
var_file=~/.config/deploy-vm/default.vars
supported_os_list="
centos-stream9
centos-stream10
rocky8
rocky9
rocky10
almalinux8
almalinux9
almalinux10
opensuse15-6
opensuse16-0
debian12
debian13
debiansid
fedora43
fedora44
ubuntu2204
ubuntu2404
ubuntu2504
ubuntu2510
ubuntu2604
arch
alpine3-23
"
#
# FUNCTIONS
#
function check_required_commands() {
missing_commands=()
required_commands=(
"curl"
"ping"
"virsh"
"wget"
"qemu-img"
"genisoimage"
"virt-install"
"osinfo-query"
)
# Check required commands
for cmd in "${required_commands[@]}"; do
if ! command -v "$cmd" >/dev/null 2>&1; then
missing_commands+=("$cmd")
fi
done
# Report missing required commands
if [[ ${#missing_commands[@]} -gt 0 ]]; then
echo "ERROR: The following required commands are missing:"
for cmd in "${missing_commands[@]}"; do
echo " - $cmd"
done
exit 1
fi
}
#
function ask() {
local prompt default reply
if [[ ${2:-} = 'Y' ]]; then
prompt='Y/n'
default='Y'
elif [[ ${2:-} = 'N' ]]; then
prompt='y/N'
default='N'
else
prompt='y/n'
default=''
fi
while true; do
# Ask the question (not using "read -p" as it uses stderr not stdout)
echo -n "$1 [$prompt] "
# Read the answer (use /dev/tty in case stdin is redirected from somewhere else)
read -r reply </dev/tty
# Default?
if [[ -z $reply ]]; then
reply=$default
fi
# Check if the reply is valid
case "$reply" in
Y*|y*) return 0 ;;
N*|n*) return 1 ;;
esac
done
}
#
function usage() {
echo "deploy-vm version $script_version"
echo "Usage: $0 -h hostname_to_build | [-c cpu_core_count] [-r ram_in_GB] [-d disk_size] [-o os] [-i ip_address/mask] [-g gateway] [-n nameserver]" 1>&2
echo " -l List avilable OS versions." 1>&2
echo " -F Skip the y/n prompt when deploying." 1>&2
echo " -V Show version" 1>&2
exit 1
}
#
function set_defaults() {
mkdir -p $(dirname $var_file)
echo "Creating var file: $var_file"
echo "# settings for deploy-vm script
VM_IMAGE_DIR=/var/lib/libvirt
user=adam
ram=2048
cpu=2
disk_size=20
os=rocky9
network_type=DHCP
ssh_pub_key_file=
BRIDGE=br0
github_user=
user_data_file=
" > $var_file
}
function load_settings() {
. $var_file
# validate SSH keys
if [[ ! -e $ssh_pub_key_file ]] && [[ -z $github_user ]]; then
echo "ssh_pub_key_file: $ssh_pub_key_file does not exist, and \$github_user is not set"
exit 1
fi
if [[ -n $github_user ]]; then
github_ssh_keys=$(curl --silent https://github.com/${github_user}.keys )
if [[ $? -ne 0 ]] || [[ -z $github_ssh_keys ]]; then
echo "Unable to grab ssh keys from github user $github_user"
exit 1
fi
fi
if [[ -n $user_data_file ]] && [[ ! -e $user_data_file ]]; then
echo "Specified user_data_file does not exist: $user_data_file"
exit 1
fi
}
function generate_server_name() {
wordlist="/usr/share/dict/words"
# Check if wordlist exists
if [[ ! -f "$wordlist" ]]; then
echo "wordlist not found. You may need to install a package, or specify a hostname with -h" >&2
echo "sudo dnf install words # For Red Hat/Rocky/Alma Linux" >&2
echo "sudo apt install wamerican # For Debian/Ubuntu" >&2
exit 1
fi
# Filter for appropriate words (4-8 chars, alphabetic only)
hostname_word_1=$(grep -E '^[a-z]{4,8}$' "$wordlist" | shuf -n 1)
hostname_word_2=$(grep -E '^[a-z]{4,8}$' "$wordlist" | shuf -n 1)
hostname_to_build="${os}-${hostname_word_1}-${hostname_word_2}"
}
function validate_input() {
# check if name is valid
if [[ ! "$hostname_to_build" =~ ^[a-zA-Z0-9-]+$ ]]; then
echo "ERROR: hostname can only contain [a-zA-Z0-9-]"
((validation_errors++))
fi
# check if name pings
if [[ $(ping -c1 -W1 $hostname_to_build >/dev/null 2>&1; echo $?) -eq 0 ]]; then
echo "ERROR: $hostname_to_build already responds to ping."
((validation_errors++))
fi
# check if vm exists with name
if [[ $(virsh list --name | grep -i ^${hostname_to_build}$ >/dev/null 2>&1; echo $?) -eq 0 ]]; then
echo "ERROR: $hostname_to_build already exists."
((validation_errors++))
fi
# check if enough CPU cores exist
if [[ $cpu -gt $(nproc) ]]; then
echo "ERROR: You asked for $cpu cores, but this system only has $(nproc)."
((validation_errors++))
fi
# check if enough RAM exists
total_mem_kb=$(grep MemTotal /proc/meminfo | awk '{print $2}')
total_mem_mb=$((total_mem_kb / 1024))
if [[ $ram -gt $total_mem_mb ]]; then
echo "ERROR: You asked for $ram MB of ram, but this sytem only has ${total_mem_mb}MB."
((validation_errors++))
fi
# check if enough disk space exists
available_space=$(df -BG $VM_IMAGE_DIR --output=avail| tail -1 | sed 's/G//' | awk '{print $1}' )
if [[ $disk_size -gt $available_space ]]; then
echo "ERROR: You asked for a ${disk_size}GB disk, but $VM_IMAGE_DIR only has ${available_space}GB "
((validation_errors++))
fi
# check if os is valid
if [[ ! "$supported_os_list" =~ (^|[[:space:]])"$os"($|[[:space:]]) ]]; then
echo "ERROR: $os is not a supported OS"
echo See supported OS list:
echo "$supported_os_list"
echo
((validation_errors++))
fi
# Validate network interface
if [[ ! -d "/sys/class/net/$BRIDGE" ]]; then
echo "ERROR: Network interface $BRIDGE does not exist"
((validation_errors++))
else
# Check if it's actually a bridge
if [[ -d "/sys/class/net/$BRIDGE/bridge" ]]; then
bridge_operstate=$(cat /sys/class/net/$BRIDGE/operstate 2>/dev/null || echo "unknown")
if [[ "$bridge_operstate" != "up" ]]; then
echo "ERROR: Bridge $BRIDGE is not up - VMs may not get network connectivity"
((validation_errors++))
fi
else
echo "ERROR: $BRIDGE exists but is not a bridge interface"
((validation_errors++))
fi
fi
if [[ $validation_errors -gt 0 ]]; then
if [[ $validation_errors -gt 1 ]]; then
errors_plural="s"
fi
echo "$validation_errors validation error${errors_plural} found. exiting..."
exit 1
fi
# Check static IP requirements
if [[ -n "$ip_address" || -n "$gateway" || -n "$nameserver" ]]; then
if [[ -z "$ip_address" || -z "$gateway" || -z "$nameserver" ]]; then
echo "ERROR: If configuring a static IP, you must provide all of: ip_address/mask (-i), gateway (-g), and nameserver (-n)."
((validation_errors++))
fi
network_type="static ip: $ip_address gateway: $gateway nameserver: $nameserver"
fi
}
function cache_image() {
mkdir -p $VM_IMAGE_DIR/base
checksum_type=sha256
shell="/bin/bash"
sudo_group="sudo"
case "$os" in
centos-stream9)
OS_VARIANT="centos-stream9"
IMAGE_URL="https://cloud.centos.org/centos/9-stream/x86_64/images/CentOS-Stream-GenericCloud-9-latest.x86_64.qcow2"
IMAGE_CHECKSUM="$(curl --silent https://cloud.centos.org/centos/9-stream/x86_64/images/CentOS-Stream-GenericCloud-9-latest.x86_64.qcow2.SHA256SUM | tail -1 | awk '{print $NF}')"
;;
centos-stream10)
OS_VARIANT="centos-stream9"
IMAGE_URL="https://cloud.centos.org/centos/10-stream/x86_64/images/CentOS-Stream-GenericCloud-10-latest.x86_64.qcow2"
IMAGE_CHECKSUM="$(curl --silent https://cloud.centos.org/centos/10-stream/x86_64/images/CentOS-Stream-GenericCloud-10-latest.x86_64.qcow2.SHA256SUM | tail -1 | awk '{print $NF}')"
;;
rocky8)
OS_VARIANT="rocky8"
IMAGE_URL="https://dl.rockylinux.org/vault/rocky/8.9/images/x86_64/Rocky-8-GenericCloud.latest.x86_64.qcow2"
IMAGE_CHECKSUM="$(curl --silent https://dl.rockylinux.org/vault/rocky/8.9/images/x86_64/Rocky-8-GenericCloud.latest.x86_64.qcow2.CHECKSUM | tail -1 | awk '{print $NF}')"
;;
rocky9)
OS_VARIANT="rocky9"
IMAGE_URL="https://dl.rockylinux.org/pub/rocky/9/images/x86_64/Rocky-9-GenericCloud.latest.x86_64.qcow2"
IMAGE_CHECKSUM="$(curl --silent https://dl.rockylinux.org/pub/rocky/9/images/x86_64/Rocky-9-GenericCloud.latest.x86_64.qcow2.CHECKSUM | tail -1 | awk '{print $NF}')"
;;
rocky10)
OS_VARIANT="rocky10"
OS_VARIANT="$(osinfo-query os | grep '^ rocky10' | awk '{print $1}')"
if [[ -z $OS_VARIANT ]]; then
OS_VARIANT="$(osinfo-query os | grep ' Rocky Linux ' | sort -n -t\| -k3 | grep -v unknown | tail -1 | awk '{print $1}')"
fi
IMAGE_URL="https://dl.rockylinux.org/pub/rocky/10/images/x86_64/Rocky-10-GenericCloud-Base.latest.x86_64.qcow2"
IMAGE_CHECKSUM="$(curl --silent https://dl.rockylinux.org/pub/rocky/10/images/x86_64/Rocky-10-GenericCloud-Base.latest.x86_64.qcow2.CHECKSUM | tail -1 | awk '{print $NF}')"
;;
almalinux8)
OS_VARIANT="almalinux8"
IMAGE_URL="https://repo.almalinux.org/almalinux/8/cloud/x86_64/images/AlmaLinux-8-GenericCloud-latest.x86_64.qcow2"
IMAGE_CHECKSUM="$(curl --silent https://repo.almalinux.org/almalinux/8/cloud/x86_64/images/CHECKSUM | grep $(basename $IMAGE_URL) | awk '{print $1}')"
;;
almalinux9)
OS_VARIANT="almalinux9"
IMAGE_URL="https://repo.almalinux.org/almalinux/9/cloud/x86_64/images/AlmaLinux-9-GenericCloud-latest.x86_64.qcow2"
IMAGE_CHECKSUM="$(curl --silent https://repo.almalinux.org/almalinux/9/cloud/x86_64/images/CHECKSUM | grep $(basename $IMAGE_URL) | awk '{print $1}')"
;;
almalinux10)
OS_VARIANT="$(osinfo-query os | grep '^ almalinux10' | awk '{print $1}')"
if [[ -z $OS_VARIANT ]]; then
OS_VARIANT="$(osinfo-query os | grep ' AlmaLinux ' | sort -n -t\| -k3 | tail -1 | awk '{print $1}')"
fi
IMAGE_URL="https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-latest.x86_64.qcow2"
IMAGE_CHECKSUM="$(curl --silent https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/CHECKSUM | grep $(basename $IMAGE_URL) | awk '{print $1}')"
;;
opensuse15-6)
OS_VARIANT="$(osinfo-query os | grep opensuse15.6 | awk '{print $1}')"
if [[ -z $OS_VARIANT ]]; then
OS_VARIANT="$(osinfo-query os | grep opensuse15 | sort -n -t\| -k3 -r | head -1 | awk '{print $1}')"
fi
IMAGE_URL="https://download.opensuse.org/distribution/leap/15.6/appliances/openSUSE-Leap-15.6-Minimal-VM.x86_64-Cloud.qcow2"
IMAGE_CHECKSUM="$(curl --silent https://download.opensuse.org/distribution/leap/15.6/appliances/openSUSE-Leap-15.6-Minimal-VM.x86_64-Cloud.qcow2.sha256 | grep $(basename $IMAGE_URL) | awk '{print $1}')"
;;
opensuse16-0)
OS_VARIANT="$(osinfo-query os | grep opensuse16.0 | awk '{print $1}')"
if [[ -z $OS_VARIANT ]]; then
OS_VARIANT="$(osinfo-query os | grep opensuse15 | sort -n -t\| -k3 -r | head -1 | awk '{print $1}')"
fi
IMAGE_URL="https://download.opensuse.org/distribution/leap/16.0/appliances/Leap-16.0-Minimal-VM.x86_64-Cloud.qcow2"
IMAGE_CHECKSUM="$(curl --silent https://download.opensuse.org/distribution/leap/16.0/appliances/Leap-16.0-Minimal-VM.x86_64-Cloud.qcow2.sha256 | grep $(basename $IMAGE_URL) | awk '{print $1}')"
;;
# we use the "generic" image for debian, as the "genericcloud" one doesnt have drivers for the cdrom drive cloud-init uses
# https://salsa.debian.org/kernel-team/linux/-/merge_requests/699
debian12)
OS_VARIANT="debian12"
IMAGE_URL="http://cdimage.debian.org/images/cloud/bookworm/latest/debian-12-generic-amd64.qcow2"
IMAGE_CHECKSUM="$(curl --silent http://cdimage.debian.org/images/cloud/bookworm/latest/SHA512SUMS | grep $(basename $IMAGE_URL) | awk '{print $1}')"
checksum_type=sha512
;;
debian13)
OS_VARIANT="$(osinfo-query os | grep debian13 | awk '{print $1}')"
if [[ -z $OS_VARIANT ]]; then
OS_VARIANT="$(osinfo-query os | grep debian | sort -n -t\| -k3 -r | head -1 | awk '{print $1}')"
fi
IMAGE_URL="http://cdimage.debian.org/images/cloud/trixie/latest/debian-13-generic-amd64.qcow2"
IMAGE_CHECKSUM="$(curl --silent http://cdimage.debian.org/images/cloud/trixie/latest/SHA512SUMS | grep $(basename $IMAGE_URL) | awk '{print $1}')"
checksum_type=sha512
;;
debiansid)
OS_VARIANT="debiantesting"
IMAGE_URL="http://cdimage.debian.org/images/cloud/sid/daily/latest/debian-sid-generic-amd64-daily.qcow2"
IMAGE_CHECKSUM="$(curl --silent http://cdimage.debian.org/images/cloud/sid/daily/latest/SHA512SUMS | grep $(basename $IMAGE_URL) | awk '{print $1}')"
checksum_type=sha512
;;
# for fedora, ubuntu, and alpine try to use the exact os name, but if that isnt there, just use the latest osinfo-query knows about
fedora43)
OS_VARIANT="$(osinfo-query os | grep '^ fedora43' | awk '{print $1}')"
if [[ -z $OS_VARIANT ]]; then
OS_VARIANT="$(osinfo-query os | grep ' Fedora Linux ' | sort -n -t\| -k3 | tail -1 | awk '{print $1}')"
fi
IMAGE_URL="https://fedora.mirror.constant.com/fedora/linux/releases/43/Cloud/x86_64/images/Fedora-Cloud-Base-Generic-43-1.6.x86_64.qcow2"
IMAGE_CHECKSUM="$(curl --silent https://fedora.mirror.constant.com/fedora/linux/releases/43/Cloud/x86_64/images/Fedora-Cloud-43-1.6-x86_64-CHECKSUM | grep $(basename $IMAGE_URL) | grep SHA256 | awk '{print $NF}')"
;;
fedora44)
OS_VARIANT="$(osinfo-query os | grep '^ fedora44' | awk '{print $1}')"
if [[ -z $OS_VARIANT ]]; then
OS_VARIANT="$(osinfo-query os | grep ' Fedora Linux ' | sort -n -t\| -k3 | tail -1 | awk '{print $1}')"
fi
IMAGE_URL="https://fedora.mirror.constant.com/fedora/linux/releases/44/Cloud/x86_64/images/Fedora-Cloud-Base-Generic-44-1.7.x86_64.qcow2"
IMAGE_CHECKSUM="$(curl --silent https://fedora.mirror.constant.com/fedora/linux/releases/44/Cloud/x86_64/images/Fedora-Cloud-44-1.7-x86_64-CHECKSUM | grep $(basename $IMAGE_URL) | grep SHA256 | awk '{print $NF}')"
;;
ubuntu2204)
OS_VARIANT="$(osinfo-query os | grep '^ ubuntu22.04' | awk '{print $1}')"
if [[ -z $OS_VARIANT ]]; then
OS_VARIANT="$(osinfo-query os | grep '^ ubuntu' | sort -n -t\| -k3 | tail -1 | awk '{print $1}')"
fi
IMAGE_URL="https://cloud-images.ubuntu.com/releases/jammy/release/ubuntu-22.04-server-cloudimg-amd64.img"
IMAGE_CHECKSUM="$(curl --silent https://cloud-images.ubuntu.com/releases/jammy/release/SHA256SUMS | grep $(basename $IMAGE_URL)| awk '{print $1}')"
;;
ubuntu2404)
OS_VARIANT="$(osinfo-query os | grep ' ^ubuntu24.04' | awk '{print $1}')"
if [[ -z $OS_VARIANT ]]; then
OS_VARIANT="$(osinfo-query os | grep '^ ubuntu' | sort -n -t\| -k3 | tail -1 | awk '{print $1}')"
fi
IMAGE_URL="https://cloud-images.ubuntu.com/releases/noble/release/ubuntu-24.04-server-cloudimg-amd64.img"
IMAGE_CHECKSUM="$(curl --silent https://cloud-images.ubuntu.com/releases/noble/release/SHA256SUMS | grep $(basename $IMAGE_URL)| awk '{print $1}')"
;;
ubuntu2504)
OS_VARIANT="$(osinfo-query os | grep '^ ubuntu25.04' | awk '{print $1}')"
if [[ -z $OS_VARIANT ]]; then
OS_VARIANT="$(osinfo-query os | grep '^ ubuntu' | sort -n -t\| -k3 | tail -1 | awk '{print $1}')"
fi
IMAGE_URL="https://cloud-images.ubuntu.com/releases/plucky/release/ubuntu-25.04-server-cloudimg-amd64.img"
IMAGE_CHECKSUM="$(curl --silent https://cloud-images.ubuntu.com/releases/plucky/release/SHA256SUMS | grep $(basename $IMAGE_URL)| awk '{print $1}')"
;;
ubuntu2510)
OS_VARIANT="$(osinfo-query os | grep '^ ubuntu25.10' | awk '{print $1}')"
if [[ -z $OS_VARIANT ]]; then
OS_VARIANT="$(osinfo-query os | grep '^ ubuntu' | sort -n -t\| -k3 | tail -1 | awk '{print $1}')"
fi
IMAGE_URL="https://cloud-images.ubuntu.com/releases/questing/release/ubuntu-25.10-server-cloudimg-amd64.img"
IMAGE_CHECKSUM="$(curl --silent https://cloud-images.ubuntu.com/releases/questing/release/SHA256SUMS | grep $(basename $IMAGE_URL)| awk '{print $1}')"
;;
ubuntu2604)
OS_VARIANT="$(osinfo-query os | grep '^ ubuntu26.04' | awk '{print $1}')"
if [[ -z $OS_VARIANT ]]; then
OS_VARIANT="$(osinfo-query os | grep '^ ubuntu' | sort -n -t\| -k3 | tail -1 | awk '{print $1}')"
fi
IMAGE_URL="https://cloud-images.ubuntu.com/releases/resolute/release/ubuntu-26.04-server-cloudimg-amd64.img"
IMAGE_CHECKSUM="$(curl --silent https://cloud-images.ubuntu.com/releases/resolute/release/SHA256SUMS | grep $(basename $IMAGE_URL)| awk '{print $1}')"
;;
arch)
OS_VARIANT="archlinux"
IMAGE_URL="https://geo.mirror.pkgbuild.com/images/latest/Arch-Linux-x86_64-cloudimg.qcow2"
IMAGE_CHECKSUM="$(curl --silent https://geo.mirror.pkgbuild.com/images/latest/Arch-Linux-x86_64-cloudimg.qcow2.SHA256 | awk '{print $1}')"
;;
alpine3-23)
OS_VARIANT="$(osinfo-query os | grep '^ alpinelinux3.23 ' | awk '{print $1}')"
if [[ -z $OS_VARIANT ]]; then
OS_VARIANT="$(osinfo-query os | grep '^ alpinelinux' | sort -V | tail -1 | awk '{print $1}')"
fi
IMAGE_URL="https://dl-cdn.alpinelinux.org/alpine/v3.23/releases/cloud/nocloud_alpine-3.23.2-x86_64-bios-cloudinit-r0.qcow2"
IMAGE_CHECKSUM="$(curl --silent ${IMAGE_URL}.sha512)"
checksum_type=sha512
shell="/bin/sh"
sudo_group="wheel"
# https://git.alpinelinux.org/aports/tree/community/cloud-init/README.Alpine?id=2eb6a8206c0af444b70e7ed2d8c3778f3fe82d6a#n379
cloud_init_users_custom="passwd: '*'
lock_passwd: false"
;;
*)
echo See supported OS list:
echo "$supported_os_list"
exit 1
;;
esac
downloaded_base_image=$VM_IMAGE_DIR/base/$os/${IMAGE_CHECKSUM}.qcow2
mkdir -p $(dirname $downloaded_base_image)
if [[ ! -e $downloaded_base_image ]]; then
echo Downloading latest base image...
wget --quiet --show-progress -O $downloaded_base_image $IMAGE_URL
if [[ $? -ne 0 ]]; then
echo "Failed to download $IMAGE_URL"
exit 1
else
if [[ $(${checksum_type}sum $downloaded_base_image | awk '{print $1}') != "$IMAGE_CHECKSUM" ]]; then
echo "Download completed, but checksum failed. deleting failed image..."
rm -f $downloaded_base_image
exit 1
fi
fi
else
if [[ $(${checksum_type}sum $downloaded_base_image | awk '{print $1}') != "$IMAGE_CHECKSUM" ]]; then
echo "Existing image doesnt match checksum, attempting to complete the download..."
wget --quiet --show-progress --continue -O $downloaded_base_image $IMAGE_URL
if [[ $? -ne 0 ]]; then
echo "Failed to download $IMAGE_URL"
exit 1
fi
else
echo "Already have the latest image for $os downloaded"
fi
fi
}
function create_disk() {
vm_image_file=${VM_IMAGE_DIR}/images/${hostname_to_build}.qcow2
if [[ ! -e $vm_image_file ]]; then
echo "Creating a qcow2 image file $vm_image_file that uses the latest cloud image $(basename ${IMAGE_URL}) as its base"
qemu-img create -b "${downloaded_base_image}" -f qcow2 -F qcow2 "${VM_IMAGE_DIR}/images/${hostname_to_build}.qcow2" "${disk_size}G"
else
echo "Image file already exists $vm_image_file"
exit 1
fi
}
function create_cloud_init_iso() {
mac_address=$(generate_mac_address)
# Create the cloud-init network-config file
echo "Creating network-config file $VM_IMAGE_DIR/init/network-config"
cat <<EOF > $VM_IMAGE_DIR/init/network-config
version: 2
ethernets:
eth0:
EOF
# If static IP is provided, use it; otherwise default to DHCP
if [[ -n "$ip_address" ]]; then
cat <<EOF >> $VM_IMAGE_DIR/init/network-config
dhcp4: false
match:
macaddress: "$mac_address"
set-name: eth0
addresses:
- $ip_address
routes:
- to: 0.0.0.0/0
via: $gateway
nameservers:
addresses: [$nameserver]
EOF
else
cat <<EOF >> $VM_IMAGE_DIR/init/network-config
dhcp4: true
EOF
fi
echo "Creating meta-data file $VM_IMAGE_DIR/init/meta-data"
cat > "$VM_IMAGE_DIR/init/meta-data" << EOF
instance-id: ${hostname_to_build}
local-hostname: ${hostname_to_build}
EOF
echo "Creating user-data file $VM_IMAGE_DIR/init/user-data"
cat > "$VM_IMAGE_DIR/init/user-data" << EOF
#cloud-config
users:
- name: $user
sudo: ["ALL=(ALL) NOPASSWD:ALL"]
groups: $sudo_group
shell: $shell
homedir: /home/$user
$cloud_init_users_custom
ssh_authorized_keys:
EOF
if [[ -n $ssh_pub_key_file ]]; then
echo "Adding keys from the public key file $ssh_pub_key_file to the user-data file"
while IFS= read -r key; do
echo " - $key" >> "$VM_IMAGE_DIR/init/user-data"
done < <(grep -v '^ *#' < "$ssh_pub_key_file")
fi
if [[ -n $github_ssh_keys ]]; then
echo "Adding keys from https://github.com/${github_user}.keys to the user-data file"
while IFS= read -r line; do
echo " - $line" >> "$VM_IMAGE_DIR/init/user-data"
done <<< "$github_ssh_keys"
fi
if [[ -n $user_data_file ]]; then
user_data_file_path=$VM_IMAGE_DIR/init/user-data.sh
# I've had some odd issues where simply smushing a standard bash script into the runcmd section of the user-data doesnt work, so here, we are copying the script file itself into the ISO, and then running it from there.
cp $user_data_file $user_data_file_path
chmod +x $user_data_file_path
echo "Setting $user_data_file to be run on first boot"
echo "runcmd:" >> $VM_IMAGE_DIR/init/user-data
echo " - mkdir -p /mnt/cdrom
- mount /dev/sr0 /mnt/cdrom
- /mnt/cdrom/user-data.sh
- umount /mnt/cdrom" >> $VM_IMAGE_DIR/init/user-data
fi
echo "Generating the cidata ISO file $VM_IMAGE_DIR/images/${hostname_to_build}-cidata.iso"
(
cd "$VM_IMAGE_DIR/init/"
genisoimage_output=$(genisoimage \
-output "$VM_IMAGE_DIR/images/${hostname_to_build}-cidata.img" \
-volid cidata \
-rational-rock \
-joliet \
user-data meta-data network-config $user_data_file_path 2>&1)
)
}
#
function virt_install() {
echo Running virt-install
virt-install \
--name="${hostname_to_build}" \
--network "bridge=${BRIDGE},model=virtio,mac=$mac_address" \
--import \
--disk "path=$vm_image_file,format=qcow2" \
--disk "path=$VM_IMAGE_DIR/images/${hostname_to_build}-cidata.img,device=cdrom" \
--ram="${ram}" \
--vcpus="${cpu}" \
--autostart \
--hvm \
--arch x86_64 \
--accelerate \
--check-cpu \
--os-variant $OS_VARIANT \
--force \
--watchdog=default \
--graphics vnc,listen=0.0.0.0 \
--noautoconsole \
--wait 0
if [[ $? -gt 0 ]]; then
echo Failed to deploy $hostname_to_build
exit 1
fi
}
#
if [[ ! -e $var_file ]]; then
# if no var file exists, create it with the defaults
set_defaults
fi
function generate_mac_address() {
printf '52:54:00:%02x:%02x:%02x\n' $((RANDOM%256)) $((RANDOM%256)) $((RANDOM%256))
}
#
################################################
check_required_commands
load_settings
#
while getopts ":h:c:r:d:i:g:n:p:o:ylV" o; do
case "${o}" in
h)
hostname_to_build=${OPTARG}
;;
c)
cpu=${OPTARG}
;;
r)
ram=$((${OPTARG}*1024))
;;
d)
disk_size=${OPTARG}
;;
i)
ip_address=${OPTARG}
;;
g)
gateway=${OPTARG}
;;
n)
nameserver=${OPTARG}
;;
p) # path
VM_IMAGE_DIR=${OPTARG}
;;
o)
os=${OPTARG}
;;
y)
force=true
;;
l)
list=true
;;
V)
echo $script_version
exit
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
mkdir -p "$VM_IMAGE_DIR"/{images,init,base}
#
if [[ $list == "true" ]]; then
echo "$supported_os_list"
exit
fi
#
if [[ -z "${hostname_to_build}" ]]; then
usage
fi
if [[ "${os}" == "random" ]]; then
os=$(echo "$supported_os_list" | grep . | sort -R | head -1)
fi
if [[ "${hostname_to_build}" == "random" ]]; then
generate_server_name
fi
#
validate_input
if [[ $force != "true" ]]; then
if ! ask "Are you sure you want to deploy the following VM:
username: $user
hostname: $hostname_to_build
os: $os
CPU cores: $cpu
RAM (in GB): $(($ram/1024))
disk size: $disk_size
network: $network_type
"; then
exit 2
fi
fi
#
cache_image
create_disk
create_cloud_init_iso
virt_install
echo Finished building $hostname_to_build