-
Notifications
You must be signed in to change notification settings - Fork 3
/
gcpcmd.sh
executable file
·1402 lines (1324 loc) · 57.6 KB
/
gcpcmd.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
# This script is to perform Google Cloud Platform (GCP) actions for creating, starting, stopping, deleting FortiPoC's
# 2018113001 Ferry Kemps, Initial release
# 2018120401 Ferry Kemps, added --zone argument to override default zone
# 2019011601 Ferry Kemps, added variables, conditional gcloud cmd executions
# 2019020401 Ferry Kemps, added simple menu enable/disable setting
# 2019031301 Ferry Kemps, added config file option
# 2019033001 Ferry Kemps, added gcp repo option to load images and poc-definitions
# 2019033002 Ferry Kemps, added sme as product to facilitate sme-event combos
# 2019050201 Ferry Kemps, increased amount of PoC-definitions to load
# 2019060301 Ferry Kemps, updated FPIMAGE to 1-5-49
# 2019062501 Ferry Kemps, added xa as product to facilitate NSE Xperts Academy events
# 2019070101 Ferry Kemps, increased poc definitions to 6
# 2019081401 Ferry Kemps, added test as product to facilitate temp installs
# 2019081501 Ferry Kemps, changed example config file name to be diff from gcpcmd command
# 2019083001 Ferry Kemps, expanded poc definitions to 8
# 2019100701 Ferry Kemps, added FPPREPEND to custom label instances names.
# 2019101001 Ferry Kemps, added config file check on action build
# 2019101101 Ferry Kemps, added listpubip option to retrieve pub IPs (concatenated for other script)
# 2019101802 Ferry Kemps, added FSW, FSA, appsec as a products/solutions
# 2019102301 Ferry Kemps, Updated the help info
# 2019110101 Ferry Kemps, Commented out simple menu option. Some screen output cleanup
# 2019110441 Ferry Kemps, Adding random sleep time to avoid GCP DB lock error
# 2019110501 Ferry Kemps, Little output corrections
# 2019110601 Ferry Kemps, Moved logfiles to logs directory
# 2019111101 Ferry Kemps, Added automatic defaults per ~/.fpoc/gcpcmd.conf
# 2019111102 Ferry Kemps, Expanded user defaults
# 2019111401 Ferry Kemps, Added add/remove IP-address to GCP ACL
# 2019111501 Ferry Kemps, Added instance clone function
# 2019111502 Ferry Kemps, Changed number generator, added comments
# 2019112201 Ferry Kemps, Fixed license server inquiry
# 2019112202 Ferry Kemps, Added conf dir creation and seq fix
# 2019112501 Ferry Kemps, Clarified GCP billing project ID
# 2019112502 Ferry Kemps, Changed GCP instance labling to list owner
# 2019112503 Ferry Kemps, Changed moment of conf and log dir creation
# 2019112601 Ferry Kemps, Added global list based on owner label
# 2019112801 Ferry Kemps, Empty license server fix
# 2019112901 Ferry Kemps, Cloning now supports labeling
# 2019120501 Ferry Kemps, Added <custom-name> for product/solution, arguments sorted alphabetic
# 2020011001 Ferry Kemps, Added [IP-address] option to --ip-address-add|remove and --ip-address-list
# 2020012701 Ferry Kemps, Use fortipoc-1.7.7 by default, add disclaimer, declare PoC-definitions, introduced group-management
# 2020012703 Ferry Kemps, Corrected CONFFILE check
# 2020012704 Ferry Kemps, Code clean-up, group management
# 2020012705 Ferry Kemps, Added --initials option for group management
# 2020013101 Ferry Kemps, Fixed -d option, added group function for cloning
# 2020022001 Ferry Kemps, Cleared GCPREPO example
# 2020052501 Ferry Kemps, Modified banner
# 2020060201 Ferry Kemps, Added option to change machine-type
# 2020072201 Ferry Kemps, Improved WARNING message on missing software packages.
# 2020081301 Ferry Kemps, Replaced gcloud beta command
# 2020081302 Ferry Kemps, Changed GCP license server input request
# 2020082601 Ferry Kemps, Pre-populated ProjectId and Service Account preferences
# 2020082701 Ferry Kemps, Added -p|--preferences option, renamed -c|--config file to -b|--build-file, improved preference questions.
# 2020110301 Ferry Kemps, Changed standard machine-types to 5 options, added SSH-key option, choice for snapshot on cloning
# 2020110401 Ferry Kemps, Added online new version checking
# 2021040601 Ferry Kemps, Rewrite of cloning from snapshot to machine-image to avoid clone limits
# 2021050401 Ferry Kemps, Added fortipoc-deny-default tag to close default GCP open ports
# 2021050501 Ferry Kemps, Little typo fixes
# 2021050502 Ferry Kemps, Fixed SSHKEY check, added dig command tool check
# 2021061601 Ferry Kemps, Sanity check on multiple retrieved Service Accounts.
# 2021071501 Ferry Kemps, Added automatic firewall-rules creation, updated instance tagging and option to toggle tags for controlling access.
# 2021071501 Ferry Kemps, Expanded global access listing, by default global access disabled on instance create/clone
# 2021071901 Ferry Kemps, Added globallist action to list ACL per user selection
# 2021071902 Ferry Kemps, Added -z|--zone override option
# 2021082401 Ferry Kemps, Fixed global access list reversed issue
# 2021090701 Ferry Kemps, Code restructed, improved formatting, better Global Access messaging, firewall-rule fix on build
# 2021091401 Ferry Kemps, Added update command
# 2021111701 Ferry Kemps, Renamed global/globallist to globalaccess/globalaccesslist
# 2022011001 Ferry Kemps, Textual updates on help page
# 2022080401 Ferry Kemps, Changed parallel option -j0 to supress warning
# 2022080501 Ferry Kemps, Added option to move instances to other zone
# 2022110401 Ferry Kemps, Updated help for --initials option to override
# 2023070301 Ferry Kemps, Added gcloud beta instance rename optopn
# 2023071001 Ferry Kemps, Remove debug and text correction on rename option
# 2023113001 Ferry Kemps, Added labellist action to list labels, add/remove labels, updated instance fortipoc label
# 2023121201 Ferry Kemps, Added label replace option
# 2024053001 Ferry Kemps, Added -lr | --list-running option to list RUNNING instances
# 2024072901 Ferry Kemps, Added creation of "default" VPC and Networks if missing, optimized the gcloud validation delay
# 2024080101 Ferry Kemps, Major update to support multi-project function
# 2024080102 Ferry Kemps, Updated onboarding project selection, clone max text
# 2024080103 Ferry Kemps, Corrected labelmodify bug with numbering
# 2024080104 Ferry Kemps, Added note for Compute Engine API, added Type name override option
# 2024080105 Ferry Kemps, Added network tag add/remove/replace with action accesslist, accessmodify. Removed globalaccesslist action
# 2024080201 Ferry Kemps, Added quit option during project sign-up to exit
# 2024080202 Ferry Kemps, Added machinetype e2-medium for allways-on small instances
# 2024080501 Ferry Kemps, Corrected global command creation
# 2024080601 Ferry Kemps, Updated OWNER label definition, updated the fpoc-example.conf directory
# 2024080602 Ferry Kemps, Improved the upload image feature
# 2024080701 Ferry Kemps, Removed obsolete fortipoc-http-https-redir network tag, fixed VPN/FIREWALLRULE in preference file
# 2024081401 Ferry Kemps, Shell code syntax checked and corrected
# 2024081501 Ferry Kemps, Syntax updates, beta statements removed, reduced pd-standard-disk to 200GB to reduce storage cost, added bulk cloning
# 2024081601 Ferry Kemps, Optimizing the bulk clone option
# 2024082301 Ferry Kemps, Supressed instance delete output, added coloring, fixed --project-select/add, image build
GCPCMDVERSION="2024082301"
# Disclaimer: This tool comes without warranty of any kind.
# Use it at your own risk. We assume no liability for the accuracy, group-management
# correctness, completeness, or usefulness of any information
# provided nor for any sort of damages using this tool may cause.
# default zones where to deploy per region. You can adjust to deploy closest to your location
ASIA="asia-southeast1-b"
EUROPE="europe-west4-a"
AMERICA="us-central1-c"
# ------------------------------------------------
# ------ No editing needed beyond this point -----
# ------------------------------------------------
# Let's create uniq logfiles with date-time stamp
PARALLELOPT="--joblog logs/logfile-$(date +%Y%m%d%H%M%S) -j 100 "
# Firewall-rules for instance tagging
WORKSHOPVPC="default"
WORKSHOPSOURCENETWORKS="workshop-source-networks"
WORKSHOPSOURCEANY="workshop-source-any"
DSTTCPPORTS="tcp:22,tcp:80,tcp:443,tcp:8000,tcp:8080,tcp:8888,tcp:10000-20000,tcp:20808,tcp:20909,tcp:22222"
DSTUDPPORTS="udp:53,udp:514,udp:1812,udp:1813"
TYPE="fpoc"
# Clear POC-definitions
POCDEFINITION1=""
POCDEFINITION2=""
POCDEFINITION3=""
POCDEFINITION4=""
POCDEFINITION5=""
POCDEFINITION6=""
POCDEFINITION7=""
POCDEFINITION8=""
# Color code definitions
BLACK='\033[0;30m' ; DARKGRAY='\033[1;30m'
RED='\033[0;31m' ; LIGHTRED='\033[1;31m'
GREEN='\033[0;32m' ; LIGHTGREEN='\033[1;32m'
ORANGE='\033[0;33m' ; export YELLOW='\033[1;33m'
BLUE='\033[0;34m' ; LIGHTBLUE='\033[1;34m'
PURPLE='\033[0;35m' ; LIGHTPURPLE='\033[1;35m'
CYAN='\033[0;36m' ; LIGHTCYAN='\033[1;36m'
LIGHTGRAY='\033[0;37m' ; WHITE='\033[1;37m'
REDREVERSED='\033[0;41m' ; GREENREVERSED='\033[0;42m'
REDREVERSEDNEW='\033[1;41m' ; GREENREVERSEDNEW='\033[1;42m'
GREENNEW='\033[1;32m'
NOCOLOR='\033[0m'
###############################
# Functions
###############################
function checkdefaultnetwork() {
if [ "${VPC}" != "validated" ]; then
if (! gcloud compute networks describe ${WORKSHOPVPC} --format=none > /dev/null 2>&1); then
echo "Default VPC networks not found, creating it"
gcloud compute networks create ${WORKSHOPVPC} \
--description="Default VPC network for FortiPoC" \
--mtu=1460
# Add VPC check to personal preferences file
fi
sed -i '' "s/GCPCMD_VPC\[${DEFAULTPROJECT}\].*/GCPCMD_VPC\[${DEFAULTPROJECT}\]=\"validated\"/" "${GCPCMDCONF}"
fi
}
function checkfirewallrules() {
#check if firewall-rules exist else create them
if [ "${FIREWALLRULES}" != "validated" ]; then
if (! gcloud compute firewall-rules describe ${WORKSHOPSOURCENETWORKS} --format=none >/dev/null 2>&1); then
echo "Firewall-rule ${WORKSHOPSOURCENETWORKS} not found, creating it"
gcloud compute firewall-rules create ${WORKSHOPSOURCENETWORKS} \
--allow=${DSTTCPPORTS},${DSTUDPPORTS} \
--description="Allow access from temporary workshop networks" \
--direction=INGRESS \
--priority=300 \
--source-ranges=10.10.10.10 \
--target-tags=${WORKSHOPSOURCENETWORKS} \
--no-user-output-enabled
fi
if (! gcloud compute firewall-rules describe ${WORKSHOPSOURCEANY} --format=none >/dev/null 2>&1); then
echo "Firewall-rule ${WORKSHOPSOURCEANY} not found, creating it (disabled by default)"
gcloud compute firewall-rules create ${WORKSHOPSOURCEANY} \
--allow=${DSTTCPPORTS},${DSTUDPPORTS} \
--description="Allow access from temporary workshop networks" \
--direction=INGRESS \
--priority=300 \
--source-ranges=0.0.0.0/0 \
--target-tags=${WORKSHOPSOURCEANY} \
--disabled \
--no-user-output-enabled
# Add Firewallrules check to personal preferences file
fi
#echo "GCPCMD_FIREWALLRULES[${DEFAULTPROJECT}]=\"validated\"" >> ${GCPCMDCONF}
sed -i '' "s/GCPCMD_FIREWALLRULES\[${DEFAULTPROJECT}\].*/GCPCMD_FIREWALLRULES[${DEFAULTPROJECT}]=\"validated\"/" "${GCPCMDCONF}"
fi
}
function togglefirewallruleany() {
if [ "${1}" = "disable" ]; then
gcloud compute firewall-rules update ${WORKSHOPSOURCEANY} --disabled --no-user-output-enabled
echo "Global access to instances => Disabled"
elif [ "${1}" = "enable" ]; then
gcloud compute firewall-rules update ${WORKSHOPSOURCEANY} --no-disabled --no-user-output-enabled
echo "Global access to instances => Enabled"
elif [ "${1}" = "status" ]; then
GLOBALACCESSSTATUS=$(gcloud compute firewall-rules describe ${WORKSHOPSOURCEANY} --format=json | jq -r '.disabled')
[ "${GLOBALACCESSSTATUS}" = "false" ] && GLOBALACCESSSTATUS="Enabled" || GLOBALACCESSSTATUS="Disabled"
echo "Global access status: ${GLOBALACCESSSTATUS}"
else
echo "Unknown global access request"
exit
fi
echo ""
}
function instancefirewallrules() {
displayheader
printf "Listing all global instances and firewall-rules for Project:${CYAN}${GCPPROJECT}${NOCOLOR} Owner:${CYAN}${OWNER}${NOCOLOR} or Group:${CYAN}${FPGROUP}${NOCOLOR}\n"
gcloud compute instances list --filter="((labels.owner:${OWNER} OR labels.group:${FPGROUP}) AND tags.items:*)" --format="table[box,title='✨ FIREWALL-RULES ✨'](name:label=INSTANCE, zone:label=ZONE, tags.items:label=TAGS,STATUS)"
}
function instancelabels() {
displayheader
printf "Listing all global instances and labels for Project:${CYAN}${GCPPROJECT}${NOCOLOR} Owner:${OWNER} or Group:${CYAN}${FPGROUP}${NOCOLOR}\n"
gcloud compute instances list --filter="(labels.owner:${OWNER} OR labels.group:${FPGROUP})" --format="table[box, title='✨ LABELS ✨'](name:label=INSTANCE, zone:label=ZONE, labels:label=LABELS,STATUS)"
}
function displayheader() {
clear
echo "-------------------------------------------------------------------------------------------"
printf " ${YELLOW}FortiPoC Toolkit for Google Cloud Platform${NOCOLOR} \n"
echo "-------------------------------------------------------------------------------------------"
echo ""
}
# Function to display personal config preferences
function displaypreferences() {
local CONFFILE=$1
echo "Your personal configuration preferences"
echo ""
cat "${CONFFILE}"
}
# Function to validate IP-address format
function validateIP() {
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 239 && ${ip[1]} -le 255 && \
${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
# Function to add/remove workshop location Public IP-address to GCP ACL to allow access
function gcpaclupdate() {
CMD=$1
PUBLICIP=$2
if [ -z "${PUBLICIP}" ]; then
# Obtain current public IP-address
PUBLICIP=$(dig TXT -4 +short o-o.myaddr.l.google.com @ns1.google.com | sed -e 's/"//g')
fi
validateIP "${PUBLICIP}"
[ ! $? -eq 0 ] && (
echo "Public IP not retreavable or not valid"
exit
)
if [ "${CMD}" == add ]; then
echo "Adding public IP address ${PUBLICIP} to GCP ACL to allow access from the location"
while read -r line; do
if [ -z ${SOURCERANGE} ]; then
SOURCERANGE="$line"
else
SOURCERANGE="${SOURCERANGE},$line"
fi
done < <(gcloud compute firewall-rules list --filter="name=${WORKSHOPSOURCENETWORKS}" --format=json | jq -r '.[] .sourceRanges[]')
SOURCERANGE="${SOURCERANGE},${PUBLICIP}"
gcloud compute firewall-rules update ${WORKSHOPSOURCENETWORKS} --source-ranges=${SOURCERANGE}
echo "Current GCP ACL list"
gcloud compute firewall-rules list --filter="name=${WORKSHOPSOURCENETWORKS}" --format=json | jq -r '.[] .sourceRanges[]'
echo ""
elif [ "${CMD}" == "remove" ]; then
echo "Removing public IP address ${PUBLICIP} from GCP ACL to remove access from the location"
while read -r line; do
if [ -z ${SOURCERANGE} ]; then
[ ! $line == ${PUBLICIP} ] && SOURCERANGE="$line"
else
[ ! $line == ${PUBLICIP} ] && SOURCERANGE="${SOURCERANGE},$line"
fi
done < <(gcloud compute firewall-rules list --filter="name=${WORKSHOPSOURCENETWORKS}" --format=json | jq -r '.[] .sourceRanges[]')
gcloud compute firewall-rules update ${WORKSHOPSOURCENETWORKS} --source-ranges=${SOURCERANGE}
echo "Current GCP ACL list"
gcloud compute firewall-rules list --filter="name=${WORKSHOPSOURCENETWORKS}" --format=json | jq -r '.[] .sourceRanges[]'
echo ""
else
echo "Listing public-ip addresses on GCP ACL"
gcloud compute firewall-rules list --filter="name=${WORKSHOPSOURCENETWORKS}" --format=json | jq -r '.[] .sourceRanges[]'
echo ""
fi
}
# Function to list all globalaccess instances
function gcplistglobal {
OWNER=$1
FPGROUP=$2
WILDCARD=$3
if [ -z ${FPGROUP} ]; then
gcloud compute instances list --filter="labels.owner:${OWNER}"
else
if [ "${WILDCARD}" == "all" ]; then
gcloud compute instances list
else
gcloud compute instances list --filter="(labels.owner:${OWNER} OR labels.group:${FPGROUP})"
fi
fi
}
# Function to list all global RUNNING instances
function gcplistrunning {
OWNER=$1
FPGROUP=$2
STATUS="RUNNING"
if [ -z ${FPGROUP} ]; then
gcloud compute instances list --filter="labels.owner:${OWNER} AND status:${STATUS}"
else
gcloud compute instances list --filter="(labels.owner:${OWNER} OR labels.group:${FPGROUP}) AND status:${STATUS}"
fi
}
# Function to build a FortiPoC instance on GCP
function gcpbuild {
if [ "${CONFIGFILE}" == "" ]; then
echo "Build file missing. Use -b option to specify or to generate fpoc-example.conf file"
exit
fi
RANDOMSLEEP=$(((RANDOM % 10) + 1))s
FPPREPEND=$1
ZONE=$2
PRODUCT=$3
FPTITLE=$4
INSTANCE=$5
INSTANCENAME="${TYPE}-${FPPREPEND}-${PRODUCT}-${INSTANCE}"
echo "==> Sleeping ${RANDOMSLEEP} seconds to avoid GCP DB locking"
sleep ${RANDOMSLEEP}
echo "==> Creating instance ${INSTANCENAME}"
gcloud compute \
instances create ${INSTANCENAME} \
--project=${GCPPROJECT} \
--service-account=${GCPSERVICEACCOUNT} \
--verbosity=info \
--zone=${ZONE} \
--machine-type=${MACHINETYPE} \
--subnet=default --network-tier=PREMIUM \
--maintenance-policy=MIGRATE \
--scopes=https://www.googleapis.com/auth/devstorage.read_only,https://www.googleapis.com/auth/logging.write,https://www.googleapis.com/auth/monitoring.write,https://www.googleapis.com/auth/servicecontrol,https://www.googleapis.com/auth/service.management.readonly,https://www.googleapis.com/auth/trace.append \
--min-cpu-platform=Intel\ Broadwell --tags=fortipoc-deny-default,${WORKSHOPSOURCENETWORKS} \
--image=${FPIMAGE} \
--image-project=${GCPPROJECT} \
--boot-disk-size=200GB \
--boot-disk-type=pd-standard \
--boot-disk-device-name=${INSTANCENAME} \
--labels=${LABELS}
# Give Google 60 seconds to start the instance
echo ""
echo "==> Sleeping 90 seconds to allow FortiPoC booting up"
sleep 90
INSTANCEIP=$(gcloud compute instances describe ${INSTANCENAME} --zone=${ZONE} | grep natIP | awk '{ print $2 }')
echo ${INSTANCENAME} "=" ${INSTANCEIP}
if ! curl -k -q --retry 1 --connect-timeout 10 https://${INSTANCEIP}/ && echo "FortiPoC ${INSTANCENAME} on ${INSTANCEIP} reachable"
then
# [ $? != 0 ] && echo "==> Something went wrong. The new instance is not reachable"
echo "==> Something went wrong. The new instance is not reachable"
fi
# Now configure, load, prefetch and start PoC-definition
[ "${FPTRAILKEY}" != "" ] && (
echo "==> Registering FortiPoC"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "reg trial ${FPTRAILKEY}"
)
[ "${FPTITLE}" != "" ] && (
echo "==> Setting title"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "set gui title \"${FPTITLE}\""
)
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command 'set guest passwd guest'
[ "${GCPREPO}" != "" ] && (
echo "==> Adding repository"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "repo add gcp-${GCPREPO} https://gcp.repository.fortipoc.com/~#{GCPREPO}/ --unsigned"
)
[ ! -z ${LICENSESERVER} ] && (
echo "==> Setting licenseserver"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "set license https://${LICENSESERVER}/"
)
[ ! -z ${POCDEFINITION1} ] && (
echo "==> Loading poc-definition 1"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "poc repo define \"${POCDEFINITION1}\" refresh"
)
[ ! -z ${POCDEFINITION2} ] && (
echo "==> Loading poc-definition 2"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "poc repo define \"${POCDEFINITION2}\" refresh"
)
[ ! -z ${POCDEFINITION3} ] && (
echo "==> Loading poc-definition 3"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "poc repo define \"${POCDEFINITION3}\" refresh"
)
[ ! -z ${POCDEFINITION4} ] && (
echo "==> Loading poc-definition 4"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "poc repo define \"${POCDEFINITION4}\" refresh"
)
[ ! -z ${POCDEFINITION5} ] && (
echo "==> Loading poc-definition 5"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "poc repo define \"${POCDEFINITION5}\" refresh"
)
[ ! -z ${POCDEFINITION6} ] && (
echo "==> Loading poc-definition 6"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "poc repo define \"${POCDEFINITION6}\" refresh"
)
[ ! -z ${POCDEFINITION7} ] && (
echo "==> Loading poc-definition 7"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "poc repo define \"${POCDEFINITION7}\" refresh"
)
[ ! -z ${POCDEFINITION8} ] && (
echo "==> Loading poc-definition 8"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "poc repo define \"${POCDEFINITION8}\" refresh"
)
echo "==> Prefetching all images and documentation"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command 'poc prefetch all'
[ "${POCLAUNCH}" != "" ] && (
echo "==> Launching poc-definition"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "poc launch \"${POCLAUNCH}\""
)
[ "${SSHKEYPERSONAL}" != "" ] && (
echo "==> Adding personal SSH key"
gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "set ssh authorized keys \"${SSHKEYPERSONAL}\""
)
# [ "${FPSIMPLEMENU}" != "" ] && (echo "==> Setting GUI-mode to simple"; gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command "set gui simple ${FPSIMPLEMENU}")
echo "==> End of Build phase <=="
echo ""
}
# Function to bulk clone instances on GCP
function gcpclonebulk {
TYPE=$1
FPPREPEND=$2
PRODUCT=$3
IMAGENUMTOCLONE=$4
ZONE=$5
INSTANCE=$6
CLONEMACHINEIMAGE="${TYPE}-${FPPREPEND}-${PRODUCT}-${IMAGENUMTOCLONE}"
INSTANCENAME="${TYPE}-${FPPREPEND}-${PRODUCT}-${INSTANCE}"
echo " - Create instance ${INSTANCENAME}"
gcloud compute instances create ${INSTANCENAME} \
--project=${GCPPROJECT} \
--zone=${ZONE} \
--source-machine-image ${CLONEMACHINEIMAGE} > /dev/null 2>&1
}
# Function to clone instance(s) on GCP
function gcpclone {
read -r -p " FortiPoC instance number to clone : " FPNUMBERTOCLONE
read -r -p " Enter amount of FortiPoC's clones : " FPCOUNT
read -r -p " Enter start of numbered range : " FPNUMSTART
# Decrease FPCOUNT to get correct starting number
((FPCOUNT--))
FPNUMEND=$((FPNUMSTART+FPCOUNT))
# Mark the last instance number because we make FPNUMEND dynamic
FPNUMMAX=$FPNUMEND
# Make FPNUMBERTOCLONE in 3 digit format for aligned screen output
FPNUMBERTOCLONE=$(printf "%03d" ${FPNUMBERTOCLONE})
CLONESOURCE="${TYPE}-${FPPREPEND}-${PRODUCT}-${FPNUMBERTOCLONE}"
CLONEMACHINEIMAGE="${TYPE}-${FPPREPEND}-${PRODUCT}"
FPNUMSTARTUI=$(printf "%03d" ${FPNUMSTART})
FPNUMENDUI=$(printf "%03d" ${FPNUMEND})
if [ ! -z ${SET_FPGROUP} ] && [ ${SET_FPGROUP} == "true" ]; then
FPGROUP=${OVERRIDE_FPGROUP}
fi
echo ""
read -r -p "Okay to ${ACTION} ${CLONESOURCE} to ${TYPE}-${FPPREPEND}-${PRODUCT}-${FPNUMSTARTUI} till ${TYPE}-${FPPREPEND}-${PRODUCT}-${FPNUMENDUI}, Project=${GCPPROJECT}, region=${ZONE}. y/n? " choice
[ "${choice}" != "y" ] && exit
CLONESOURCE="${TYPE}-${FPPREPEND}-${PRODUCT}-${FPNUMBERTOCLONE}"
CLONEMACHINEIMAGE="${TYPE}-${FPPREPEND}-${PRODUCT}"
# Make a rough time estimate to show
CLONETIME=$((FPCOUNT/4))
[[ CLONETIME -eq 0 ]] && CLONETIME="couple"
echo ""; echo "==> Preparing machine-image(s)....be patienced, enjoy a tasty espresso (estimated ${CLONETIME} minutes))"
STARTTIME=$SECONDS
# Catch the 1 clone request
[[ $FPCOUNT -eq 0 ]] && ((FPCOUNT++))
# Run the loop to batch 5 builds at a time
for ((COUNT=0; COUNT<FPCOUNT; COUNT+=5))
do
echo " ...Wait a second for the next batch" #$COUNT"
echo "y" | gcloud compute machine-images delete ${CLONEMACHINEIMAGE}-${COUNT} >/dev/null 2>&1
gcloud compute machine-images create ${CLONEMACHINEIMAGE}-${COUNT} \
--source-instance ${CLONESOURCE} \
--source-instance-zone=${ZONE} >/dev/null 2>&1
FPNUMEND=$((FPNUMSTART+5))
# Check is another clone batch is needed
if [[ FPNUMSTART -le FPNUMMAX ]]
then
if [[ FPNUMEND -gt FPNUMMAX ]]
then
FPNUMEND=$FPNUMMAX
fi
# Make FPNUMBERTOCLONE in 3 digit format for aligned screen output
FPNUMSTARTUI=$(printf "%03d" ${FPNUMSTART})
FPNUMENDUI=$(printf "%03d" ${FPNUMEND})
echo " => Cloning instances ${CLONEMACHINEIMAGE}-${FPNUMSTARTUI} to ${CLONEMACHINEIMAGE}-${FPNUMENDUI}"
parallel ${PARALLELOPT} -j0 gcpclonebulk ${TYPE} ${FPPREPEND} ${PRODUCT} ${COUNT} ${ZONE} ::: $(seq -f%03g ${FPNUMSTART} ${FPNUMEND})
# Lets shutdown the new instance
#prallel ${PARALLELOPT} -j0 gcpstop ${FPPREPEND} ${ZONE} ${PRODUCT} ${COUNT} ::: $(seq -f%03g ${FPNUMSTART} ${FPNUMEND})
FPNUMSTART=$((FPNUMEND+1))
# exit the bulk building loop when START reached last instance (FPNUMMAX)
[[ FPNUMSTART -ge FPNUMMAX ]] && ((COUNT+=999))
fi
done
echo "==> Cloning finished"
# Show how long the cloning took
DURATION=$(( (SECONDS-STARTTIME)/60 ))
echo " It took: $DURATION minutes to clone."; echo ""
}
# Function to start instance
function gcpstart {
FPPREPEND=$1
ZONE=$2
PRODUCT=$3
INSTANCE=$4
INSTANCENAME="${TYPE}-${FPPREPEND}-${PRODUCT}-${INSTANCE}"
echo "==> Starting instance ${INSTANCENAME}"
gcloud compute instances start ${INSTANCENAME} --zone=${ZONE}
}
# Function to stop instance
function gcpstop {
FPPREPEND=$1
ZONE=$2
PRODUCT=$3
INSTANCE=$4
INSTANCENAME="${TYPE}-${FPPREPEND}-${PRODUCT}-${INSTANCE}"
echo "==> Stopping instance ${INSTANCENAME}"
# gcloud compute ssh admin@${INSTANCENAME} --zone ${ZONE} --command 'poc eject' # not working if admin pwd is set
gcloud compute instances stop ${INSTANCENAME} --zone=${ZONE} --quiet #> /dev/null 2>&1
}
# Function to delete instance
function gcpdelete {
FPPREPEND=$1
ZONE=$2
PRODUCT=$3
INSTANCE=$4
INSTANCENAME="${TYPE}-${FPPREPEND}-${PRODUCT}-${INSTANCE}"
echo "==> Deleting instance ${INSTANCENAME}"
echo yes | gcloud compute instances delete ${INSTANCENAME} --zone=${ZONE} > /dev/null 2>&1
}
# Function to change instance machinetype
function gcpmachinetype {
FPPREPEND=$1
ZONE=$2
PRODUCT=$3
MACHINETYPE=$4
INSTANCE=$5
INSTANCENAME="${TYPE}-${FPPREPEND}-${PRODUCT}-${INSTANCE}"
echo "==> Changing machine-type of ${INSTANCENAME}"
gcloud compute instances set-machine-type ${INSTANCENAME} --machine-type=${MACHINETYPE} --zone=${ZONE}
}
# Function to move instance to other zone
function gcpmove {
FPPREPEND=$1
ZONE=$2
PRODUCT=$3
DESTINATIONZONE=$4
INSTANCE=$5
INSTANCENAME="${TYPE}-${FPPREPEND}-${PRODUCT}-${INSTANCE}"
echo "==> Move instance ${INSTANCENAME} from zone ${ZONE} to ${DESTINATIONZONE}"
#gcloud compute instances move INSTANCE_NAME --destination-zone=DESTINATION_ZONE [--async] [--zone=ZONE] [GCLOUD_WIDE_FLAG …]
gcloud compute instances move ${INSTANCENAME} --zone=${ZONE} --destination-zone=${DESTINATIONZONE}
}
# Function to rename instance
function gcprename {
FPPREPEND=$1
ZONE=$2
PRODUCT=$3
NEWPRODUCT=$4
INSTANCE=$5
INSTANCENAME="${TYPE}-${FPPREPEND}-${PRODUCT}-${INSTANCE}"
NEWINSTANCENAME="${TYPE}-${FPPREPEND}-${NEWPRODUCT}-${INSTANCE}"
echo "==> Renaming instance ${INSTANCENAME} to ${NEWINSTANCENAME}"
gcloud compute instances set-name ${INSTANCENAME} --new-name=${NEWINSTANCENAME} --zone=${ZONE}
}
# Function to change instance firewall-rules
function gcpglobalaccess {
FPPREPEND=$1
ZONE=$2
PRODUCT=$3
GLOBALACCESS=$4
INSTANCE=$5
INSTANCENAME="${TYPE}-${FPPREPEND}-${PRODUCT}-${INSTANCE}"
if [ ${GLOBALACCESS} = "enable" ]; then
echo "==> Enabling global access firewall-rule of ${INSTANCENAME}"
gcloud compute instances add-tags ${INSTANCENAME} --tags=${WORKSHOPSOURCEANY} --zone=${ZONE} --no-user-output-enabled
else
echo "==> Disabling global access firewall-rule of ${INSTANCENAME}"
gcloud compute instances remove-tags ${INSTANCENAME} --tags=${WORKSHOPSOURCEANY} --zone=${ZONE} --no-user-output-enabled
fi
}
# Function to add/remove/replace instance labels
function gcplabelmodify {
FPPREPEND=$1
ZONE=$2
PRODUCT=$3
LABELACTION=$4
LABEL=$5
NEWLABEL=$6
INSTANCE=$7
INSTANCENAME="${TYPE}-${FPPREPEND}-${PRODUCT}-${INSTANCE}"
if [ ${LABELACTION} = "add" ]; then
echo "==> Adding label ${LABEL} to instance ${INSTANCENAME}"
gcloud compute instances add-labels ${INSTANCENAME} --labels=${LABEL} --zone=${ZONE} --no-user-output-enabled
elif [ ${LABELACTION} = "remove" ]; then
echo "==> Removing label ${LABEL} from instance ${INSTANCENAME}"
gcloud compute instances remove-labels ${INSTANCENAME} --labels=${LABEL} --zone=${ZONE} --no-user-output-enabled
else
echo "==> Replacibg label ${LABEL} with ${NEWLABEL} on instance ${INSTANCENAME}"
gcloud compute instances remove-labels ${INSTANCENAME} --labels=${LABEL} --zone=${ZONE} --no-user-output-enabled
gcloud compute instances add-labels ${INSTANCENAME} --labels=${NEWLABEL} --zone=${ZONE} --no-user-output-enabled
fi
}
# Function to add/remove/replace instance network tags
function gcpaccessmodify {
FPPREPEND=$1
ZONE=$2
PRODUCT=$3
TAGACTION=$4
TAG=$5
NEWTAG=$6
INSTANCE=$7
INSTANCENAME="${TYPE}-${FPPREPEND}-${PRODUCT}-${INSTANCE}"
if [ ${TAGACTION} = "add" ]; then
echo "==> Adding network tag ${TAG} to instance ${INSTANCENAME}"
gcloud compute instances add-tags ${INSTANCENAME} --tags=${TAG} --zone=${ZONE} --no-user-output-enabled
elif [ ${TAGACTION} = "remove" ]; then
echo "==> Removing network tag ${TAG} from instance ${INSTANCENAME}"
gcloud compute instances remove-tags ${INSTANCENAME} --tags=${TAG} --zone=${ZONE} --no-user-output-enabled
else
echo "==> Replacibg network tag ${TAG} with ${NEWTAG} on instance ${INSTANCENAME}"
gcloud compute instances remove-tags ${INSTANCENAME} --tags=${TAG} --zone=${ZONE} --no-user-output-enabled
gcloud compute instances add-tags ${INSTANCENAME} --tags=${NEWTAG} --zone=${ZONE} --no-user-output-enabled
fi
}
# Function to list instance firewall-rules
function gcpaccesslist {
FPPREPEND=$1
ZONE=$2
PRODUCT=$3
INSTANCESTART=$(($4))
INSTANCEEND=$(($5))
echo "Listing network tags (firewall-rules) of selected instances"
echo ""
echo "Instancename : network tags"
echo "---------------------------------------------------------------------------------"
for ((COUNT = INSTANCESTART; COUNT <= INSTANCEEND; COUNT++)); do
INSTANCENUMBER=$(printf "%03d" $COUNT)
FPINSTANCENAME="${TYPE}-${FPPREPEND}-${PRODUCT}-${INSTANCENUMBER}"
#gcloud compute instances describe ${INSTANCENAME} --zone=${ZONE} | jq -r '.tags .items[]'
TAGS=($(gcloud compute instances describe ${FPINSTANCENAME} --zone=${ZONE} --format=json | jq -r '.tags .items[]'))
echo "${FPINSTANCENAME} : ${TAGS[*]}"
done
}
# Function to list instance labels
function labellist {
FPPREPEND=$1
ZONE=$2
PRODUCT=$3
INSTANCESTART=$(($4))
INSTANCEEND=$(($5))
echo "Listing labels of selected instances"
echo ""
echo "Instancename : labels"
echo "---------------------------------------------------------------------------------"
for ((COUNT = INSTANCESTART; COUNT <= INSTANCEEND; COUNT++)); do
INSTANCENUMBER=$(printf "%03d" $COUNT)
FPINSTANCENAME="${TYPE}-${FPPREPEND}-${PRODUCT}-${INSTANCENUMBER}"
#gcloud compute instances describe ${INSTANCENAME} --zone=${ZONE} | jq -r '.tags .items[]'
LABELS=($(gcloud compute instances describe ${FPINSTANCENAME} --zone=${ZONE} --format=json | jq -c '.labels'| sed 's/{//;s/}//;s/:/=/g;s/"//g'))
echo "${FPINSTANCENAME} : ${LABELS[*]}"
done
}
# Function to display the help
function displayhelp {
echo ' _____ _ _ ____ _____ _ _ _ _ __ ____ ____ ____'
echo '| ___|__ _ __| |_(_) _ \ ___ ___ |_ _|__ ___ | | | _(_) |_ / _| ___ _ __ / ___|/ ___| _ \'
echo '| |_ / _ \| __| __| | |_) / _ \ / __| | |/ _ \ / _ \| | |/ / | __| | |_ / _ \| __| | | _| | | |_) |'
echo '| _| (_) | | | |_| | __/ (_) | (__ | | (_) | (_) | | <| | |_ | _| (_) | | | |_| | |___| __/'
echo '|_| \___/|_| \__|_|_| \___/ \___| |_|\___/ \___/|_|_|\_\_|\__| |_| \___/|_| \____|\____|_|'
printf "${LIGHTRED}(Version: ${GCPCMDVERSION})${NOCOLOR}\n"
echo ""
printf "Selected project : ${CYAN}${GCPPROJECT}${NOCOLOR}\n"
printf "Default deployment region: ${CYAN}${ZONE}${NOCOLOR}\n"
printf "Personal instance identification: ${CYAN}${FPPREPEND}${NOCOLOR}\n"
printf "Default product: ${CYAN}${PRODUCT}${NOCOLOR}\n"
echo ""
echo "Usage: $0 [OPTIONS] [ARGUMENTS] e.g. $0 -z europe-west1-a -i fl <region> <product> <action>"
echo " $0 [OPTIONS] <-b configfile> <region> <product> build"
echo " $0 [OPTIONS] [region] [product] list|listpubip"
echo "OPTIONS:"
echo " -b --build-file File for building instances. Leave blank to generate example"
echo " -d --delete-config Delete default user config settings"
echo " -g --group Group name for shared instances"
echo " -ge --global-access-enable Enable glocal access to instances"
echo " -gd --global-access-disable Disable glocal access to instances"
echo " -gl --global-access-list List global access to instances (network tags)"
echo " -gs --global-access-status Status glocal access to instances"
echo " -i --initials <initials> Override intials on instance name for group management"
echo " -ia --ip-address-add [IP-address] Add current public IP-address to GCP ACL"
echo " -ir --ip-address-remove [IP-address] Remove current public IP-address from GCP ACL"
echo " -il --ip-address-list List current public IP-address on GCP ACL"
echo " -lg --list-global List all your instances globally"
echo " -ll --list-labels List all your instances and labels"
echo " -lr --list-running List all your instances in RUNNING state"
echo " -p --preferences Show personal config preferences"
echo " -pa --project-add Add GCP project to preferences"
echo " -ps --project-select Select project on GCP"
echo " -t --type Override default type name (fpoc)"
echo " -ui --upload-image Upload image to build an instance"
echo " -z --zone Override default region zone"
echo "ARGUMENTS:"
echo " region : america, asia, europe"
echo " product : appsec, fad, fpx, fsa, fsw, fwb, sme, test, xa or <custom-name>"
echo " action : accesslist, accessmodify, build*, clone, delete, globalaccess, labellist, labelmodify"
echo " list, listpubip, machinetype, move, rename, start, stop"
echo ""
echo " *action build needs -b <conf/configfile>. Use ./gcpcmd.sh -b to generate fpoc-example.conf file"
echo ""
[ "${NEWVERSION}" = "true" ] && echo "***** Newer version ${ONLINEVERSION} is available online on GitHub (use 'git pull' to update) *****"
echo ""
}
# Function to select project on GCP from multi-project
function projectselect {
echo ""
echo "--------------------------------------------------------------------------"
echo " Current project : ${GCPCMD_PROJECT[${DEFAULTPROJECT}]}"
echo " Number of projects : ${#GCPCMD_PROJECT[@]}"
echo " All projects : ${GCPCMD_PROJECT[*]}"
echo "--------------------------------------------------------------------------"
echo ""
for ((i=1;i<=${#GCPCMD_PROJECT[@]};i++))
do
echo " ${i}) : ${GCPCMD_PROJECT[${i}]}"
done
echo ""
read -r -p " Select your GCP project : " SELECTEDPROJECT
if [[ ${SELECTEDPROJECT} -lt 1 ]] || [[ ${SELECTEDPROJECT} -gt ${#GCPCMD_PROJECT[@]} ]]
then
echo""; echo " [ERROR] Invalid project number selected"
exit 1
else
echo " Project \"${GCPCMD_PROJECT[${SELECTEDPROJECT}]}\" selected and made permanent"
sed -i '' "s/DEFAULTPROJECT.*/DEFAULTPROJECT=\"${SELECTEDPROJECT}\"/" ${GCPCMDCONF}
echo " Switching GCP-SDK to new selected project"
gcloud config set project ${GCPCMD_PROJECT[${SELECTEDPROJECT}]}
fi
}
# Function to upload a tar.gz file into GCP as image
function gcpuploadimage {
echo " This option allows you to upload a tar.gz file as an image"
read -r -p " What is the image filename (full path)? : " IMAGEFILENAME
IMAGEFILE=$(basename ${IMAGEFILENAME})
if [[ ! ${IMAGEFILE} =~ "tar.gz" ]]; then
echo " Filename is not ending in tar.gz"
exit
fi
read -r -p " Provide image filename for GCP (to build an instance) : " IMAGENAME
echo ""
echo " Copying ${IMAGEFILE} to you bucket gs://images-${OWNER}/"
if ! gsutil ls gs://images-${OWNER} > /dev/null 2>&1
then
gcloud storage buckets create gs://images-${OWNER} --project=${GCPPROJECT} --location=$(echo ${ZONE}|awk -F "-" '{ print $1"-"$2}')
fi
if ! gsutil cp ${IMAGEFILENAME} gs://images-${OWNER}/${IMAGEFILE}
then
echo ""
echo " Building your image file ${IMAGENAME}"
gcloud compute images create ${IMAGENAME} \
--project=${GCPPROJECT} \
--source-uri gs://images-${OWNER}/${IMAGEFILE} \
--licenses "https://www.googleapis.com/compute/v1/projects/vm-options/global/licenses/enable-vmx" \
--family fortipoc
else
echo""; echo " There was an error copying the file"
fi
}
# Funtion to gatgher perferences
function gatherpreferences {
EXPAND="${1}"
if [ ! -f ${GCPCMDCONF} ]; then
echo "-------------------------------------------------------"
echo " Welcome to FortiPoc Toolkit for Google Cloud Platform"
echo "-------------------------------------------------------"
echo ""
echo "This is your first time use of gcpcmd.sh and no preferences are set. Let's set them!"
echo "NOTE: Make sure you have enabled the 'Compute Engine API' via the Google Cloud Console first!"
sleep 3
echo 'DEFAULTPROJECT="1"' > ${GCPCMDCONF}
read -r -p "Would you like to have "gcpcmd" as a global command? y/n : " choice
if [ -z "${choice}" ] || [ "${choice}" == "y" ]; then
if [[ ${PATH} =~ "/usr/local/bin" ]]; then
[ -d /usr/local/bin ] && sudo ln -s $(pwd)/gcpcmd.sh /usr/local/bin/gcpcmd
fi
fi
echo "" >> ${GCPCMDCONF}
EXPAND="new"
fi
if [ "${EXPAND}" = "new" ]; then
let NEWPROJECTNUM=${#GCPCMD_PROJECT[@]}+1
read -r -p "Your initials e.g. fl : " CONFINITIALS
read -r -p "Your name to lable instanced e.g. flastname : " CONFGCPLABEL
read -r -p "Groupname for shared instances (optional) : " CONFGCPGROUP
until [ ! -z ${CONFREGION} ]; do
read -r -p "Your region 1) Asia, 2) Europe, 3) America : " CONFREGIONANSWER
case ${CONFREGIONANSWER} in
1) CONFREGION="${ASIA}" ;;
2) CONFREGION="${EUROPE}" ;;
3) CONFREGION="${AMERICA}" ;;
esac
done
# Request ProjectId from GCP and use that if no projectId is entered
echo ""
echo "You have access to the following GCP Projects"
GCPPROJECTS=$(gcloud projects list --format json | jq '.[] .projectId')
GCPPROJECTID=(${GCPPROJECTS})
for ((i=0;i<${#GCPPROJECTID[@]};i++))
do
echo " ${i}) : ${GCPPROJECTID[${i}]}"
done
echo ""
echo " q to quit"
echo ""
read -r -p " Select your GCP project : " SELECTEDPROJECT
if [[ ${SELECTEDPROJECT} -lt 0 ]] || [[ ${SELECTEDPROJECT} -ge ${#GCPPROJECTID[@]} ]] && [ ! ${SELECTEDPROJECT} == "q" ]
then
echo""; echo " [ERROR] Invalid project selected"
exit 1
else
if [ "${SELECTEDPROJECT}" = "q" ]; then exit
else
CONFPROJECTNAME=$(echo ${GCPPROJECTID[${SELECTEDPROJECT}]} | tr -d \")
fi
fi
# Request default Compute Service Account and use that if no Service Account is entered
GCPSRVACCOUNT=$(gcloud iam service-accounts list --filter=Compute --format=json | jq -r '.[] .email')
until [[ ${ONEACCOUNT} -eq 1 ]]; do
read -r -p "GCP service account (provide only one) [${GCPSRVACCOUNT}] : " CONFSERVICEACCOUNT
[ -z "${CONFSERVICEACCOUNT}" ] && CONFSERVICEACCOUNT="${GCPSRVACCOUNT}"
[[ ! ${CONFSERVICEACCOUNT} =~ \ ]] && ONEACCOUNT=1
done
until [[ ${VALIDIP} -eq 1 ]]; do
read -r -p "IP-address of license-server (optional) : " CONFLICENSESERVER
if [ -z ${CONFLICENSESERVER} ]; then
VALIDIP=1
else
validateIP ${CONFLICENSESERVER}
VALIDIP=!$?
fi
done
# Obtain pesonal SSH-key for FortiPoC access
SSHKEYPERSONAL="_no_key_found"
if [ -f ~/.ssh/id_rsa.pub ]; then
SSHKEYPERSONAL=$(head -1 ~/.ssh/id_rsa.pub)
fi
read -r -p "Your SSH public key for FortiPoC access (optional) [${SSHKEYPERSONAL}] : " CONFSSHKEYPERSONAL
CONFSSHKEYPERSONAL="${SSHKEYPERSONAL}"
cat <<EOF >>${GCPCMDCONF}
GCPCMD_PROJECT[${NEWPROJECTNUM}]="${CONFPROJECTNAME}"
GCPCMD_SERVICEACCOUNT[${NEWPROJECTNUM}]="${CONFSERVICEACCOUNT}"
GCPCMD_LICENSESERVER[${NEWPROJECTNUM}]="${CONFLICENSESERVER}"
GCPCMD_FPPREPEND[${NEWPROJECTNUM}]="${CONFINITIALS}"
GCPCMD_ZONE[${NEWPROJECTNUM}]="${CONFREGION}"
GCPCMD_LABELS[${NEWPROJECTNUM}]="expire=MM-DD-YYYY,group=${CONFGCPGROUP}, purpose=ReplaceMe,owner=${CONFGCPLABEL}"
GCPCMD_FPGROUP[${NEWPROJECTNUM}]="${CONFGCPGROUP}"
GCPCMD_PRODUCT[${NEWPROJECTNUM}]="test"
GCPCMD_SSHKEYPERSONAL[${NEWPROJECTNUM}]="${CONFSSHKEYPERSONAL}"
GCPCMD_VPC[${NEWPROJECTNUM}]=""
GCPCMD_FIREWALLRULES[${NEWPROJECTNUM}]=""
EOF
echo ""
fi
}
###############################
# start of program
###############################
# Check if required software is available and exit if missing
type gcloud >/dev/null 2>&1 || (
echo ""
echo "WARNING: gcloud SDK not installed"
exit 1
)
[ $? -eq 1 ] && exit
type parallel >/dev/null 2>&1 || (
echo ""
echo "WARNING: parallel software not installed"
exit 1
)
[ $? -eq 1 ] && exit
type jq >/dev/null 2>&1 || (
echo""
echo "WARNING: jq software not installed"
exit 1
)
[ $? -eq 1 ] && exit
type dig >/dev/null 2>&1 || (
echo ""
echo "WARNING: dig software not installed (bind-tools)"
exit 1
)
[ $? -eq 1 ] && exit
echo ""
# Check on first run and user specific defaults
# Chech if .fpoc logs and conf directories exists, create if it doesn't exist to store peronal perferences
[ ! -d ~/.fpoc/ ] && mkdir ~/.fpoc
[ ! -d logs ] && mkdir logs
[ ! -d conf ] && mkdir conf
eval GCPCMDCONF="~/.fpoc/gcpcmd.conf"
gatherpreferences
source ${GCPCMDCONF}
# Populate the internal (old) variables from the multi-project gcpcmd.conf preferences file
GCPPROJECT="${GCPCMD_PROJECT[${DEFAULTPROJECT}]}"
GCPSERVICEACCOUNT="${GCPCMD_SERVICEACCOUNT[${DEFAULTPROJECT}]}"
LICENSESERVER="${GCPCMD_LICENSESERVER[${DEFAULTPROJECT}]}"
FPPREPEND="${GCPCMD_FPPREPEND[${DEFAULTPROJECT}]}"
ZONE="${GCPCMD_ZONE[${DEFAULTPROJECT}]}"
LABELS="${GCPCMD_LABELS[${DEFAULTPROJECT}]}"
FPGROUP="${GCPCMD_FPGROUP[${DEFAULTPROJECT}]}"
PRODUCT="${GCPCMD_PRODUCT[${DEFAULTPROJECT}]}"
SSHKEYPERSONAL="${GCPCMD_SSHKEYPERSONAL[${DEFAULTPROJECT}]}"
VPC="${GCPCMD_VPC[${DEFAULTPROJECT}]}"
FIREWALLRULES="${GCPCMD_FIREWALLRULES[${DEFAULTPROJECT}]}"
#OWNER=$(echo ${LABELS} | grep owner | cut -d "=" -f 3)
OWNER=$(echo ${LABELS} | awk -F "owner=" '{ print $2}')
# Check online if there is a newer Version
ONLINEVERSION=$(curl --fail --silent --retry-max-time 1 --user-agent ${GCPCMDVERSION}-${GCPPROJECT}-${FPPREPEND} http://www.4xion.com/gcpcmdversion.txt)
[ ! -z "${ONLINEVERSION}" ] && [ ${ONLINEVERSION} -gt ${GCPCMDVERSION} ] && NEWVERSION="true"
# Verify if DEFAULTPROJECT is populated in prefences file. If not than gcpcmd.sh was updated to multi-project support..
if [ -z ${DEFAULTPROJECT} ] && [ ! "$1" == "-d" ]; then
echo "Run ./gcpcmd.sh -d because your configured preferences are from older gcpcmd.sh version not supporting multi-projects."
[ -f ${GCPCMDCONF} ] && displaypreferences ${GCPCMDCONF}
exit
fi
# Check if GCP default VPC and Firewall rules exist
checkdefaultnetwork
checkfirewallrules
# Handling options given
while [[ "$1" =~ ^-.* ]]; do
case $1 in
-b | --build-file)
# Check if a build config file is provided
CONFIGFILE=$2
RUN_CONFIGFILE="true"
shift
;;
-d | --delete-defaults)
echo "Delete default user settings"
rm ${GCPCMDCONF}
exit
;;