forked from greenled/portainer-stack-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
psu
executable file
·1448 lines (1339 loc) · 51.2 KB
/
psu
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
#!/usr/bin/env bash
#
# Deploy/update/remove/inspect/status Docker stacks in a Portainer instance.
# List stacks, services, tasks and containers
# And more!
set -e
############################
# Main entrypoint #
# Globals: #
# HTTPIE_VERIFY_SSL #
# PORTAINER_URL #
# PORTAINER_USER #
# PORTAINER_AUTH_TOKEN #
# PORTAINER_PASSWORD #
# PORTAINER_STACK_NAME #
# PORTAINER_SERVICE_NAME #
# STACKS #
# STACK #
# TIMEOUT #
# ACTION #
# Arguments: #
# None #
# Returns: #
# None #
############################
main() {
VERSION="1.0.0-alpha.3"
OPTIONS_TABLE=(
# option_key;flag_text;option_text;description
"url;-l;--url=URL;URL of the Portainer instance"
"user;-u;--user=USERNAME;Username of the Portainer instance"
"password;-p;--password=PASSWORD;Password of the Portainer instance"
"auth-token;-A;--auth-token=[AUTH_TOKEN];Use a Portainer auth token instead of '--user' and '--password' options, you can get it with the 'psu login' command. Defaults to null"
"name;-n;--name=STACK_NAME;Stack name"
"compose-file;-c|-f;--compose-file=[FILE_PATH];Path to docker compose/stack file (required if action=deploy)"
"compose-file-base64;-C|-F;--compose-file-base64=[BASE64];Content of docker compose/stack file, encoded in base64, useful with Docker in Docker (only used when action=deploy)"
"env-file;-g;--env-file=[FILE_PATH];Path to a file of environment variables, to be used by the stack (only used when action=deploy)"
"env-file-base64;-G;--env-file-base64=[BASE64];Content of file with environment variables, encoded in base64, to be used by the stack, useful with Docker in Docker (only used when action=deploy)"
"endpoint;-e;--endpoint=[ENDPOINT_ID];Which Docker endpoint to use. Defaults to 1"
"prune;-r;--prune;Whether to prune unused containers or not (only used when action=deploy). Defaults to false"
"timeout;-T;--timeout=[SECONDS];Timeout, number of seconds before thrown an error (only used when action=status|tasks|tasks:healthy). Defaults to 100"
"detect-job;-j;--detect-job=[true|false];Auto detect services who are jobs in the current stack. Defaults to true"
"service;-S;--service[=SERVICE_NAME];Filtering by a service name of the current stack (only used when action=status|tasks|tasks:healthy|containers)"
"insecure;-i;--insecure;Skip the host's SSL certificate verification, use at your own risk. Defaults to false"
"verbose;-v;--verbose;Increase the verbosity of messages. Defaults to false"
"debug;-d;--debug;Print as much information as possible to help diagnosing a malfunction. Defaults to false"
"masked-variables;-m;--masked-variables;In debug/verbose mode, value of sensitive variables will be hidden, useful in CI to avoid leaking passwords/tokens in logs. Possible values: true|extended|false. Defaults to false"
"quiet;-q;--quiet;Display the minimum of information or nothing, UNIX/Linux friendly. Defaults to false"
"strict;-t;--strict;Never updates an existent stack nor removes an inexistent one, and instead exits with an error. Defaults to false"
"lint;-L;--lint;Validate the Docker compose/stack file before deploying the stack (only used when action=deploy). Defaults to false"
"help;-h;--help;Display help message. To display help of a given action, run: 'psu <action> --help'"
"version;-V;--version;Display the version of this program"
"secure;-s;--secure[=yes|no];DEPRECATED: Use the '--insecure' option instead. Enable or disable the host's SSL certificate verification. Defaults to 'yes'"
"action;-a;--action=[ACTION_NAME];DEPRECATED: Use <action> argument instead. The name of the action to execute"
)
ACTIONS_TABLE=(
# action_name;description[;required_option_key1|required_option_key2...][;optional_option_key1|optional_option_key2...]
"deploy;Deploy the stack;url|user|password|name|compose-file;auth-token|endpoint|lint|file-base64|env-file|env-file-base64|prune|insecure|verbose|debug|masked-variables|strict"
"rm;Remove/undeploy the stack;url|user|password|name;auth-token|endpoint|insecure|verbose|debug|masked-variables|strict"
"ls;List stacks already deployed;url|user|password;auth-token|endpoint|quiet|insecure|verbose|debug|masked-variables|help"
"status;Check if the stack is running/deployed correctly;url|user|password|name;auth-token|endpoint|service|detect-job|timeout|insecure|verbose|debug|masked-variables"
"services;List services already deployed in the current stack;url|user|password|name;auth-token|endpoint|quiet|insecure|verbose|debug|masked-variables"
"tasks;List tasks in the current stack;url|user|password|name;auth-token|endpoint|service|detect-job|timeout|quiet|insecure|verbose|debug|masked-variables"
"tasks:healthy;List tasks who are running correctly in the current stack;url|user|password|name;auth-token|endpoint|service|detect-job|timeout|quiet|insecure|verbose|debug|masked-variables"
"containers;List containers running in the current stack;url|user|password|name;auth-token|endpoint|service|quiet|insecure|verbose|debug|masked-variables"
"login;Log in to a Portainer instance;url|user|password;insecure|verbose|debug|masked-variables"
"lint;Validate the Docker compose/stack file;compose-file;file-base64|verbose|debug"
"inspect;Display low-level information of the current stack;url|user|password|name;auth-token|endpoint|quiet|insecure|verbose|debug|masked-variables"
"system:info;Display Docker system-wide information;url|user|password;auth-token|endpoint|insecure|verbose|debug|masked-variables"
"actions;List available actions of this program;;verbose|debug"
"help;Display help message"
"version;Display this program version"
)
# Special actions who display text only
# No HTTP requests will be made
ACTIONS_TEXT_ONLY="actions lint help version"
# Aliases of default actions
# NOTICE: This is an experimental feature
# Please, don't use these aliases in production
declare -A ACTIONS_ALIASES
ACTIONS_ALIASES=(
["auth"]="login"
["docker:info"]="system:info"
["remove"]="rm"
["undeploy"]="rm"
["list"]="ls"
["ps"]="tasks"
["ps:healthy"]="tasks:healthy"
["update"]="deploy"
["validate"]="lint"
)
# TODO: move this stuff in a function
# Set the ACTIONS variable
# and the ACTIONS_ASSOC variable
declare -A ACTIONS_ASSOC
local action_table
local action_name
local action_description
local required_options
local optional_options
for action in "${ACTIONS_TABLE[@]}"; do
IFS=';' read -ra action_table <<< "$action"
action_name="${action_table[0]}"
action_description="${action_table[1]}"
required_options="${action_table[2]}"
optional_options="${action_table[3]}"
ACTIONS_ASSOC["$action_name"]="$action_description;$required_options;$optional_options"
if [ -n "$action_description" ]; then
if [ -n "$ACTIONS" ]; then
ACTIONS+=" $action_name"
else
ACTIONS="$action_name"
fi
fi
done
# TODO: move this stuff in a function
# Set the OPTIONS variable
# and the OPTIONS_ASSOC variable
declare -A OPTIONS_ASSOC
local option_table
local option_key
local flag_text
local option_text
local option_description
for option in "${OPTIONS_TABLE[@]}"; do
IFS=';' read -ra option_table <<< "$option"
option_key="${option_table[0]}"
flag_text="${option_table[1]}"
option_text="${option_table[2]}"
option_description="${option_table[3]}"
OPTIONS_ASSOC["$option_key"]="$flag_text;$option_text;$option_description"
if [ -n "$OPTIONS" ]; then
OPTIONS+=" $option_key"
else
OPTIONS="$option_key"
fi
done
export PORTAINER_AUTH_TOKEN
set_globals "$@"
if [[ ! ${ACTIONS_TEXT_ONLY[*]} =~ $ACTION ]]; then
if [ -z "$PORTAINER_AUTH_TOKEN" ]; then
login
fi
# Get list of all stacks
echo_verbose "Getting stack $PORTAINER_STACK_NAME..."
STACKS=$(http \
--check-status \
--ignore-stdin \
--verify=$HTTPIE_VERIFY_SSL \
"$PORTAINER_URL/api/stacks" \
"Authorization: Bearer $PORTAINER_AUTH_TOKEN")
check_for_errors $? "$STACKS"
echo_debug_safe_json "Get stacks response -> $(echo $STACKS | jq -C .)" "$STACKS"
# Get desired stack from stacks list by it's name
STACK=$(echo "$STACKS" \
| jq --arg PORTAINER_STACK_NAME "$PORTAINER_STACK_NAME" -jc '.[] | select(.Name == $PORTAINER_STACK_NAME)')
echo_debug_safe_json "Stack ${PORTAINER_STACK_NAME} -> $(echo $STACK | jq -C .)" "$STACK"
fi
if [ $ACTION == "deploy" ]; then
deploy
exit 0
fi
if [ $ACTION == "rm" ]; then
undeploy
exit 0
fi
if [ $ACTION == "login" ]; then
# if [ -z "$PORTAINER_AUTH_TOKEN" ]; then
# login
# fi
if [ $QUIET_MODE == "false" ] && [ $MASKED_VARIABLES == "false" ]; then
echo "$PORTAINER_AUTH_TOKEN"
fi
exit 0
fi
# Returns Docker system info
if [ $ACTION == "system:info" ]; then
local docker_info
echo_verbose "Getting Docker info..."
docker_info="$(docker_info)"
echo_debug "Docker info -> $(echo $docker_info | jq -C .)"
if [ -n "$docker_info" ]; then
echo "$docker_info"
exit 0
fi
exit 1
fi
if [ $ACTION == "services" ]; then
echo_verbose "List service(s) of stack '$PORTAINER_STACK_NAME'..."
local services
services=$(services)
echo_debug "Services action response -> $(echo $services | jq -C .)"
if [ -n "$services" ] && [ ! "$services" == "[]" ]; then
if [ $QUIET_MODE == "false" ]; then
# Returns response in JSON format
echo "$services"
else
# Only display service(s) name in quiet mode
echo "$services" | jq -r '.[] | [.Spec.Name] | add'
fi
exit 0
fi
exit 1
fi
if [ $ACTION == "status" ]; then
echo_verbose "Status of tasks for the stack '$PORTAINER_STACK_NAME'..."
local status
# WIP: Each services should have at least one task
# with desired state == 'running' and state == 'running'
# or desired state == 'shutdown' and state == 'complete'
# Tasks should not have one of these states:
# 'failed', 'orphaned', 'remove'
timeout $TIMEOUT bash -c "until (export PORTAINER_SERVICE_NAME=$PORTAINER_SERVICE_NAME && export DEBUG_MODE=false && export VERBOSE_MODE=false && psu -a tasks:healthy -q) >/dev/null 2>&1; do echo -n \$(if [ \"\$VERBOSE_MODE\" == \"true\" ]; then echo -n .; fi) && sleep 1; done;"
status=$?
if $(exit $status); then
echo_verbose "Status: healthy for the stack '$PORTAINER_STACK_NAME'"
exit 0
else
echo_verbose "Status: unhealthy for the stack '$PORTAINER_STACK_NAME'"
echo_error "Error: No tasks or not all tasks are running correctly for the stack \"$PORTAINER_STACK_NAME\""
exit 1
fi
fi
if [ $ACTION == "tasks" ] || [ $ACTION == "tasks:healthy" ]; then
local scope
scope="$(if [ $ACTION == "tasks:healthy" ]; then echo healthy; else echo all; fi)"
local tasks
if [ -n "$PORTAINER_SERVICE_NAME" ]; then
echo_verbose "List $scope tasks from service '$PORTAINER_SERVICE_NAME' of stack '$PORTAINER_STACK_NAME'..."
tasks=$(if [ $scope == "healthy" ]; then tasks_healthy; else tasks; fi)
echo_debug "Tasks action response -> $(echo $tasks | jq -C .)"
else
echo_verbose "List $scope tasks of stack '$PORTAINER_STACK_NAME'..."
local services
services="$(timeout $TIMEOUT bash -c "until (export DEBUG_MODE=false && export VERBOSE_MODE=false && echo \"\$(psu -a services -q)\"); do sleep 1; done;")"
# TODO: Improve performance, find a way to do parallel requests
# See: https://stackoverflow.com/questions/8634109/parallel-download-using-curl-command-line-utility#comment51239188_24276040
# Try and tweaks these command:
# psu services -u admin -p password -l http://portainer.local -n $PORTAINER_STACK_NAME -q | sed "s/^${PORTAINER_STACK_NAME}_\(.*\)$/\1/" | xargs -I {} -P 10 -- psu tasks -u admin -p password -l http://portainer.local -n $PORTAINER_STACK_NAME -S {} -q
for service in $services; do
export PORTAINER_SERVICE_NAME=${service#"${PORTAINER_STACK_NAME}_"}
local new_tasks
new_tasks=$(if [ $scope == "healthy" ]; then tasks_healthy; else tasks; fi)
if [ -z "$new_tasks" ] || [ "$new_tasks" == "[]" ]; then
echo_verbose "Error: $scope tasks aren't running correctly for the stack \"$PORTAINER_STACK_NAME\""
exit 1;
fi
tasks="$(echo -n "${tasks}${new_tasks}" | jq -sjc 'add | unique_by(.ID)')"
done
echo_debug "Tasks action response -> $(echo $tasks | jq -C .)"
fi
if [ -n "$tasks" ] && [ ! "$tasks" == "[]" ]; then
if [ $QUIET_MODE == "false" ]; then
# Returns response in JSON format
echo "$tasks"
else
# Only display task(s) id in quiet mode
echo "$tasks" | jq -r '.[] | [.ID] | add'
fi
exit 0
fi
echo_verbose "Error: No tasks or not all tasks are running correctly for the stack \"$PORTAINER_STACK_NAME\""
exit 1
fi
if [ $ACTION == "containers" ]; then
echo_verbose "List container(s) of stack '$PORTAINER_STACK_NAME'..."
local containers
containers=$(containers)
echo_debug "Containers action response -> $(echo $containers | jq -C .)"
if [ -n "$containers" ] && [ ! "$containers" == "[]" ]; then
if [ $QUIET_MODE == "false" ]; then
# Returns response in JSON format
echo "$containers"
else
# Only display container(s) id in quiet mode
echo "$containers" | jq -r '.[] | [.Id] | add'
fi
exit 0
fi
exit 1
fi
# Returns stack info
# If it already exists
if [ $ACTION == "inspect" ]; then
if [ -n "$STACK" ]; then
if [ $QUIET_MODE == "false" ]; then
echo "$STACK"
else
# Only display the stack name in quiet mode
echo "$STACK" | jq -r ".Name"
fi
exit 0
fi
exit 1
fi
# Get list of all stacks
if [ $ACTION == "ls" ]; then
if [ $QUIET_MODE == "false" ]; then
# Returns response in JSON format
echo "$STACKS"
else
# Only display stack names in quiet mode
echo "$STACKS" | jq -r '.[] | [.Name] | add'
fi
exit 0
fi
# Lint the Docker compose/stack file
if [ $ACTION == "lint" ]; then
lint
exit 0
fi
# Get list of all actions who can be used for this program
if [ $ACTION == "actions" ]; then
echo "Portainer Stack Utils, version $VERSION"
echo ""
display_actions_message
exit 0
fi
if [[ ! ${ACTIONS[*]} =~ $ACTION ]]; then
echo_error "Error: Unknown action \"$ACTION\"."
exit 1
fi
}
################################
# Set globals #
# Globals: #
# ACTION #
# PORTAINER_USER #
# PORTAINER_PASSWORD #
# PORTAINER_AUTH_TOKEN #
# PORTAINER_URL #
# PORTAINER_STACK_NAME #
# PORTAINER_SERVICE_NAME #
# DOCKER_COMPOSE_FILE #
# DOCKER_COMPOSE_LINT #
# ENVIRONMENT_VARIABLES_FILE #
# PORTAINER_ENDPOINT #
# PORTAINER_PRUNE #
# TIMEOUT #
# AUTO_DETECT_JOB #
# HTTPIE_VERIFY_SSL #
# VERBOSE_MODE #
# DEBUG_MODE #
# QUIET_MODE #
# STRICT_MODE #
# MASKED_VARIABLES #
# Arguments: #
# None #
# Returns: #
# None #
################################
set_globals() {
# Set arguments through envvars
VERSION=${VERSION}
ACTIONS=${ACTIONS}
ACTION=${ACTION}
PORTAINER_AUTH_TOKEN=${PORTAINER_AUTH_TOKEN}
PORTAINER_USER=${PORTAINER_USER}
PORTAINER_PASSWORD=${PORTAINER_PASSWORD}
PORTAINER_URL=${PORTAINER_URL}
PORTAINER_STACK_NAME=${PORTAINER_STACK_NAME}
PORTAINER_SERVICE_NAME=${PORTAINER_SERVICE_NAME}
DOCKER_COMPOSE_FILE=${DOCKER_COMPOSE_FILE}
DOCKER_COMPOSE_LINT=${DOCKER_COMPOSE_LINT:-"false"}
ENVIRONMENT_VARIABLES_FILE=${ENVIRONMENT_VARIABLES_FILE}
PORTAINER_ENDPOINT=${PORTAINER_ENDPOINT:-"1"}
PORTAINER_PRUNE=${PORTAINER_PRUNE:-"false"}
TIMEOUT=${TIMEOUT:-100}
AUTO_DETECT_JOB=${AUTO_DETECT_JOB:-"true"}
HTTPIE_VERIFY_SSL=${HTTPIE_VERIFY_SSL:-"yes"}
VERBOSE_MODE=${VERBOSE_MODE:-"false"}
DEBUG_MODE=${DEBUG_MODE:-"false"}
QUIET_MODE=${QUIET_MODE:-"false"}
STRICT_MODE=${STRICT_MODE:-"false"}
MASKED_VARIABLES=${MASKED_VARIABLES:-"false"}
# Set arguments through argument and options (overwrite envvars)
inputs "$@"
# Print config (only if debug mode is active)
echo_debug "ACTION -> $ACTION"
echo_debug "PORTAINER_USER -> $PORTAINER_USER"
echo_debug "PORTAINER_PASSWORD -> $PORTAINER_PASSWORD"
echo_debug "PORTAINER_AUTH_TOKEN -> $PORTAINER_AUTH_TOKEN"
echo_debug "PORTAINER_URL -> $PORTAINER_URL"
echo_debug "PORTAINER_STACK_NAME -> $PORTAINER_STACK_NAME"
echo_debug "PORTAINER_SERVICE_NAME -> $PORTAINER_SERVICE_NAME"
echo_debug "DOCKER_COMPOSE_FILE -> $DOCKER_COMPOSE_FILE"
echo_debug "DOCKER_COMPOSE_LINT -> $DOCKER_COMPOSE_LINT"
echo_debug "ENVIRONMENT_VARIABLES_FILE -> $ENVIRONMENT_VARIABLES_FILE"
echo_debug "PORTAINER_ENDPOINT -> $PORTAINER_ENDPOINT"
echo_debug "PORTAINER_PRUNE -> $PORTAINER_PRUNE"
echo_debug "TIMEOUT -> $TIMEOUT"
echo_debug "AUTO_DETECT_JOB -> $AUTO_DETECT_JOB"
echo_debug "HTTPIE_VERIFY_SSL -> $HTTPIE_VERIFY_SSL"
echo_debug "VERBOSE_MODE -> $VERBOSE_MODE"
echo_debug "DEBUG_MODE -> $DEBUG_MODE"
echo_debug "QUIET_MODE -> $QUIET_MODE"
echo_debug "STRICT_MODE -> $STRICT_MODE"
echo_debug "MASKED_VARIABLES -> $MASKED_VARIABLES"
# Check required arguments have been provided
check_argument "$ACTION" "action" "ACTION" "a" "action"
if [[ ! ${ACTIONS_TEXT_ONLY[*]} =~ $ACTION ]]; then
if [ -z "$PORTAINER_AUTH_TOKEN" ]; then
check_argument "$PORTAINER_USER" "portainer user" "PORTAINER_USER" "u" "user"
check_argument "$PORTAINER_PASSWORD" "portainer password" "PORTAINER_PASSWORD" "p" "password"
fi
check_argument "$PORTAINER_URL" "portainer url" "PORTAINER_URL" "l" "url"
fi
if [ "$ACTION" == "deploy" ] || [ "$ACTION" == "lint" ]; then
check_argument "$DOCKER_COMPOSE_FILE" "docker compose file" "DOCKER_COMPOSE_FILE" "c" "compose-file"
if [ -n "$ENVIRONMENT_VARIABLES_FILE" ] && [[ ! -f "$ENVIRONMENT_VARIABLES_FILE" ]]; then
echo_error "Error: File path \"$ENVIRONMENT_VARIABLES_FILE\" not found for \"ENVIRONMENT_VARIABLES_FILE\" environment variable or the \"-g\" flag or the \"--env-file\" option."
exit 1
fi
fi
if [ "$ACTION" != "ls" ] && [ "$ACTION" != "login" ] && [ "$ACTION" != "system:info" ] && [[ ! ${ACTIONS_TEXT_ONLY[*]} =~ $ACTION ]]; then
check_argument "$PORTAINER_STACK_NAME" "portainer stack name" "PORTAINER_STACK_NAME" "n" "name"
fi
}
inputs() {
while [ $# -gt 0 ]; do
case "$1" in
-A=*|--auth-token=*|-A|--auth-token)
PORTAINER_AUTH_TOKEN=$(input_option "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-u=*|--user=*|-u|--user)
PORTAINER_USER=$(input_option "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-p=*|--password=*|-p|--password)
PORTAINER_PASSWORD=$(input_option "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-l=*|--url=*|-l|--url)
PORTAINER_URL=$(input_option "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-n=*|--name=*|-n|--name)
PORTAINER_STACK_NAME=$(input_option "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-c=*|-f=*|--compose-file=*|--file=*|-c|-f|--compose-file|--file)
DOCKER_COMPOSE_FILE=$(input_option "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-C=*|-F=*|--compose-file-base64=*|--file-base64=*|-C|-F|--compose-file-base64|--file-base64)
local docker_compose_file_base64
docker_compose_file_base64=$(input_option "$1" "$2")
echo "$docker_compose_file_base64" | base64 -d > docker_compose_file_from_base64.yml
DOCKER_COMPOSE_FILE=docker_compose_file_from_base64.yml
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-L|--lint|-L=*|--lint=*)
DOCKER_COMPOSE_LINT=$(input_flag "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-g=*|--env-file=*|-g|--env-file)
ENVIRONMENT_VARIABLES_FILE=$(input_option "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-G=*|--env-file-base64=*|-G|--env-file-base64)
local env_file_base64
env_file_base64=$(input_option "$1" "$2")
echo "$env_file_base64" | base64 -d > env_file_from_base64
ENVIRONMENT_VARIABLES_FILE=env_file_from_base64
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-e=*|--endpoint=*|-e|--endpoint)
PORTAINER_ENDPOINT=$(input_option "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-r|--prune|-r=*|--prune=*)
PORTAINER_PRUNE=$(input_flag "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-T=*|--timeout=*|-T|--timeout)
TIMEOUT=$(input_option "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-j|--detect-job|-j=*|--detect-job=*)
AUTO_DETECT_JOB=$(input_flag "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-S=*|--service=*|-S|--service)
PORTAINER_SERVICE_NAME=$(input_option "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-d|--debug|-d=*|--debug=*)
DEBUG_MODE=$(input_flag "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-v|--verbose|-v=*|--verbose=*)
VERBOSE_MODE=$(input_flag "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-m|--masked-variables|-m=*|--masked-variables=*)
MASKED_VARIABLES=$(input_flag "$1" "$2" "true extended false")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-q|--quiet|-q=*|--quiet=*)
QUIET_MODE=$(input_flag "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-t|--strict|-t=*|--strict=*)
STRICT_MODE=$(input_flag "$1" "$2")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-i|--insecure|-i=*|--insecure=*)
local insecure
insecure=$(input_flag "$1" "$2")
if [ "$insecure" == "true" ]; then
HTTPIE_VERIFY_SSL="no"
else
HTTPIE_VERIFY_SSL="yes"
fi
if [ "$HTTPIE_VERIFY_SSL" == "no" ] && [ -z "$PYTHONWARNINGS" ]; then
# Fix httpie with Ubuntu 16.04
PYTHONWARNINGS="ignore:Unverified HTTPS request"
fi
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
-s|--secure|-s=*|--secure=*)
echo_verbose "DEPRECATED: Use '--insecure' option, instead of this '$1' option"
HTTPIE_VERIFY_SSL=$(input_flag "$1" "$2" "yes no" "no")
if [ "$HTTPIE_VERIFY_SSL" == "no" ] && [ -z "$PYTHONWARNINGS" ]; then
# Fix httpie with Ubuntu 16.04
PYTHONWARNINGS="ignore:Unverified HTTPS request"
fi
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
actions)
ACTION="actions"
;;
-V|--version|version)
if [ -z "$ACTION" ]; then
ACTION="version"
echo "Portainer Stack Utils, version $VERSION
License GPLv3: GNU GPL version 3"
else
input_error "Error: invalid option '$1' for the '$ACTION' action"
exit 1
fi
;;
-h|--help|help)
if [ -z "$ACTION" ] || [ "$1" == "help" ]; then
ACTION="help"
display_help_message
else
display_help_action_message
ACTION="help"
fi
exit 0
;;
-a=*|--action=*|-a|--action)
# To keep backwards compatibility with psu 0.1.x
echo_verbose "DEPRECATED: Use 'psu <action> [options]' command, instead of using this '$1' option"
ACTION=$(input_option "$1" "$2" "$ACTIONS")
if [ -n "$2" ] && [[ ! $2 =~ ^-.+$ ]] ; then
# When the second argument is the value of the current option
shift
fi
;;
*)
# deploy|rm|ls|inspect|status|tasks|services... argument
if [ -n "${ACTIONS_ALIASES[$1]}" ] && [ -z "$ACTION" ]; then
# Use aliased action '$1' who use the action '${ACTIONS_ALIASES[$1]}'"
ACTION="${ACTIONS_ALIASES[$1]}";
elif [[ ${ACTIONS[*]} =~ $1 ]]; then
if [ -z "$ACTION" ]; then
ACTION="$1";
else
input_error "Error: <action> argument already set with the '$ACTION' value"
exit 1
fi
else
input_error "Error: Unknown action '$1', run the 'psu help' command for more information"
exit 1
fi
esac
shift
done
if [ -z "$ACTION" ]; then
input_error "Error: <action> argument is required, run the 'psu help' command for more information"
exit 1
fi
}
input_option() {
local option
local argument
local value
local allowed_values
option="$1"
argument="$2"
allowed_values="$3"
value="${option#*=}"
if [ "$value" == "$option" ]; then
if [[ -n $argument ]] && [[ ! $argument =~ ^-.+$ ]]; then
# When the second argument is the value of the current option
value="$argument"
else
unset value
if [ -n "$argument" ]; then
input_error "Error: wrong value '$argument' given for the '$option' option"
exit 1
fi
fi
fi
if [ -n "$value" ]; then
if [ -z "$allowed_values" ] || [[ ${allowed_values[*]} =~ $value ]]; then
echo "$value"
else
input_error "Error: wrong value given for the '${option%=*}' option, should be '${allowed_values// /\' or \'}'"
exit 1
fi
else
input_error "Error: no value given for the '$option' option"
exit 1
fi
}
input_flag() {
local option
local argument
local value
local allowed_values
local default_value
option="$1"
argument="$2"
allowed_values="${3:-"true false"}"
default_value="${4:-"true"}"
value="${option#*=}"
if [ "$value" == "$option" ]; then
if [[ -n $argument ]] && [[ ! $argument =~ ^-.+$ ]]; then
# Second argument is a value for the current option
value="$argument"
else
value="$default_value"
fi
fi
if [ -z "$allowed_values" ] || [[ ${allowed_values[*]} =~ $value ]]; then
echo "$value"
else
input_error "Error: wrong value given for the '${option%=*}' option, should be '${allowed_values// /\' or \'}'"
exit 1
fi
}
input_error() {
local message
if [ -n "$1" ]; then
message="$1"
else
message="Error: Invalid argument."
fi
echo_error "$message"
}
############################
# Print an error to stderr #
# Globals: #
# None #
# Arguments: #
# $1 Error message #
# Returns: #
# None #
############################
echo_error() {
local error_message="$@"
local red='\033[0;31m'
local nc='\033[0m'
echo -e "${red}[$(date +'%Y-%m-%dT%H:%M:%S%z')]: ${error_message}${nc}" >&2
}
#######################################
# Check a parameter has been provided #
# Globals: #
# None #
# Arguments: #
# $1 Argument value #
# $2 Argument name #
# $3 Argument envvar #
# $4 Argument flag #
# Returns: #
# None #
#######################################
check_argument() {
local argument_value=$1
local argument_name=$2
local argument_envvar=$3
local argument_flag=$4
local argument_option=$5
if [ -z "$argument_value" ]; then
echo_error "Error: Missing argument \"$argument_name\"."
echo_error "Try setting \"$argument_envvar\" environment variable $(if [ -n "$argument_flag" ]; then echo or using the \"-$argument_flag\" flag; fi)$(if [ -n "$argument_option" ]; then echo " or using the \"--$argument_option\" option"; fi)."
exit 1
fi
}
###########################################
# Checks for error exit codes from httpie #
# Globals: #
# None #
# Arguments: #
# $1 Httpie exit code #
# $2 Response returned by Portainer API #
# Returns: #
# None #
###########################################
check_for_errors() {
local exit_code=$1
local response=$2
if [ $exit_code -ne 0 ]; then
case $exit_code in
2) echo_error 'Request timed out!' ;;
3) echo_error 'Unexpected HTTP 3xx Redirection!' ;;
4)
echo_error 'HTTP 4xx Client Error!'
echo_error $response
;;
5)
echo_error 'HTTP 5xx Server Error!'
echo_error $response
;;
6) echo_error 'Exceeded --max-redirects=<n> redirects!' ;;
*) echo_error 'Unholy Error!' ;;
esac
exit 1
fi
}
echo_debug_safe_json() {
echo_safe_json "debug" "$1" "$2"
}
echo_verbose_safe_json() {
echo_safe_json "verbose" "$1" "$2"
}
echo_safe_json() {
local type="$1"
local message="$2"
local json="$3"
local temp_file
# If the $json variable has an '.Env' entry
# We parse its content to mask sensitive values
if [ "$MASKED_VARIABLES" == "extended" ] && [ -n "$(echo "$json" | jq -j 'if type == "array" then .[] else . end | .Env // ""')" ]; then
temp_file=".stack_envs-$(echo "$(date +%s%3N)")"
(
echo "$json" | jq -r 'if type == "array" then .[] else . end | .Env | map(.name = .name + "=" + .value) | map (.name) | .[]' | sed "s/\"/\\\\\"/g" | sed "s/^\([^=]\{1,\}=\)\(.* .*\)$/\1\"\2\"/" > $temp_file && \
. $temp_file && rm -f $temp_file && \
if [ "$type" == "debug" ]; then \
echo_debug "$message"; \
elif [ "$type" == "verbose" ]; then \
echo_verbose "$message"; \
fi
)
else
if [ "$type" == "debug" ]; then
echo_debug "$message"
elif [ "$type" == "verbose" ]; then
echo_verbose "$message"
fi
fi
}
###########################################
# Print message if verbose mode is active #
# Globals: #
# VERBOSE_MODE #
# Arguments: #
# $1 Message #
# Returns: #
# None #
###########################################
echo_verbose() {
local message=$1
local yellow='\033[1;33m'
local nc='\033[0m'
if [ $VERBOSE_MODE == "true" ]; then
local verbose_message
verbose_message=$(mask_variables "$message")
echo -e "${yellow}${verbose_message}${nc}"
fi
}
#########################################
# Print message if debug mode is active #
# Globals: #
# DEBUG_MODE #
# Arguments: #
# $1 Message #
# Returns: #
# None #
#########################################
echo_debug() {
local message=$1
if [ $DEBUG_MODE == "true" ]; then
local debug_message
debug_message=$(mask_variables "$message")
echo -e "${debug_message}"
fi
}
mask_variables() {
local message="$1"
if [ "$MASKED_VARIABLES" == "true" ] && [ -n "$PORTAINER_PASSWORD" ]; then
# Mask PORTAINER_PASSWORD and PORTAINER_AUTH_TOKEN variable values
local auth_token_masked
auth_token_masked="$PORTAINER_AUTH_TOKEN"
if [ -z "$auth_token_masked" ]; then
auth_token_masked="$PORTAINER_PASSWORD"
fi
message=$(echo "$message" | sed "s/\($PORTAINER_PASSWORD\|$auth_token_masked\)/[MASKED]/g")
elif [ "$MASKED_VARIABLES" == "extended" ]; then
# Mask all variable values with PASSWORD or TOKEN in their name
local masked_vars
# Get all declared variable names and filtering by specific terms
masked_vars="$(compgen -v | grep -i 'PASSWORD\|TOKEN')"
for masked_var in $masked_vars; do
if [ -n "$masked_var" ] && [ -n "${!masked_var}" ]; then
# Converts multi lines value to one line value
masked_value="$(echo ${!masked_var})"
message="$(echo "$message" | sed "s/$masked_value/[MASKED]/g")"
fi
done
fi
echo "$message"
}
################################
# Create/update a stack #
# Globals: #
# STACK #
# DOCKER_COMPOSE_FILE #
# DOCKER_COMPOSE_LINT #
# PORTAINER_STACK_NAME #
# PORTAINER_URL #
# ENVIRONMENT_VARIABLES_FILE #
# HTTPIE_VERIFY_SSL #
# PORTAINER_ENDPOINT #
# PORTAINER_AUTH_TOKEN #
# Arguments: #
# None #
# Returns: #
# None #
################################
deploy() {
# Lint docker-compose file if --lint option is "true"
if [ "$DOCKER_COMPOSE_LINT" == "true" ]; then
lint
fi
# Read docker-compose file content
local docker_compose_file_content
docker_compose_file_content=$(cat "$DOCKER_COMPOSE_FILE")
# Remove carriage returns
docker_compose_file_content="${docker_compose_file_content//$'\r'/''}"
# Escape double quotes
docker_compose_file_content="${docker_compose_file_content//$'"'/'\"'}"
# Escape newlines
docker_compose_file_content="${docker_compose_file_content//$'\n'/'\n'}"
# If the stack does not exist
if [ -z "$STACK" ]; then
echo_verbose "Stack $PORTAINER_STACK_NAME does not exist."
# Get Docker info
echo_verbose "Getting Docker info..."
local docker_info
docker_info=$(docker_info)
check_for_errors $? "$docker_info"
echo_debug "Docker info -> $(echo $docker_info | jq -C .)"
# Get Docker swarm ID
echo_verbose "Getting swarm cluster (if any)..."
local swarm_id
swarm_id=$(echo $docker_info | jq -r ".Swarm.Cluster.ID // empty")
echo_debug "Swarm ID -> $swarm_id"
# If there is no swarm ID
if [ -z "$swarm_id" ];then
echo_verbose "Swarm cluster not found."
echo_verbose "Preparing stack JSON..."
local stack_envvars