-
Notifications
You must be signed in to change notification settings - Fork 0
/
compose2manifests.sh
executable file
·1729 lines (1556 loc) · 61.4 KB
/
compose2manifests.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/bash
# 24/10/21 blanchet<at>abes.fr
# Script de conversion d'un fichier docker-compose.yaml en manifests k8s
# Génère pour chacun des services ces manifest: deploy, services, configMap, secret, persistentVolumeClaim
# Nécessite les paquets jq, yq, jc, moreutils, docker-compose, kompose
# Usage:
# ./compose2manifests.sh [ prod || test || dev || local ] [ appli_name ] [default || '' || secret || env_file | help] [kompose] [helm]\n"
help () {
echo -e "usage: ./compose2manifests.sh [ prod || test || dev || local ] [ appli_name ] [default || '' || secret || env_file | copy | help] [kompose] [helm]\n"
echo -e "dev|test|prod: \tenvironnement sur lequel récupérer le .env. Local: fournir manuellement les '.env' et 'docker-compose.yml'"
echo -e "appli_name: \t\tnom de l'application à convertir"
echo -e "default or '' : \tGenerates cleaned appli.yml compose file to plain k8s manifests "
echo -e "env_file: \t\tGenerates cleaned advanced appli.yml with migrating plain 'environment' \n\t\t\tto 'env_file' statement, will generate k8s \"configmaps\" for common vars and \"secrets\" for vars containing 'PASSWORD' or 'KEY' as keyword"
echo -e "copy: \t\t only run PVCs copy staff"
echo -e "kompose: \t\tConverts appli.yml into plain k8s manifests ready to be deployed with \n\t\t\t'kubectl apply -f *.yaml"
echo -e "helm: \t\t\tKompose option that generates k8s manifest into helm skeleton for appli.yml\n"
echo -e "example: ./compose2manifests.sh local item env_file kompose\n"
echo -e "example: ./compose2manifests.sh prod qualimarc default kompose helm\n"
echo -e "A simple video usecase is available at: https://vimeo.com/1022133270/90cfd9e0a7\n"
echo -e "A building context video usecase is available at: https://vimeo.com/1037464417"
exit 1
}
source functions.sh
ENV=$1
NAME=$2
VARS_TYPE=$3
KOMPOSE=$4
PROVIDER=${5:-kubernetes}
HELM=$6
# RED="31"
# GREEN="32"
MAGENTA="\e[35m"
GREEN="\e[92m"
YELLOW="\e[93m"
BLUE="\e[94m"
RED="\e[31m"
CYAN="\e[36m"
BOLDGREEN="\e[1;${GREEN}m"
ITALICRED="\e[3;${RED}m"
ENDCOLOR="\e[0m"
FAINT="\e[2m"
BOLD="\e[1m"
ITALICS="\e[3m"
case $NAME in
'' | help | --help)
help;;
*)
;;
esac
case $VARS_TYPE in
default | '' | secret | env_file | copy)
;;
*)
help;;
esac
blue () {
echo -e "${BLUE}$1${ENDCOLOR}"
}
red () {
echo -e "${RED}$1${ENDCOLOR}"
}
faint () {
echo -e "${FAINT}$1${ENDCOLOR}"
}
italics () {
echo -e "${ITALICS}$1${ENDCOLOR}"
}
bold () {
echo -e "${BOLD}$1${ENDCOLOR}"
}
step () {
echo -e "\n\n"${YELLOW}################################################################################################################################${ENDCOLOR}"
${YELLOW}STEP $1: $2${ENDCOLOR}"
}
title () {
echo -e "\n${GREEN}$1> ##################################################${ENDCOLOR}
${GREEN}############ $2 ${ENDCOLOR}
${GREEN}#######################################################${ENDCOLOR}"
}
message () {
if [ $(echo $?) = "0" ];
then
echo -e "${BLUE}...OK${ENDCOLOR}";
else echo -e "${RED}echec!!!${ENDCOLOR}";
exit 1;
fi
}
calc(){ awk "BEGIN { print $*}"; }
step "1" "Project Initialization........"
title "1.1" "Cleaning working dir"
if [ -f ./okd ]
then rm -rf okd
fi
# Check potential previous existent sshfs mount
sshfs=$( mount | grep sshfs )
if [ -n "$sshfs" ]
then
echo -e "There is one active sshfs mount, please unmount it before going on: \n"
blue "$sshfs"
exit 1
fi
shopt -s extglob
rm -rf !(.env|docker-compose.yml|*.sh|.git|*.md|*.py|documentation|.|..)
message
if [ "$VARS_TYPE" = "clean" ]; then
echo "Cleaned Wordir";
exit;
fi
echo -e ""
# echo "1.2> #################### Installation des pré-requis ####################"
title "1.2" "Installation of pre-required features"
install_bin () {
if ! [ -f /usr/local/bin/$1 ] && ! [ -f /usr/bin/$1 ];then
case $1 in
jq)
BIN="jqlang/jq/releases/latest/download/jq-linux-amd64";;
yq)
BIN="mikefarah/yq/releases/latest/download/yq_linux_amd64";;
docker-compose)
BIN="docker/compose/releases/latest/download/docker-compose-linux-x86_64";;
kompose)
BIN="kubernetes/kompose/releases/download/v1.28.0/kompose-linux-amd64";;
oc)
wget -q okd-project/okd/releases/download/4.G1263.0-0.okd-2023-02-18-033438/openshift-client-linux-4.12.0-0.okd-2023-02-18-033438.tar.gz \
-O /usr/local/bin/ | \
tar xzf -
chmod +x {kubectl,oc};;
jc)
wget -q https://github.com/kellyjonbrazil/jc/releases/download/v1.25.3/jc-1.25.3-linux-x86_64.tar.gz \
-O /usr/local/bin/ | \
tar xzf -
chmod +x jc;;
*)
;;
esac
echo "Installing $(blue $1)......................................."
sudo wget -q https://github.com/${BIN} -O /usr/local/bin/$1 && sudo chmod +x /usr/local/bin/$1
fi
if ! [ -f /usr/bin/sponge ];then
echo "Installing sponge......................................."
case $(cat /etc/os-release | grep ID_LIKE) in \
*debian*) \
apt install moreutils -y;; \
*rhel*) \
if [[ "$(cat /etc/os-release | grep VERSION_ID)" =~ .*8.* ]];then
dnf config-manager --set-enabled powertools powertools
else
dnf config-manager --set-enabled powertools crb
fi
dnf -q install moreutils -y;; \
*) \
echo "Not supported plateform!" \
exit 1;; \
esac
fi
case $1 in
jq|yq) $1 --version;;
kompose) echo "kompose $($1 version)";;
jc) $1 -v |head -1;;
*) $1 version;;
esac
}
for i in jq yq docker-compose kompose oc jc; do install_bin $i; done
echo -ne "Application to deploy: "
blue \"$NAME\"
namespace=$(oc config view --minify -o 'jsonpath={..namespace}')
api=$(oc config view --minify -o 'jsonpath={..server}')
echo -ne "Cluster k8s: "
blue $api
echo -ne "Namespace in use: "
blue "\"$namespace\""
echo -e "A video usecase is available at: https://vimeo.com/1022133270/90cfd9e0a7\n"
case $1 in
test|dev|prod)
echo -e "You will deploy appli $(blue \"$NAME\") from the Docker $(blue \"$1\") platform to\n$(blue \"$api\") to $(blue \"$PROVIDER\") cluster in the $(blue \"$namespace\") namespace.\""
;;
local)
echo -e "You will deploy appli $(blue \"$NAME\") from a docker-compose.yml file and a .env file (provided by yourself) $(blue \"$api\") to $(blue \"$PROVIDER\") cluster in the $(blue \"$namespace\") namespace."
;;
*)
echo "Bad arguments"
exit;;
esac
if [[ $(echo $namespace | grep $NAME > /dev/null && echo $?) != 0 ]];
then
echo -e "${YELLOW}!! Warning !! ${ENDCOLOR}: current OKD namespace $(blue \"$namespace\") may not correspond to the appli $(blue \"$NAME\") you are about to deploy.\n"
fi
echo "################################################################################################################################"
echo -e ""
prod_test_dev() {
if [[ "$ENV" == "prod" ]] || [[ "$ENV" == "test" ]] || [[ "$ENV" == "dev" ]];
then
$*
return 7
fi
}
is_empty_project() {
project=${project:-$namespace}
test_project=$(oc get all -n $project -o json|jq '(if .items==[] then false else true end)')
if [ "$test_project" != "false" ]
then
read -p "$(italics "?? Project $project is not empty. Do you want to erase all resources? ..............$(faint "[n]")"): " yn
yn=${yn:-n}
if [ "$yn" = y ]
then
oc delete project $project
fi
fi
oc new-project $project >/dev/null
echo -e "Setting SCC anyuid to default SA.......................................\n"
oc adm policy add-scc-to-user anyuid -z default
}
create_project() {
oc project
while true;
do
read -p "$(italics "?? Would you like to create a new project? (y/n)....................................$(faint "[y]")"): " yn
yn=${yn:-y}
case $yn in
[Yy]* )
read -p "$(italics "?? Enter the name of the project $(faint "[$namespace]")....................................:") " project
namespace=${project:-$namespace}
break;;
[Nn]* )
break;;
* ) echo "Please answer yes or no.";;
esac
done
is_empty_project
oc project $project
echo -e ""
}
set_ssh_key() {
if [[ $( ls ~/.ssh | grep "id" ) == '' ]]
then
read -p "$(italics "?? No pub keys have been found. Do you want to generate? $(faint "[y]")"): " yn3
yn3=${yn3:-y}
case $yn3 in
[Yy]* )
ssh-keygen;;
[Nn]* )
italics "You must first install some pub key before using this script"
exit;;
esac
else
if [ -z "$key" ]; then
echo -e "Here are the available public keys in your home directory:"
for k in $(ls ~/.ssh/ |grep pub|cut -d"." -f1); do blue $k; done
read -p "$(italics "?? Which one do you want to use to connect to your Docker hosts? $(faint "[id_rsa]")"): " key
key=${key:-id_rsa}
blue $key
fi
fi
}
testing_ssh() {
echo "Checking ssh connectivity to Docker hosts to bind ...."
for i in $docker_hosts
do
SSH=$(ssh -q -o "BatchMode=yes" -o "ConnectTimeout=3" root@${i}.${domain} "echo 2>&1" && echo "OK" )
if [[ $(echo $SSH) == "OK" ]]
then
echo "Connexion to root@${i}.${domain} ........... $(blue OK)"
else
echo "Connexion to root@${i}.${domain} ........... $(red NOK)"
read -p "$(italics "?? Do you want to install $key to root@${i}.${domain}: $(faint "[y]")?") " yn
yn=${yn:-y}
while true; do
case $yn in
[Yy]* )
set_ssh_key
echo -e "Installing pub keys......."
ssh-copy-id root@${i}.${domain} > /dev/null
message
break;;
[Nn]* )
italics "You must first install some pub key before using this script"
exit
break;;
esac; done
fi
done
}
set_domain() {
dom=$(hostname -d)
read -p "$(italics "?? Please enter the domain (default is the one of the bastion) $(faint [$dom]): ")" domain2
domain=${domain:-$dom}
blue $domain
}
create_project
# Check ssh key presence
set_ssh_key
# Docker hosts domain identification
set_domain
ask_testing_ssh() {
echo -e "${YELLOW}!!! Warning !!!${ENDCOLOR}"
read -p "$(italics "?? Do you want to check ssh connectivity? If a host is not reacheable, pub key will be installed.[no]: ")" yn
yn=${yn:-n}
while true; do
case $yn in
[Yy]* )
testing_ssh
break;;
[Nn]* )
echo "Assuming Docker hosts are available without any password..."
break;;
esac
done
}
fetch() {
if [[ -f "$1" ]];
then
echo "$(blue \"$1\") ready to be used"
else
if [[ $1 == "docker-compose.yml" ]]
then
italics "\"$1\" has not been found. Please check https://raw.githubusercontent.com/abes-esr/$NAME-docker/develop/docker-compose.yml and retry"
elif [[ $1 == ".env" ]]
then
echo "$(blue \"$1\") has not been found. Please check $(blue $docker_host:/opt/pod/$NAME-docker/.env) and retry"
fi
exit
fi
}
get_running_docker() {
echo ""
read -p "$(italics "?? If you know the Docker host where \"$NAME\" is currently running on, please enter the hostname (not fqdn), else type \"enter\" to automatically find it: ")" hostname
# hostname=${hostname:-diplotaxis2-test}
if [ -z $hostname ]
then
docker_hosts=
read -p "$(italics "?? Please enter the list of your Docker hosts hostnames: ")" docker_hosts
docker_hosts=${docker_hosts:-"diplotaxis1 diplotaxis2 diplotaxis3 diplotaxis4 diplotaxis5 diplotaxis6 diplotaxis7"}
set -- $(echo $docker_hosts)
if [[ -n $ENV ]] && [[ "$ENV" != "local" ]];
then
set -- "${@/%/-$ENV}"
fi
docker_hosts=$(echo $@)
blue "$docker_hosts"
title "1.4" "SSH connexion validation"
ask_testing_ssh
echo "Searching which Docker host \"$NAME\" is currently running on ......"
NAME_SHORT=$(echo $NAME | cut -d"-" -f1)
diplo=$( \
for i in $docker_hosts
do
ssh root@${i}.${domain} docker ps --format json | jq --arg i "${i}" '{"docker_host": ($i), nom: .Names}'; \
done \
| jq -rs --arg docker_hosts "$i" --arg var "$NAME_SHORT" '[.[] | select(.nom | test("^\($var)-.*"))]|first|."docker_host"'
); \
else
diplo="$hostname"
fi
blue "\"$NAME\" is running on $diplo\n"
docker_host="${diplo}.${domain}"
}
dockerhub_auth() {
read -p "$(italics "?? Do you want to authenticate against DockerHub? $(faint "[n]")"): " ynyn
ynyn=${ynyn:-n}
case $ynyn in
[Yy]* )
read -p "$(italics "?? DockerHub server $(faint "[docker.io]")"): " dh_server
dh_server=${dh_server:-docker.io}
read -p "$(italics "?? DockerHub username" ): " dh_user
read -p "$(italics "?? DockerHub password" ): " dh_passwd
echo -e "Creation of docker secret for pulling images without restriction.......................................\n"
oc create secret docker-registry docker.io --docker-server=${dh_server} --docker-username=${dh_user} --docker-password=${dh_passwd}
oc secrets link default docker.io --for=pull
echo -e "\n"
;;
esac
}
secret_pull() {
echo -e "Creation of docker secret for pulling images without restriction.......................................\n"
oc create secret docker-registry $1 --docker-server=${1} --docker-username=${dh_user} --docker-password=$dh_passwd
oc secrets link default $1 --for=pull
}
pusher_sa() {
oc create serviceaccount pusher
sleep 2
pusher=$(oc get -o json sa pusher| jq -r '.secrets[0].name')
TOKEN=$(oc get -o json secrets $pusher |jq -r '.metadata.annotations."openshift.io/token-secret.value"')
oc policy add-role-to-user system:image-builder -z pusher
}
docker_login() {
echo "Setting registry authentication for pushing images......."
oc_registry=$(oc get route default-route -n openshift-image-registry -o json | jq -r .spec.host)
registry_cert=$(oc extract --confirm=true secret/router-certs-default -n openshift-ingress --to=/tmp/$oc_registry/ | grep crt)
if [[ -z "$1" ]]
then
registry=$oc_registry
else
registry=$1
fi
if [ "$registry" = "docker.io" ]
then
read -p "$(italics "?? Enter DockerHub user: ")" dh_user
read -p "$(italics "?? Enter DockerHub password" ): " dh_passwd
echo $dh_passwd | docker login -u $dh_user --password-stdin >/dev/null 2>&1
else
dh_user=any
oc whoami -t 2>/tmp/toto
if [ $(grep "error" /tmp/toto | wc -l) = 0 ];
then
TOKEN=$(oc whoami -t)
else
while true; do
echo "Requiring a token to connect to $registry..."
pusher_sa
if [ -z $TOKEN ]
then
echo "There is no valid token to authenticate against $registry, please check your credentials"
else
break
fi
done
fi
command="echo $TOKEN | docker --tlscacert $registry_cert login -u $dh_user $registry --password-stdin"
echo $TOKEN | docker --tlscacert $registry_cert login -u $dh_user $registry --password-stdin >/dev/null 2>&1
if [ $(echo $?) = 0 ]
then
echo -e "$(blue "Login for pushing to $registry Succeeded")"
else
read -p "$(italics "?? Retry with an adjusted plain docker login command: $(faint "$command"): ")" docker_command
eval "$docker_command"
fi
read -p "$(italics "?? Enter DockerHub user: ")" dh_user
read -p "$(italics "?? Enter DockerHub password" ): " dh_passwd
secret_pull docker.io
fi
}
build_image() {
for build_service in $build_services;
do
echo -e "########################################### ${YELLOW}Building $build_service${ENDCOLOR} ###########################################"
if [ -z "$docker_host" ];
then
while true; do
case $docker_host in
"" )
read -p "$(italics "?? Enter the Docker host where $NAME is running on: ")" docker_host;;
* )
docker_host=${docker_host}.${domain}
break;;
esac
done
fi
if [ -z "$path" ];
then
read -p "$(italics "?? Enter docker-compose.yml path on host \"$docker_host\" $(faint [/opt/pod/$NAME-docker]): ")" path
path=${path:-/opt/pod/$NAME-docker}
fi
CONTEXT=$(cat docker-compose.yml |yq -ojson |jq --arg build_service "$build_service" -r '.services|to_entries[]|select(.value.container_name==$build_service).value.build')
IMAGE=$(cat $NAME.yml|yq -ojson |jq --arg build_service "$build_service" -r '.services|to_entries[]|select(.value.container_name==$build_service).value.image')
echo -e "$(blue \"$build_service\"): Syncing build context from $(blue \"$docker_host\") ..............\n"
rsync -a --info=progress2 root@$docker_host:/$path/$CONTEXT .
message
echo -e "$(blue \"$build_service\"): Building $(blue \"$IMAGE\") ............\n"
docker build -q -t $IMAGE ${CONTEXT##*/}
message
echo ''
docker_push_image
done
}
docker_push_image() {
if [ "$is" = "y" ]
then
echo "oc create is $build_service --lookup-local=true"
oc create is $build_service --lookup-local=true
fi
echo "Pushing image $(blue $build_service) to registry $(blue "$registry")............"
echo "docker tag $IMAGE $registry/$namespace/$IMAGE"
docker tag $IMAGE $registry/$namespace/$IMAGE
echo "docker push $registry/$namespace/$IMAGE"
docker push $registry/$namespace/$IMAGE
}
oc_tag_image() {
not_build_services=$(cat $NAME.yml | yq -o json|jq -r '.services|to_entries[]|select(.value|has("build")|not).value.container_name')
for not_build_service in $not_build_services
do
if [[ "$PROVIDER" != "openshift" ]]
then
oc create is $not_build_service --lookup-local=true
fi
IMAGE_TGT=$(cat $NAME.yml | yq -o json|jq --arg tgt "$not_build_service" -r '.services|to_entries[].value|select(."container_name"=="\($tgt)").image')
IMAGE_TAG=$(cat $NAME.yml | yq -o json|jq --arg tgt "$not_build_service" -r '.services|to_entries[].value|select(."container_name"=="\($tgt)").image|split(":")|last')
oc tag --source=docker $IMAGE_TGT $not_build_service:$IMAGE_TAG
oc set image-lookup deploy/$not_build_service
done
}
ask_docker_host() {
if [ -z "$docker_host" ];
then
while true; do
case $docker_host in
'' )
read -p "$(italics "?? Enter the Docker fqdn where $NAME is running on: ")" docker_host
;;
* )
docker_host=${docker_host}.${domain}
break;;
esac
done
fi
}
# Creating working dir
mkdir $NAME-docker-${ENV} && cd $NAME-docker-${ENV}
if [[ "$ENV" == "prod" ]] || [[ "$ENV" == "test" ]] || [[ "$ENV" == "dev" ]]; then
echo -e ""
echo "Ok, let's go on!"
title "1.3" "Docker host search"
get_running_docker
read -p "$(italics "?? Choose docker-compose.yml method $(faint "[docker_host|github]"): ")" method
method=${method:-docker_host}
blue "$method"
case $method in
github )
italics "Fetching \"docker-compose.yml\" from GitHub......................................."; \
read -p "$(italics "?? Enter DockerHub URL docker-compose.yml path"): " path
path=${path:-https://raw.githubusercontent.com/abes-esr/$NAME-docker/develop/docker-compose.yml}
wget -N $path 2> /dev/null; \
fetch "docker-compose.yml"
echo "";;
docker_host )
echo "Fetching \"docker-compose.yml\" from $docker_host ......................................."; \
read -p "$(italics "?? Enter docker-compose.yml path on host \"$docker_host\" $(faint [/opt/pod/$NAME-docker]): ")" path
path=${path:-/opt/pod/$NAME-docker}
rsync -a root@$docker_host:$path/docker-compose.yml . ; \
fetch "docker-compose.yml"
echo "";;
esac
echo "Fetching \".env\" from $docker_host Docker host..........................................."
rsync -a root@$docker_host:/opt/pod/$NAME-docker/.env .; \
fetch ".env"
echo ""
elif [[ "$ENV" == local ]];then
ask_docker_host
if ! [[ -f ../docker-compose.yml ]]; then
echo "There is no current docker-compose.yml file for \"$NAME\" in $(pwd)"
echo "Please manually copy the docker-compose.yml to $PWD and re-execute this script"
exit
else
rsync ../docker-compose.yml .
cat docker-compose.yml |grep "$NAME" > /dev/null
if [ "$?" == 0 ];
then
echo "\"docker-compose.yml\" is already present and ready to be used for \"$NAME\".... "
else
echo "\"docker-compose.yml\" is already present but doesn't seem to belong to \"$NAME\".... "
read -p "$(italics "?? Do you want to continue anyway? $(faint "[n]")")" yn
if [ "$yn" == "n" ]; then echo -e "Please check \"$(cd .. && pwd)/docker-compose.yml\" content.\nExiting" ; exit; fi
fi
fi
if ! [[ -f ../.env ]]
then
echo "There is no current \".env\" file for \"$NAME\" in $(pwd)"
echo "Please manually provide a valid \".env\" file in the same directory as docker-compose.yml file ($PWD)"
exit 1
else
rsync ../.env .
cat .env |grep "$NAME" > /dev/null
if [ "$?" == 0 ];
then
echo "\".env\" is already present and ready to be used for \"$NAME\".... "
else
echo "\".env\" is already present but doesn't seem to belong to \"$NAME\".... "
read -p "$(italics "?? Do you want to continue anyway? $(faint "[n]")")" yn
if [ "$yn" == "n" ]; then echo -e "Please check \"$(cd .. && pwd)/.env\" content. \nExiting..." ; exit; fi
fi
fi
elif [[ "$ENV" != "local" ]]; then
echo "Valid verbs are 'dev', 'test', 'prod' or 'local'"
exit 1;
elif ! test -f .env || ! test -f docker-compose.yml; then
echo -e "No valid files have been found\nCopy your '.env' and your 'docker-compose.yml in $PWD'";
exit 1;
fi
echo ""
# Customizing .env
if test -f .env;
then
read -p "$(italics "?? Do you want to customize your variable environment before the conversion to manifests?: $(faint "[n]") ")" yn
yn=${yn:-n}
while true; do
case $yn in
[Yy]* )
vi .env
break;;
[Nn]* )
break;;
esac
done
fi
if [ "$VARS_TYPE" = "copy" ];
then
is_deploy=$(oc get deploy -o json|jq '(if .items==[] then false else true end)')
if [ "$is_deploy" = "false" ]
then
PROVIDER=openshift
fi
ask_docker_host
docker-compose config -o compose.yml
copy_to_okd bind compose.yml
copy_to_okd volume compose.yml
rm -f compose.yml
read -p "$(italics "?? Reloading pods to launch \"$NAME\" $(faint "[y]") : ?")" yn
yn=${yn:-y}
case $yn in
[Yy]* )
echo "Restart all $NAME pods......................................."
oc rollout restart deploy
timeout 10 oc get pods -w;;
[Nn]* )
echo "You should manually relaod pods before \"$NAME\" being up by typing \"oc rollout restart deploy\"";;
esac
exit
fi
echo -e "\n"
step "2" "Conversion des variables en objet secrets et configMaps"
title "2.1" ".env resolution"
docker-compose config --format json | yq -o json \
| jq '.services
|=with_entries(
.key=(
if .value|has("container_name")
then .value."container_name"
else .
end)
)' \
| yq -P \
| sed 's/\.svc//g'> $NAME.yml
message
title "2.2" "Buiding images if directives are present"
build_services=$(cat $NAME.yml | yq -o json|jq -r '.services|to_entries[]|select(.value|has("build")).value.container_name')
if ! [ -z "$build_services" ]
then
echo -e "${YELLOW}!!Build directives have been detected!!${ENDCOLOR}"
echo "This services have some directives to build images:"
echo "$build_services"
read -p "$(italics "?? Which method do you want to build images with ? [buildConfig|local_docker]: ")" provider
provider=${provider:-buildConfig}
echo ''
docker_login
if [[ "$provider" = "buildConfig" ]];
then
echo -e "You will use $(blue \"deploymentConfig API\")"
echo "Cloning $NAME-docker......"
read -p "$(italics "?? Enter the Github namespace of $NAME-docker? [abes-esr]: ")" gh_namespace
gh_namespace=${gh_namespace:-abes-esr}
read -p "$(italics "?? Enter the Github branch of $NAME-docker? [develop]: ")" gh_branch
gh_branch=${gh_branch:-develop}
rm -f docker-compose.yml
git init -q
git remote add origin https://github.com/$gh_namespace/$NAME-docker.git
git pull origin $gh_branch --allow-unrelated-histories
git checkout $gh_branch
# git submodule update --init --recursive
BUILD_ARGS="--build build-config"
PROVIDER=openshift
else
echo -e "You will use $(blue \"deployment API\")"
read -p "$(italics "?? Do you want to use imageStream with deployment API............$(faint "[y]"): ")" is
is=${is:-y}
build_image
message
docker logout
PROVIDER=kubernetes
fi
rm -f $registry_cert
else
blue "No building instruction, going on ..."
fi
title "2.3" "Cleaning of $NAME.yml"
cat $NAME.yml \
| yq -ojson \
| jq --arg name "$NAME" 'del (.services."\($name)-watchtower")
| del(..|nulls)
| del(.services[].volumes[]?|select(.source|test("sock")))
| del(.services[]."depends_on")
| del(.services."theses-elasticsearch-setupcerts")
| del(.services."theses-elasticsearch-setupusers")
| del(.services."theses-api-diffusion-poc")
| (if has("volumes") then .volumes|=with_entries(.key|=gsub("\\.";"-")) else . end)
| .services[].volumes[]?|=(if .type=="bind" then . else .source|=gsub("\\.";"-") end)
| .services|=with_entries(.value|=(select(has("volumes")).volumes |= sort_by((.type)) ))' \
| yq -P | sponge $NAME.yml
message
CLEANED="$NAME.yml"
#### insertion de la clé "secrets" dans chacun des services de docker-compose.yml
#### prend en paramètre le nom du fichier docker-compose.yml
if [ -n "$VARS_TYPE" ] && [ "$VARS_TYPE" == 'env_file' ]
then
echo -e "on continue......................................."
SMALL_LIST=$(cat $CLEANED | yq eval - -o json | jq '.services|to_entries[] | {(.key): .value.environment}'| jq -s)
message
###### select variable name filtering by KEY or PASSWORD ####
FILTER_LIST=$(echo $SMALL_LIST | yq eval - -o json \
| jq '.[]|to_entries[]|try {key:.key,value:.value|to_entries[]} | select(.value.key | test("KEY|PASS|SECRET"))' \
| jq -s )
message
###### Generating secret files from .env file #####
export var=$(echo $FILTER_LIST | jq -r '.[].value.key')
for i in $(echo $var); \
do
export data=$(echo $FILTER_LIST | jq --arg tata "$i" -r '[.[].value | select(.key==$tata).value]|first')
echo $data > $(echo $i| sed 's/_/-/g' | tr '[:upper:]' '[:lower:]').txt; \
cat $CLEANED \
| yq eval - -o json \
| jq --arg i $i '.secrets[$i|ascii_downcase|gsub("_";"-")].file = ($i|ascii_downcase|gsub("_";"-")) + ".txt"' \
| yq eval - -P \
| sponge $CLEANED; \
done
message
########### Conversion du environment en env_file ############
# Génération des {service}.env à partir du docker-compose.yml
title "2.4" "Generation of \${services}.env"
for i in $(cat $CLEANED|yq eval -ojson|jq -r --arg var "$i" '.services|to_entries|map(select(.value.environment != null)|.key)|flatten[]'); \
do cat $CLEANED | \
yq eval - -o json |\
jq -r --arg var "$i" '.services[$var].environment' | \
# egrep -v 'KEY|PASS|SECRET' | \
yq eval - -P| \
sed "s/:\ /=/g" > $i.env;
done
message
# Déclaration des variables contenant un secret dans le env_file
for i in $(ls *.env);
do
for j in $(cat $i | egrep '(KEY|PASS|SECRET)');
do
KEY=$(echo $j | cut -d"=" -f1);
LINE=$(echo $KEY | cut -d"=" -f1 | tr '[:upper:]' '[:lower:]' | sed 's/_/-/g');
sed -i "s/.*$KEY.*/$KEY=\/run\/secrets\/$LINE/g" $i;
done;
done
# Déclaration des {services.env} dans docker-compose.yml
title "2.5" "Declaration of \${services}.env into deployments"
for i in $(cat $CLEANED|yq eval -ojson|jq -r --arg var "$i" '.services|to_entries|map(select(.value.environment != null)|.key)|flatten[]'); \
do echo $i; cat $CLEANED | \
yq eval - -o json | \
jq -r --arg var "$i" '.services[$var]."env_file" = $var +".env"' | \
yq -P |
sponge $CLEANED ; \
done
message
#
title "2.6" "Check mem_limit"
for i in $(cat $CLEANED | yq -o json| jq -r '.services|keys|.[]')
do
MEM_LIMIT=$(cat $CLEANED | yq -o json| jq -r --arg i "$i" '.services|to_entries[]|.value|select(.container_name=="\($i)").mem_limit')
if [ "$MEM_LIMIT" > 2147483648 ]
then
echo -e "${YELLOW}!! Warning !!${ENDCOLOR}: service $(blue \"$i\") will lock $(blue $(calc "int($MEM_LIMIT / (1024*1024*1024) )")) GiB of RAM on worker."
read -p "$(italics "?? Worker nodes may not be able to schedule concerned pods. Please enter a lower limit in GiB $(faint "(0 for no limit, empty for current limit)"): ")" LIMIT
limit=${LIMIT:-$MEM_LIMIT}
if ! [ "$limit" = "$MEM_LIMIT" ];
then
limit=$(calc "int($limit * (1024*1024*1024))")
fi
if [ "$limit" = 0 ]
then
cat $CLEANED |
yq -o json|
jq --arg limit "$limit" --arg i "$i" '.services|=with_entries( if .value.container_name=="\($i)"
then del(.value."mem_limit")|del(.value."memswap_limit")
else .
end)' | \
sponge $CLEANED
else
cat $CLEANED |
yq -o json|
jq --arg limit "$limit" --arg i "$i" '.services|=with_entries( if .value.container_name=="\($i)"
then .value.mem_limit="\($limit)"
else .
end)' | \
sponge $CLEANED
fi
fi
done
message
# Suppression des environnements et nettoyage
title "2.7" "Cleaning"
cat $CLEANED \
| jq 'del (.services[].environment)' \
| jq 'del(.networks)' \
| jq 'del(.services[].networks)' \
| jq 'del(.services[].labels."com.centurylinklabs.watchtower.scope")' \
| yq eval - -P | sponge $CLEANED
message
# fi
else
# Suppression des environnements et nettoyage final
echo -e "5> #################### Suppression des environnements et nettoyage final ####################\n"
cat $CLEANED \
| yq eval -o json \
| jq 'del(.networks)' \
| jq 'del(.services[].networks)' \
| jq 'del(.services[].labels."com.centurylinklabs.watchtower.scope")' \
| yq eval - -P | sponge $CLEANED
message
fi
# Patch ReadOnlyMany pvc to ReadWriteOnly. The readOnly feature will be later executed with the "readOnly:"" true directive into deployment
patch_RWO () {
for i in $(grep ReadOnlyMany *persistent* |cut -d: -f1);
do
echo "Patching \n ReadOnlyMany modeAccess to ReadWriteOnce in $i......................................."
sed -i 's/ReadOnlyMany/ReadWriteOnce/g' $i;
done
}
patch_expose_auto () {
for service in $services;
do
port=$(ssh root@$docker_host docker inspect $service | jq -cr '[.[].NetworkSettings.Ports|to_entries[]|.key|split("/")|.[0]'])
port=${port:-[]}
if [[ $port != '[]' ]]
then
blue "Patching ports $port for service $service ............"
cat $CLEANED | yq -o json| jq | jq --arg service "$service" --argjson port "$port" '.services."\($service)".expose+=$port' \
|sponge $CLEANED
fi
done
cat $CLEANED | yq -P | sponge $CLEANED
}
patch_expose () {
echo "You may define them one by one so as the conversion to be successfull"
for service in $services;
do
read -p "$(italics "?? $(blue $service): Enter port number to expose the service $(faint '(press to leave empty)'): ")" port
if [[ -n $service ]]
then
if [[ -n $port ]]
then
cat $CLEANED | yq -o json | jq --arg service "$service" --arg port "$port" '.services."\($service)".expose+=[ "\($port)" ]' \
|sponge $CLEANED
fi
fi
done
cat $CLEANED | yq -P | sponge $CLEANED
}
# Patch *.txt file to remove '\n' character based in 64
patch_secret () {
for i in $(ls *secret*yaml); \
do \
echo "Patching \n character in $i.......................................";
cat $i | yq eval -ojson \
| jq -r '.data|=with_entries(.value |=(@base64d|sub("\n";"")|@base64))' \
| yq eval - -P \
| sponge $i; \
done
}
# Patch secretKeys
patch_secretKeys () {
for i in $(ls *deployment*);
do
echo "patching lowercase in $i......................................."
cat $i| yq eval -ojson |
jq '.spec.template.spec.containers
|= map(
(.env
|= map(
if (.name|test("SECRET|PASS|KEY"))
then .valueFrom
|= with_entries(.key="secretKeyRef"
|.value.name=(.value.key|ascii_downcase|gsub("_";"-"))
|.value.key|=(ascii_downcase|gsub("_";"-"))
)
else .
end
)
)? // .
)' |
yq eval -P | sponge $i;
done
}
# Patch networkpolicy to allow ingress
patch_networkPolicy () {
NETWORK=$(ls | grep networkpolicy)
if ! [ -z "$NETWORK" ]
then
echo "patching ingress in $NAME-docker-$ENV-default-networkpolicy.yaml......................................."
cat $NETWORK | yq eval -ojson |
jq '.spec.ingress|=
map(.from |= .+ [{"namespaceSelector":{"matchLabels":{ "policy-group.network.openshift.io/ingress": ""}}}])'|
yq eval -P | sponge $NETWORK
else
blue "Nothing to do"
fi
}
select_sc() {
default_sc=$(oc get sc -o json | jq -r '.items[]|select(.metadata.annotations|has("storageclass.kubernetes.io/is-default-class")).metadata.name')
echo "You are about to deploy \"$NAME\" with the default storageClass \"$default_sc"\"
read -p "$(italics "?? Would you like to use a different storageClass?....[n]: ")" yn
yn=${yn:-n}
while true; do
case $yn in
[Yy]* )
echo "Here are available storageClasses:"