-
Notifications
You must be signed in to change notification settings - Fork 5
/
lightsail-k8s-installer.sh
1449 lines (1210 loc) · 41.4 KB
/
lightsail-k8s-installer.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
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
#
# @author Rio Astamal <[email protected]>
# @desc Script to automate Kubernetes installation on Amazon Lightsail instances
readonly LK8S_SCRIPT_NAME=$( basename "$0" )
LK8S_BASEDIR=$( cd -P -- "$( dirname "$0" )" && pwd -P )
LK8S_VERSION="1.1"
LC_CTYPE="C"
# Path to directory to store application outputs
[ ! -d "$LK8S_OUTPUT_DIR/.out" ] && LK8S_OUTPUT_DIR="$LK8S_BASEDIR/.out"
# Default config
# --------------
[ -z "$LK8S_CLOUDFORMATION_STACKNAME_PREFIX" ] && LK8S_CLOUDFORMATION_STACKNAME_PREFIX="lk8s"
[ -z "$LK8S_CONTROL_PLANE_NODE_PREFIX" ] && LK8S_CONTROL_PLANE_NODE_PREFIX="kube-cp"
[ -z "$LK8S_WORKER_NODE_PREFIX" ] && LK8S_WORKER_NODE_PREFIX="kube-worker"
[ -z "$LK8S_WORKER_LOAD_BALANCER_PREFIX" ] && LK8S_WORKER_LOAD_BALANCER_PREFIX="kube-worker-lb"
[ -z "$LK8S_POD_NETWORK_CIDR" ] && LK8S_POD_NETWORK_CIDR="10.244.0.0/16"
[ -z "$LK8S_NUMBER_OF_WORKER_NODES" ] && LK8S_NUMBER_OF_WORKER_NODES=2
[ -z "$LK8S_SSH_LIGHTSAIL_KEYPAIR_NAME" ] && LK8S_SSH_LIGHTSAIL_KEYPAIR_NAME="id_rsa"
[ -z "$LK8S_SSH_PRIVATE_KEY_FILE" ] && LK8S_SSH_PRIVATE_KEY_FILE="$HOME/.ssh/id_rsa"
[ -z "$LK8S_FIREWALL_SSH_ALLOW_CIDR" ] && LK8S_FIREWALL_SSH_ALLOW_CIDR="0.0.0.0/0"
[ -z "$LK8S_DRY_RUN" ] && LK8S_DRY_RUN="no"
[ -z "$LK8S_CONTROL_PLANE_PLAN" ] && LK8S_CONTROL_PLANE_PLAN="5_usd"
[ -z "$LK8S_WORKER_PLAN" ] && LK8S_WORKER_PLAN="5_usd"
[ -z "$LK8S_DEBUG" ] && LK8S_DEBUG="true"
# Currently only 1 control plane node supported
# Todo: Support High Availability Control Plane Cluster
LK8S_NUMBER_OF_CP_NODES=1
# Required tools to perform tasks
LK8S_REQUIRED_TOOLS="awk aws cat cut date jq sed ssh tr wc"
# See all available OS/Blueprint ID using: `aws lightsail get-blueprints`
# Only amazon_linux_2 is supported at the moment.
LK8S_CP_OS_ID="amazon_linux_2"
LK8S_WORKER_OS_ID="amazon_linux_2"
# Function to show the help message
lk8s_help()
{
echo "\
Usage: $0 [OPTIONS]
Where OPTIONS:
-a AZs specify list of Available Zones using AZs
-c CIDR specify pod network using CIDR
-d ID destroy installation id specified by ID
-h print this help and exit
-i ID specify installation id using ID
-m dry run mode, print CloudFormation template and exit
-r REGION specify region using REGION
-v print script version
-w NUM specify number of worker nodes using NUM
-u update the cluster by adding new worker nodes
----------------------- lightsail-k8s-installer -----------------------
lightsail-k8s-installer is a command line interface to bootstrap Kubernetes
cluster on Amazon Lightsail.
lightsail-k8s-installer is free software licensed under MIT. Visit the project
homepage at http://github.com/rioastamal/lightsail-k8s-installer."
}
lk8s_write_log()
{
_LOG_MESSAGE="$@"
_SYSLOG_DATE_STYLE="$( date +"%b %e %H:%M:%S" )"
# Date Hostname AppName[PID]: MESSAGE
printf "[%s LK8S]: %s\n" \
"$_SYSLOG_DATE_STYLE" \
"${_LOG_MESSAGE}">> "$LK8S_LOG_FILE"
}
lk8s_log()
{
[ "$LK8S_DEBUG" = "true" ] && printf "[LK8S]: %s\n" "$@"
lk8s_write_log "$@"
}
lk8s_log_waiting()
{
[ "$LK8S_DEBUG" = "true" ] && printf "\r[LK8S]: %s\033[K" "$@"
lk8s_write_log "$@"
}
lk8s_err() {
printf "[LK8S ERROR]: %s\n" "$@" >&2
lk8s_write_log "$@"
}
lk8s_init()
{
mkdir -p "$LK8S_OUTPUT_DIR"
[ -z "$LK8S_INSTALLATION_ID" ] && {
echo "Missing installation id. See -h for help." >&2
return 1
}
local _MISSING_TOOL="$( lk8s_missing_tool )"
[ ! -z "$_MISSING_TOOL" ] && {
echo "Missing tool: ${_MISSING_TOOL}. Make sure it is installed and available in your PATH." >&2
return 1
}
# See all available regions using CLI: `aws lightsail get-regions`
[ -z "$LK8S_REGION" ] && {
[ ! -z "$AWS_REGION" ] && LK8S_REGION=$AWS_REGION
[ -z "$AWS_REGION" ] && {
[ ! -z "$AWS_DEFAULT_REGION" ] && LK8S_REGION=$AWS_DEFAULT_REGION
[ -z "$AWS_DEFAULT_REGION" ] && LK8S_REGION="us-east-1"
}
}
export AWS_REGION=$LK8S_REGION
# The AZ list is the same with EC2
[ -z "$LK8S_AZ_POOL" ] && {
LK8S_AZ_POOL=""
for az in a b c
do
LK8S_AZ_POOL="${LK8S_AZ_POOL}${LK8S_REGION}${az} "
done
}
LK8S_CLOUDFORMATION_STACKNAME=$LK8S_CLOUDFORMATION_STACKNAME_PREFIX-$LK8S_INSTALLATION_ID
LK8S_CONTROL_PLANE_NODE_PREFIX=$LK8S_CONTROL_PLANE_NODE_PREFIX-$LK8S_CLOUDFORMATION_STACKNAME
LK8S_WORKER_NODE_PREFIX=$LK8S_WORKER_NODE_PREFIX-$LK8S_CLOUDFORMATION_STACKNAME
LK8S_WORKER_LOAD_BALANCER_PREFIX=$LK8S_WORKER_LOAD_BALANCER_PREFIX-$LK8S_CLOUDFORMATION_STACKNAME
local _LOG_SUFFIX="$( date +"%Y%m%d%H%M%S" )"
LK8S_LOG_FILE="${LK8S_OUTPUT_DIR}/${LK8S_REGION}-${LK8S_CLOUDFORMATION_STACKNAME}-${_LOG_SUFFIX}.log"
[ ! -r "$LK8S_SSH_PRIVATE_KEY_FILE" ] && {
printf "Missing SSH private key file: %s.\n" "$LK8S_SSH_PRIVATE_KEY_FILE" 2>&1
printf "Make sure it is exists and readble. You can set the location via LK8S_SSH_PRIVATE_KEY_FILE environment variable." 2>&1
return 1
}
([ $LK8S_NUMBER_OF_WORKER_NODES -lt 2 ] && [ "$LK8S_ACTION" = "install" ]) && {
echo "Number of worker nodes must be >= 2." >&2
return 1
}
([ $LK8S_NUMBER_OF_WORKER_NODES -lt 1 ] && [ "$LK8S_ACTION" = "update" ]) && {
echo "Number of worker nodes must be >= 1." >&2
return 1
}
LK8S_WORKER_NODE_RANDOM_IDS=""
for i in $( seq 1 $LK8S_NUMBER_OF_WORKER_NODES )
do
LK8S_WORKER_NODE_RANDOM_IDS="$( lk8s_gen_random_chars 6 ) ${LK8S_WORKER_NODE_RANDOM_IDS}"
done
LK8S_CONTROL_PLANE_NODE_RANDOM_IDS=""
for i in $( seq 1 $LK8S_NUMBER_OF_CP_NODES )
do
LK8S_CONTROL_PLANE_NODE_RANDOM_IDS="$( lk8s_gen_random_chars 6 ) ${LK8S_CONTROL_PLANE_NODE_RANDOM_IDS}"
done
return 0
}
lk8s_char_repeat()
{
# $1 -> char
# $2 -> number of repeat
for i in $( seq 1 $2 )
do
printf "%s" "$1"
done
}
lk8s_cp_node_user_data()
{
# Indendation is important here since it will used inside YAML
cat << 'EOF'
#!/bin/sh
## Disable SELinux
sudo setenforce 0
sudo sed -i 's/^SELINUX=enforcing$/SELINUX=permissive/' /etc/selinux/config
## Add Kubernetes repo
cat <<EOF_KUBE | sudo tee /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-\$basearch
enabled=1
gpgcheck=1
gpgkey=https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
exclude=kubelet kubeadm kubectl
EOF_KUBE
## Install Kubernetes Tools and Docker
sudo yum install -y docker kubelet kubeadm kubectl tc jq --disableexcludes=kubernetes
sudo systemctl enable --now docker
sudo systemctl enable --now kubelet
## Modify networking and Swappiness
cat <<EOF_SYS | sudo tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
vm.swappiness = 0
EOF_SYS
sudo sysctl --system
EOF
return 0
}
lk8s_worker_node_user_data()
{
lk8s_cp_node_user_data
return 0
}
lk8s_ssh_to_node()
{
local _NODE_IP=$1
# Remove the $1
shift
ssh -i $LK8S_SSH_PRIVATE_KEY_FILE -o ConnectTimeout=3 \
-o StrictHostKeyChecking=no -o LogLevel=error \
ec2-user@$_NODE_IP $@
}
lk8s_get_az_pool_index()
{
local _SEQUENCE=$1
local _NUMBER_OF_AZ=$( echo "$_AZ_POOL" | wc -w )
local _AZ_POOL_INDEX=$(( $_SEQUENCE % $_NUMBER_OF_AZ ))
[ $_AZ_POOL_INDEX -eq 0 ] && {
echo $_NUMBER_OF_AZ
return 0
}
echo $_AZ_POOL_INDEX
return 0
}
lk8s_cf_template_nodes()
{
while [ $# -gt 0 ]; do
case $1 in
--node-az-pool) local _NODE_AZ_POOL="$2"; shift ;;
--node-prefix) local _NODE_PREFIX="$2"; shift ;;
--number-of-nodes) local _NO_OF_NODES=$2; shift ;;
--random-ids) local _RANDOM_IDS="$2"; shift ;;
--node-type) local _NODE_TYPE="$2"; shift ;;
*) echo "Unrecognised option passed: $1" 2>&2; return 1;;
esac
shift
done
for i in $( seq 1 $_NO_OF_NODES )
do
local _AZ_POOL_INDEX=$( _AZ_POOL=$_NODE_AZ_POOL lk8s_get_az_pool_index $i )
local _AZ_ID=$( echo "$_NODE_AZ_POOL" | awk "{print \$${_AZ_POOL_INDEX}}" )
local _RANDOM_ID=$( echo $_RANDOM_IDS | awk "{print \$${i}}" )
[ "$_NODE_TYPE" = "control-plane" ] && _RESOURCE_NAME="ControlPlaneNode${_RANDOM_ID}"
[ "$_NODE_TYPE" = "worker" ] && _RESOURCE_NAME="WorkerNode${_RANDOM_ID}"
lk8s_cf_template_node --az-id "$_AZ_ID" \
--bundle-id "$LK8S_WORKER_BUNDLE_ID" \
--cf-stackname "$LK8S_CLOUDFORMATION_STACKNAME" \
--installation-id "$LK8S_INSTALLATION_ID" \
--instance-name "$_NODE_PREFIX-$_RANDOM_ID" \
--keypair-name "$LK8S_SSH_LIGHTSAIL_KEYPAIR_NAME" \
--node-type "$_NODE_TYPE" \
--resource-name "$_RESOURCE_NAME" \
--ssh-allow-cidr "$LK8S_FIREWALL_SSH_ALLOW_CIDR" \
--os-id "$LK8S_WORKER_OS_ID"
done
return 0
}
lk8s_cf_template_node()
{
while [ $# -gt 0 ]; do
case $1 in
--az-id) local _AZ_ID="$2"; shift ;;
--bundle-id) local _BUNDLE_ID="$2"; shift ;;
--cf-stackname) local _CF_STACKNAME="$2"; shift ;;
--installation-id) local _INSTALLATION_ID="$2"; shift ;;
--instance-name) local _INSTANCE_NAME="$2"; shift ;;
--keypair-name) local _KEYPAIR_NAME="$2"; shift ;;
--resource-name) local _RESOURCE_NAME="$2"; shift ;;
--ssh-allow-cidr) local _SSH_ALLOW_CIDR="$2"; shift ;;
--node-type) local _NODE_TYPE="$2"; shift ;;
--os-id) local _OS_ID="$2"; shift ;;
*) echo "Unrecognised option passed: $1" 2>&2; return 1;;
esac
shift
done
[ -z "$_KEYPAIR_NAME" ] && _KEYPAIR_NAME=$LK8S_SSH_LIGHTSAIL_KEYPAIR_NAME
[ "$_NODE_TYPE" = "worker" ] && {
local _NETWORKING_RULES="$(cat <<EOF
Ports:
- Protocol: tcp
FromPort: 22
ToPort: 22
Cidrs:
- $_SSH_ALLOW_CIDR
- FromPort: 80
ToPort: 80
Protocol: tcp
Cidrs:
- 172.26.0.0/16
- FromPort: 30000
ToPort: 32767
Protocol: tcp
Cidrs:
- 172.26.0.0/16
- FromPort: 10250
ToPort: 10250
Protocol: tcp
Cidrs:
- 172.26.0.0/16
EOF
)"
}
[ "$_NODE_TYPE" = "control-plane" ] && {
local _NETWORKING_RULES="$( cat <<EOF
Ports:
- Protocol: tcp
FromPort: 22
ToPort: 22
Cidrs:
- $_SSH_ALLOW_CIDR
- FromPort: 6443
ToPort: 6443
Protocol: tcp
Cidrs:
- 172.26.0.0/16
- FromPort: 2379
ToPort: 2380
Protocol: tcp
Cidrs:
- 172.26.0.0/16
- FromPort: 10250
ToPort: 10250
Protocol: tcp
Cidrs:
- 172.26.0.0/16
- FromPort: 10257
ToPort: 10257
Protocol: tcp
Cidrs:
- 172.26.0.0/16
- FromPort: 10259
ToPort: 10259
Protocol: tcp
Cidrs:
- 172.26.0.0/16
EOF
)"
}
cat <<EOF
$_RESOURCE_NAME:
Type: AWS::Lightsail::Instance
Properties:
AvailabilityZone: $_AZ_ID
BlueprintId: $_OS_ID
BundleId: $_BUNDLE_ID
KeyPairName: $_KEYPAIR_NAME
InstanceName: $_INSTANCE_NAME
Networking:
$_NETWORKING_RULES
Tags:
- Key: cf-$_CF_STACKNAME
- Key: lightsail-k8s-installer
- Key: type-$_NODE_TYPE-$_INSTALLATION_ID
- Key: installation-id-$_INSTALLATION_ID
- Key: installer
Value: lightsail-k8s-installer
- Key: cfstackname
Value: $_CF_STACKNAME
- Key: node-type
Value: $_NODE_TYPE
EOF
return 0
}
lk8s_cf_template_load_balancer_worker_nodes()
{
local _WORKER_INSTANCE_LIST=""
cat <<EOF
LoadBalancerWorker:
Type: AWS::Lightsail::LoadBalancer
Properties:
LoadBalancerName: $LK8S_WORKER_LOAD_BALANCER_PREFIX
IpAddressType: ipv4
InstancePort: 80
SessionStickinessEnabled: false
EOF
return 0
}
lk8s_cf_template_header()
{
echo "AWSTemplateFormatVersion: '2010-09-09'"
echo "Resources:"
return 0
}
lk8s_run_cloudformation()
{
# See all available Bundle ID using CLI: `aws lightsail get-bundles`
LK8S_CP_BUNDLE_ID="$( lk8s_is_package_valid $LK8S_CONTROL_PLANE_PLAN )" || {
lk8s_err "Control plane plan '$LK8S_CONTROL_PLANE_PLAN' is not valid"
return 1
}
LK8S_WORKER_BUNDLE_ID="$( lk8s_is_package_valid $LK8S_WORKER_PLAN )" || {
lk8s_err "Worker plan '$LK8S_WORKER_PLAN' is not valid"
return 1
}
[ "$LK8S_DRY_RUN" = "yes" ] && {
lk8s_is_region_and_az_valid && \
lk8s_cf_template_header && \
lk8s_cf_template_nodes \
--node-az-pool "$LK8S_AZ_POOL" \
--number-of-nodes "$LK8S_NUMBER_OF_CP_NODES" \
--random-ids "$LK8S_CONTROL_PLANE_NODE_RANDOM_IDS" \
--node-prefix "$LK8S_CONTROL_PLANE_NODE_PREFIX" \
--node-type "control-plane" && \
lk8s_cf_template_nodes \
--node-az-pool "$LK8S_AZ_POOL" \
--number-of-nodes "$LK8S_NUMBER_OF_WORKER_NODES" \
--random-ids "$LK8S_WORKER_NODE_RANDOM_IDS" \
--node-prefix "$LK8S_WORKER_NODE_PREFIX" \
--node-type "worker" && \
lk8s_cf_template_load_balancer_worker_nodes
return 1
}
local _ANSWER="no"
local _TITLE="lightsail-k8s-installer v${LK8S_VERSION}"
local _ANY_KEY=""
local _MONTHLY_COST=$( lk8s_get_monthly_estimated_cost )
local _HOURLY_COST=$( echo "$_MONTHLY_COST 30 24" | awk '{printf "%.2f", $1 / $2 / $3}' )
local _CP_PRICE=$( lk8s_get_control_plane_plan_price )
local _WORKER_PRICE=$( lk8s_get_worker_plan_price )
lk8s_char_repeat "-" $( echo $_TITLE | wc -c ) && echo
echo $_TITLE
lk8s_char_repeat "-" $( echo $_TITLE | wc -c ) && echo
cat <<EOF
This process will create Kubernetes cluster on Amazon Lightsail.
CloudFormation stack: $LK8S_CLOUDFORMATION_STACKNAME
Region: $LK8S_REGION
AZs worker pool: $LK8S_AZ_POOL
Resources: - $LK8S_NUMBER_OF_CP_NODES control plane node (plan: \$${_CP_PRICE})
- $LK8S_NUMBER_OF_WORKER_NODES worker nodes (plan: \$${_WORKER_PRICE})
- 1 load balancer (plan: \$18)
Estimated cost. : \$${_MONTHLY_COST}/month or \$${_HOURLY_COST}/hour
Lightsail SSH key pair: $LK8S_SSH_LIGHTSAIL_KEYPAIR_NAME
SSH private key file: $LK8S_SSH_PRIVATE_KEY_FILE
EOF
echo
printf "Press any key to continue: "
read _ANY_KEY
echo "This may take several minutes, please wait..."
echo "To view detailed log, run following command on another terminal:"
echo " tail -f $LK8S_LOG_FILE"
echo
lk8s_log "Checking region validity"
lk8s_is_region_and_az_valid || return 1
lk8s_log "Checking SSH key pair '$LK8S_SSH_LIGHTSAIL_KEYPAIR_NAME' in region '$LK8S_REGION'"
lk8s_is_ssh_keypair_valid || return 1
lk8s_log "Checking existing stack '${LK8S_CLOUDFORMATION_STACKNAME}'"
# Do not create when the stack already exists
aws cloudformation describe-stacks --stack-name=$LK8S_CLOUDFORMATION_STACKNAME >>$LK8S_LOG_FILE 2>&1 && {
lk8s_err "Stack already exists. Aborted!"
return 1
}
lk8s_log "Stack '${LK8S_CLOUDFORMATION_STACKNAME}' is not exists, good!"
# Validating template
local _TEMPLATE_OUT_FILE="$LK8S_OUTPUT_DIR/${LK8S_CLOUDFORMATION_STACKNAME}.yaml"
_TEMPLATE_OUT_FILE="$( lk8s_transform_to_windows_path "$_TEMPLATE_OUT_FILE" )"
( lk8s_cf_template_header && \
lk8s_cf_template_nodes \
--node-az-pool "$LK8S_AZ_POOL" \
--number-of-nodes "$LK8S_NUMBER_OF_CP_NODES" \
--random-ids "$LK8S_CONTROL_PLANE_NODE_RANDOM_IDS" \
--node-prefix "$LK8S_CONTROL_PLANE_NODE_PREFIX" \
--node-type "control-plane" && \
lk8s_cf_template_nodes \
--node-az-pool "$LK8S_AZ_POOL" \
--number-of-nodes "$LK8S_NUMBER_OF_WORKER_NODES" \
--random-ids "$LK8S_WORKER_NODE_RANDOM_IDS" \
--node-prefix "$LK8S_WORKER_NODE_PREFIX" \
--node-type "worker" && \
lk8s_cf_template_load_balancer_worker_nodes ) > $_TEMPLATE_OUT_FILE && \
aws cloudformation validate-template \
--template-body file://$_TEMPLATE_OUT_FILE >> $LK8S_LOG_FILE 2>&1 || {
lk8s_err "CloudFormation generated template is not valid. Aborted!"
return 1
}
( lk8s_cf_template_header && \
lk8s_cf_template_nodes \
--node-az-pool "$LK8S_AZ_POOL" \
--number-of-nodes "$LK8S_NUMBER_OF_CP_NODES" \
--random-ids "$LK8S_CONTROL_PLANE_NODE_RANDOM_IDS" \
--node-prefix "$LK8S_CONTROL_PLANE_NODE_PREFIX" \
--node-type "control-plane" && \
lk8s_cf_template_nodes \
--node-az-pool "$LK8S_AZ_POOL" \
--number-of-nodes "$LK8S_NUMBER_OF_WORKER_NODES" \
--random-ids "$LK8S_WORKER_NODE_RANDOM_IDS" \
--node-prefix "$LK8S_WORKER_NODE_PREFIX" \
--node-type "worker" && \
lk8s_cf_template_load_balancer_worker_nodes ) | \
aws cloudformation create-stack \
--stack-name="$LK8S_CLOUDFORMATION_STACKNAME" \
--template-body file://$_TEMPLATE_OUT_FILE >> $LK8S_LOG_FILE 2>&1
local STACK_STATUS=""
local _WAIT_COUNTER=1
while [ "$STACK_STATUS" != "CREATE_COMPLETE" ]
do
lk8s_log_waiting "Waiting stack '$LK8S_CLOUDFORMATION_STACKNAME' to be ready$( lk8s_char_repeat '.' $_WAIT_COUNTER )"
STACK_STATUS="$( aws cloudformation describe-stacks \
--stack-name="$LK8S_CLOUDFORMATION_STACKNAME" 2>>$LK8S_LOG_FILE | \
jq -r '.Stacks[0].StackStatus' )"
[ $_WAIT_COUNTER -ge 3 ] && _WAIT_COUNTER=0
_WAIT_COUNTER=$(( $_WAIT_COUNTER + 1 ))
sleep 2
done
echo
lk8s_log "Stack '$LK8S_CLOUDFORMATION_STACKNAME' is ready"
local _CP_NODE_NAME="$LK8S_CONTROL_PLANE_NODE_PREFIX-"$( echo "$LK8S_CONTROL_PLANE_NODE_RANDOM_IDS" | awk '{print $1}' )
lk8s_run_post_command_control_plance_nodes && \
lk8s_run_post_command_worker_node --cp-node-name "$_CP_NODE_NAME" && \
lk8s_deploy_sample_app && \
lk8s_attach_load_balancer_to_worker_node && \
lk8s_print_installation_info
return 0
}
lk8s_update_cloudformation()
{
# See all available Bundle ID using CLI: `aws lightsail get-bundles`
LK8S_CP_BUNDLE_ID="$( lk8s_is_package_valid $LK8S_CONTROL_PLANE_PLAN )" || {
lk8s_err "Control plane plan '$LK8S_CONTROL_PLANE_PLAN' is not valid"
return 1
}
LK8S_WORKER_BUNDLE_ID="$( lk8s_is_package_valid $LK8S_WORKER_PLAN )" || {
lk8s_err "Worker plan '$LK8S_WORKER_PLAN' is not valid"
return 1
}
lk8s_log_waiting "Checking region validity" >&2
lk8s_is_region_and_az_valid || return 1
lk8s_log_waiting "Checking existing stack '$LK8S_CLOUDFORMATION_STACKNAME'" >&2
aws cloudformation describe-stacks --stack-name=$LK8S_CLOUDFORMATION_STACKNAME >>$LK8S_LOG_FILE 2>&1 || {
lk8s_err "Stack not exists. Aborted!"
return 1
}
local _ANSWER="no"
local _TITLE="lightsail-k8s-installer v${LK8S_VERSION}"
local _ANY_KEY=""
local _WORKER_PRICE=$( lk8s_get_worker_plan_price )
# Remove last 3 lines from template since it just a identifier
local _CURRENT_CF_TEMPLATE="$(
_TPL="$( aws cloudformation get-template --stack-name "$LK8S_CLOUDFORMATION_STACKNAME" --output text )" && \
_LINE="$(( $( echo "$_TPL" | wc -l ) - 3 ))" && \
echo "$_TPL" | head -n $_LINE
)"
local _WORKER_TEMPLATE="$(
lk8s_cf_template_nodes \
--node-az-pool "$LK8S_AZ_POOL" \
--number-of-nodes "$LK8S_NUMBER_OF_WORKER_NODES" \
--random-ids "$LK8S_WORKER_NODE_RANDOM_IDS" \
--node-prefix "$LK8S_WORKER_NODE_PREFIX" \
--node-type "worker"
)"
local _NEW_CF_TEMPLATE="$_CURRENT_CF_TEMPLATE
$_WORKER_TEMPLATE
"
[ "$LK8S_DRY_RUN" = "yes" ] && {
echo "$_NEW_CF_TEMPLATE"
return 0
}
echo -en "\r\033[2K" >&2
lk8s_char_repeat "-" $( echo $_TITLE | wc -c ) && echo
echo $_TITLE
lk8s_char_repeat "-" $( echo $_TITLE | wc -c ) && echo
cat <<EOF
This process will update your Kubernetes cluster on Amazon Lightsail.
CloudFormation stack: $LK8S_CLOUDFORMATION_STACKNAME
Region: $LK8S_REGION
AZs worker pool: $LK8S_AZ_POOL
New resources: $LK8S_NUMBER_OF_WORKER_NODES worker node(s) (plan: \$${_WORKER_PRICE})
Lightsail SSH key pair: $LK8S_SSH_LIGHTSAIL_KEYPAIR_NAME
SSH private key file: $LK8S_SSH_PRIVATE_KEY_FILE
EOF
echo
printf "Press any key to continue: "
read _ANY_KEY
echo "This may take several minutes, please wait..."
echo "To view detailed log, run following command on another terminal:"
echo " tail -f $LK8S_LOG_FILE"
echo
lk8s_log "Checking SSH key pair '$LK8S_SSH_LIGHTSAIL_KEYPAIR_NAME' in region '$LK8S_REGION'"
lk8s_is_ssh_keypair_valid || return 1
# Apply change set
local _NOW="$( date +"%Y%m%d%H%M%S" )"
local _CHANGE_SET_NAME=$LK8S_WORKER_NODE_PREFIX-$_NOW
local _NEW_CF_TEMPLATE_FILE=$LK8S_OUTPUT_DIR/${LK8S_CLOUDFORMATION_STACKNAME}-update.yaml
_NEW_CF_TEMPLATE_FILE="$( lk8s_transform_to_windows_path "$_NEW_CF_TEMPLATE_FILE" )"
lk8s_log "Creating CloudFormation change set '$_CHANGE_SET_NAME' for new worker node(s)"
echo "$_NEW_CF_TEMPLATE" > "$_NEW_CF_TEMPLATE_FILE"
aws cloudformation create-change-set \
--stack-name $LK8S_CLOUDFORMATION_STACKNAME \
--change-set-name $_CHANGE_SET_NAME \
--template-body file://$_NEW_CF_TEMPLATE_FILE >>$LK8S_LOG_FILE 2>&1 || {
lk8s_err "Failed to creating change set '$_CHANGE_SET_NAME'"
return 1
}
local _CHANGE_SET_STATUS=""
local _WAIT_COUNTER=1
while [ "$_CHANGE_SET_STATUS" != "CREATE_COMPLETE" ]
do
lk8s_log_waiting "Waiting change set '$_CHANGE_SET_NAME' to be ready$( lk8s_char_repeat '.' $_WAIT_COUNTER )"
_CHANGE_SET_STATUS="$( aws cloudformation describe-change-set \
--stack-name "$LK8S_CLOUDFORMATION_STACKNAME" \
--change-set-name "$_CHANGE_SET_NAME" 2>>$LK8S_LOG_FILE | \
jq -r '.Status' )"
[ $_WAIT_COUNTER -ge 3 ] && _WAIT_COUNTER=0
_WAIT_COUNTER=$(( $_WAIT_COUNTER + 1 ))
sleep 1
done
echo
aws cloudformation execute-change-set \
--stack-name "$LK8S_CLOUDFORMATION_STACKNAME" \
--change-set-name "$_CHANGE_SET_NAME" >>$LK8S_LOG_FILE >&1 || {
lk8s_err "Failed to execute change set '$_CHANGE_SET_NAME'"
return 1
}
local STACK_STATUS=""
local _WAIT_COUNTER=1
while [ "$STACK_STATUS" != "UPDATE_COMPLETE" ]
do
lk8s_log_waiting "Updating stack '$LK8S_CLOUDFORMATION_STACKNAME'$( lk8s_char_repeat '.' $_WAIT_COUNTER )"
STACK_STATUS="$( aws cloudformation describe-stacks \
--stack-name="$LK8S_CLOUDFORMATION_STACKNAME" 2>>$LK8S_LOG_FILE | \
jq -r '.Stacks[0].StackStatus' )"
[ $_WAIT_COUNTER -ge 3 ] && _WAIT_COUNTER=0
_WAIT_COUNTER=$(( $_WAIT_COUNTER + 1 ))
sleep 2
done
local _GET_INSTANCES_OUTPUT="$( aws lightsail get-instances --no-paginate 2>>$LK8S_LOG_FILE )"
local _CP_NODE_NAME=$(
echo "$_GET_INSTANCES_OUTPUT" | \
jq -r ".instances | map(select(any(.tags[]; .key==\"type-control-plane-$LK8S_INSTALLATION_ID\"))) | .[0].name"
)
lk8s_run_post_command_worker_node --cp-node-name "$_CP_NODE_NAME" && \
lk8s_attach_load_balancer_to_worker_node && {
local _CP_NODE_IP=$(
echo "$_GET_INSTANCES_OUTPUT" | \
jq -r ".instances | map(select(any(.tags[]; .key==\"type-control-plane-$LK8S_INSTALLATION_ID\"))) | .[0].publicIpAddress"
)
lk8s_wait_for_kubelet_worker_to_be_ready "$_CP_NODE_IP"
lk8s_log "Kubernetes nodes info:"
lk8s_ssh_to_node $_CP_NODE_IP kubectl get nodes
echo
lk8s_log "update COMPLETED."
}
return 0
}
lk8s_run_post_command_control_plance_nodes()
{
for i in $( seq 1 $LK8S_NUMBER_OF_CP_NODES )
do
local _NODE_NAME="$LK8S_CONTROL_PLANE_NODE_PREFIX"-$( echo $LK8S_CONTROL_PLANE_NODE_RANDOM_IDS | awk "{print \$${i}}" )
lk8s_wait_for_node_to_be_ready $_NODE_NAME
local _NODE_IP="$( aws lightsail get-instance --instance-name=$_NODE_NAME 2>>$LK8S_LOG_FILE \
| jq -r .instance.publicIpAddress )"
lk8s_log "Running init scripts on control plane node '${_NODE_NAME}'"
local _INIT_SCRIPTS="$( lk8s_cp_node_user_data )"
echo "$_INIT_SCRIPTS" >> $LK8S_LOG_FILE
echo "$_INIT_SCRIPTS" | lk8s_ssh_to_node $_NODE_IP sudo -u ec2-user bash >> $LK8S_LOG_FILE 2>&1
lk8s_log "Installing Kubernetes control plane on node '${_NODE_NAME}'"
local _KUBERNETES_INSTALL_CMD="$( cat <<EOF
[ "\$( hostname )" != "$_NODE_NAME" ] && {
sudo hostnamectl set-hostname $_NODE_NAME
}
[ ! -f /etc/kubernetes/admin.conf ] && {
sudo kubeadm init --pod-network-cidr=$LK8S_POD_NETWORK_CIDR \
--ignore-preflight-errors=NumCPU,Mem
}
[ ! -d \$HOME/.kube ] && (
mkdir -p \$HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf \$HOME/.kube/config
sudo chown \$(id -u):\$(id -g) \$HOME/.kube/config
)
CP_NODE_STATUS="\$( kubectl get nodes --no-headers | awk '{print \$2}' )"
[ "\$CP_NODE_STATUS" = "NotReady" ] && {
curl -s -L https://github.com/flannel-io/flannel/releases/latest/download/kube-flannel.yml | \
sed 's#10.244.0.0/16#$LK8S_POD_NETWORK_CIDR#' | kubectl apply -f -
}
EOF
)"
echo "$_KUBERNETES_INSTALL_CMD" >> $LK8S_LOG_FILE
echo "$_KUBERNETES_INSTALL_CMD" | lk8s_ssh_to_node $_NODE_IP sudo -u ec2-user bash >> $LK8S_LOG_FILE 2>&1
done
return 0
}
lk8s_run_post_command_worker_node()
{
while [ $# -gt 0 ]; do
case $1 in
--cp-node-name) local _CP_NODE_NAME="$2"; shift ;;
*) echo "Unrecognised option passed: $1" 2>&2; return 1;;
esac
shift
done
for i in $( seq 1 $LK8S_NUMBER_OF_WORKER_NODES )
do
local _NODE_NAME="$LK8S_WORKER_NODE_PREFIX"-"$( echo $LK8S_WORKER_NODE_RANDOM_IDS | awk "{print \$${i}}" )"
lk8s_wait_for_node_to_be_ready $_NODE_NAME
local _NODE_IP="$( aws lightsail get-instance --instance-name=$_NODE_NAME | jq -r .instance.publicIpAddress )"
lk8s_log "Running init scripts on worker node '${_NODE_NAME}'"
local _INIT_SCRIPTS="$( lk8s_worker_node_user_data )"
echo "$_INIT_SCRIPTS" >> $LK8S_LOG_FILE
echo "$_INIT_SCRIPTS" | lk8s_ssh_to_node $_NODE_IP sudo -u ec2-user bash >> $LK8S_LOG_FILE 2>&1
local _JOIN_CMD="$( lk8s_gen_join_command --cp-node-name "$_CP_NODE_NAME" )"
local _KUBERNETES_WORKER_CMD="$(cat <<EOF
[ "\$( hostname )" != "$_NODE_NAME" ] && {
sudo hostnamectl set-hostname $_NODE_NAME
}
sudo $_JOIN_CMD
EOF
)"
lk8s_log "Joining worker node '$_NODE_NAME' to control plane"
echo "$_KUBERNETES_WORKER_CMD" >> $LK8S_LOG_FILE
echo "$_KUBERNETES_WORKER_CMD" | lk8s_ssh_to_node $_NODE_IP sudo -u ec2-user bash >> $LK8S_LOG_FILE 2>&1
done
return 0
}
lk8s_attach_load_balancer_to_worker_node()
{
local _INSTANCE_NAMES=""
local _RANDOM_ID=""
for _RANDOM_ID in $( printf "$LK8S_WORKER_NODE_RANDOM_IDS" )
do
local _NAME="$LK8S_WORKER_NODE_PREFIX-$_RANDOM_ID"
_INSTANCE_NAMES="$_INSTANCE_NAMES $_NAME"
done
_INSTANCE_NAMES=$( printf "%s" "$_INSTANCE_NAMES" | awk '{$1=$1;print}' )
lk8s_log "Attaching worker nodes to Lightsail Load Balancer"
local _ATTACH_CMD="$( printf "aws lightsail attach-instances-to-load-balancer \\
--load-balancer-name %s \\
--instance-names %s
" "$LK8S_WORKER_LOAD_BALANCER_PREFIX" "$_INSTANCE_NAMES" )"
eval "$_ATTACH_CMD" >> $LK8S_LOG_FILE 2>&1
return 0
}
lk8s_print_installation_info()
{
local _NODE_NAME="$LK8S_CONTROL_PLANE_NODE_PREFIX"-$( echo $LK8S_CONTROL_PLANE_NODE_RANDOM_IDS | awk '{print $1}' )
local _CONTROL_PLANE_IP=$( aws lightsail get-instance --instance-name=$_NODE_NAME | jq -r .instance.publicIpAddress )
local _LB_URL=$( aws lightsail get-load-balancer --load-balancer-name $LK8S_WORKER_LOAD_BALANCER_PREFIX | jq -r '.loadBalancer.dnsName' )
local _KUBERNETES_INFO="$( lk8s_ssh_to_node $_CONTROL_PLANE_IP kubectl get nodes,services,deployments,pods )"
local _BACKSLASH=$( printf '%b' '\134' ) # backslash
lk8s_log "Your Kubernetes installation info:
$_KUBERNETES_INFO
Accessing Control Plane via SSH:
ssh ec2-user@$_CONTROL_PLANE_IP
Your app are available via load balancer:
http://$_LB_URL
You can view detailed installation log at:
$LK8S_LOG_FILE
To delete sample app run following on Control plane:
kubectl get services,deployments --no-headers -o name \\
-l cfstackname=$LK8S_CLOUDFORMATION_STACKNAME | xargs kubectl delete
"
echo
lk8s_log "Installation COMPLETED."
return 0
}
lk8s_gen_join_command()
{
while [ $# -gt 0 ]; do
case $1 in
--cp-node-name) local _NODE_NAME="$2"; shift ;;
*) echo "Unrecognised option passed: $1" 2>&2; return 1;;
esac
shift
done
local _NODE_IP="$( aws lightsail get-instance --instance-name=$_NODE_NAME | jq -r .instance.publicIpAddress )"
lk8s_ssh_to_node $_NODE_IP kubeadm token create --print-join-command
return 0
}
lk8s_gen_sample_configuration_deployment()
{
local _NUMBER_OF_REPLICAS=$(( $LK8S_NUMBER_OF_WORKER_NODES * 2 ))
local _YAML_DEPLOYMENT="$( cat <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
name: http-echo-deployment
labels:
app: http-echo
cfstackname: $LK8S_CLOUDFORMATION_STACKNAME
spec:
replicas: $_NUMBER_OF_REPLICAS
selector:
matchLabels:
app: http-echo
template:
metadata:
labels:
app: http-echo
action: auto-label-node
cfstackname: $LK8S_CLOUDFORMATION_STACKNAME
spec:
containers:
- name: http-echo
image: hashicorp/http-echo
args:
- |-
-text=Node: \$(MY_NODE_NAME)
IP: \$(MY_HOST_IP)
--
Pod: \$(MY_POD_NAME)
IP: \$(MY_POD_IP)
- "-listen=:80"
ports:
- containerPort: 80
env:
- name: MY_NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
- name: MY_HOST_IP
valueFrom:
fieldRef:
fieldPath: status.hostIP
- name: MY_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: MY_POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
EOF
)"
local _YAML_SERVICES=""
for i in $( seq 1 $LK8S_NUMBER_OF_WORKER_NODES )
do
local _NODE_NAME="$LK8S_WORKER_NODE_PREFIX"-$( echo $LK8S_WORKER_NODE_RANDOM_IDS | awk "{print \$${i}}" )
local _NODE_PRIVATE_IP="$( aws lightsail get-instance --instance-name=$_NODE_NAME | jq -r .instance.privateIpAddress )"
local _TMP="$( cat <<EOF
---
apiVersion: v1
kind: Service
metadata:
name: http-echo-svc-$_NODE_NAME
labels:
app: http-echo
cfstackname: $LK8S_CLOUDFORMATION_STACKNAME
spec:
selector:
app: http-echo
node: $_NODE_NAME
ports:
- protocol: TCP
port: 80
targetPort: 80
type: ClusterIP
externalIPs:
- $_NODE_PRIVATE_IP
EOF
)"
_YAML_SERVICES="${_YAML_SERVICES}
${_TMP}"
done
printf "%s\n" "$_YAML_DEPLOYMENT"
printf "%s\n" "$_YAML_SERVICES"
printf "Kubernetes YAML deployment\n%s\n\%s" "$_YAML_DEPLOYMENT" "$_YAML_SERVICES" >> $LK8S_LOG_FILE
return 0
}
lk8s_gen_cloudformation_new_worker_node()
{
lk8s_cf_template_header && \
lk8s_cf_template_control_plane_nodes && \
lk8s_cf_template_worker_nodes
}
lk8s_gen_random_chars()
{
local _LENGTH=$1
tr -dc 'a-z0-9' </dev/urandom | head -c $_LENGTH; echo
return 0
}