Repository navigation
Expand file tree
/
Copy pathcloudflare
More file actions
executable file
·1383 lines (1270 loc) · 38.7 KB
/
Copy pathcloudflare
File metadata and controls
executable file
·1383 lines (1270 loc) · 38.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
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
# =================================================================================================
# cloudflare-cli v1.4.4
# =================================================================================================
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
API_METHOD=""
API_PROFILE=""
# Default account id for create-style commands (set via --account-id)
CLI_ACCOUNT_ID=""
# Multi-zone processing globals
declare -a CLI_ZONES=()
declare -a ZONES_TO_PROCESS=()
ZONES_FILE=""
MULTI_ZONE_CONTINUE_ON_ERROR=0
# shellcheck source=./cf-inc.sh
source "$SCRIPT_DIR/cf-inc.sh"
# shellcheck source=./cf-inc-api.sh
source "$SCRIPT_DIR/cf-inc-api.sh"
# shellcheck source=cf-inc-cf.sh
source "$SCRIPT_DIR/cf-inc-cf.sh"
# ==============================================================================================
# -- Start Script
# ==============================================================================================
# -- Check options
_debug "Checking for options"
declare -a POSITIONAL_ARGS=()
while [ -n "$1" ]
do
case "$1" in
-E)
shift
[ -z "$1" ] && _die "Usage: cloudflare -E <email>"
CF_ACCOUNT=$1
shift
continue
;;
-T)
shift
[ -z "$1" ] && _die "Usage: cloudflare -T <api_token>"
CF_TOKEN=$1
shift
continue
;;
--test)
shift
[ -z "$1" ] && _die "Usage: cloudflare --test <value>"
TEST=$1
shift
continue
;;
-D|--debug)
DEBUG=1
UI_VERBOSE=1
shift
continue
;;
-DF|--debug-file)
DEBUG_FILE=1
UI_VERBOSE=1
shift
continue
;;
-DC|--debug-curl)
DEBUG=1
UI_VERBOSE=1
DEBUG_CURL_OUTPUT=1
shift
continue
;;
-d|--detail|--detailed|--details)
details=1
shift
continue
;;
-z|--zone)
shift
if [ -z "$1" ]; then
_die "Usage: cloudflare -z <zone>"
fi
CLI_ZONES+=("$1")
_debug "Added zone from CLI: $1"
shift
continue
;;
-f|--zones-file)
shift
if [ -z "$1" ]; then
_die "Usage: cloudflare -f <zones-file>"
fi
ZONES_FILE="$1"
_debug "Zones file specified: $ZONES_FILE"
shift
continue
;;
--continue-on-error)
MULTI_ZONE_CONTINUE_ON_ERROR=1
shift
continue
;;
-q|--quiet)
# Human output is suppressed; errors and warnings still print.
QUIET=1
UI_QUIET=1
shift
continue
;;
-p|--profile)
shift
if [ -z "$1" ]; then
_die "Usage: cloudflare --profile <profile_name>"
fi
API_PROFILE="$1"
_debug "Using profile: $API_PROFILE"
shift
continue
;;
-A|--account-id)
shift
if [ -z "$1" ]; then
_die "Usage: cloudflare --account-id <account_id>"
fi
CLI_ACCOUNT_ID="$1"
_debug "Default account id specified: $CLI_ACCOUNT_ID"
shift
continue
;;
-y|--yes|--force)
FORCE_YES=1
UI_YES=1
shift
continue
;;
-h|--help)
help full
_die
;;
--)
shift
while [ -n "$1" ]; do
POSITIONAL_ARGS+=("$1")
shift
done
break
;;
*)
POSITIONAL_ARGS+=("$1")
shift
;;
esac
done
set -- "${POSITIONAL_ARGS[@]}"
# -- One banner per run; -q (UI_QUIET) suppresses it. stderr only.
if [[ ${UI_QUIET:-0} != 1 ]]; then
ui_header "cloudflare-cli" "v${VERSION}"
fi
# -- Merge zones from CLI and file into ZONES_TO_PROCESS
if [[ -n "$ZONES_FILE" ]]; then
while IFS= read -r zone; do
ZONES_TO_PROCESS+=("$zone")
done < <(_parse_zones_file "$ZONES_FILE")
fi
for zone in "${CLI_ZONES[@]}"; do
ZONES_TO_PROCESS+=("$zone")
done
[[ ${#ZONES_TO_PROCESS[@]} -gt 0 ]] && _debug "Total zones to process: ${#ZONES_TO_PROCESS[@]}"
# -- If no command left after option parsing, just show usage and exit
if [ -z "$1" ]; then
help usage
_die "Missing arguments" 1
fi
# -- Debug full command (post-option parsing)
CMD_ALL="${*}"
_loading "Running: ${CMD_ALL}"
if [[ -n "$API_PROFILE" ]]; then
_loading2 "Using profile: $API_PROFILE"
fi
# =================================================================================================
# -- Process Commands
# =================================================================================================
CMD1=$1
shift
case "$CMD1" in
# =================================================================================================
# -- show command @SHOW
# =================================================================================================
show|list)
CMD2=$1
shift
case "$CMD2" in
# -- zone
zone)
_pre_flight_check CF_
[ -z "$1" ] && { help show; _die "Missing zone for $CMD2"; }
DOMAIN="$1"
_cf_zone_exists "$DOMAIN"
ZONE_ID=$(_cf_zone_id "$DOMAIN")
if [ $? ]; then
_loading2 "Getting zone details for $DOMAIN with ID $ZONE_ID"
LIST_ZONE_OUTPUT="Name\tStatus\tType\tID\tName Servers\tOriginal Name Servers\n"
LIST_ZONE_OUTPUT+="----\t------\t----\t--\t------------\t-------------------\n"
LIST_ZONE_OUTPUT+=$(call_cf_v4 GET /zones/"$ZONE_ID" -- %"%s$TA%s$TA%s$TA%s$TA%s$TA%s$NL" ,name,status,type,id,name_servers,original_name_servers)
echo -e "$LIST_ZONE_OUTPUT" | column -t -s $'\t'
else
_die "No zone found for $DOMAIN"
fi
;;
# -- zone
zones)
_pre_flight_check CF_
# -- Max per page=1000 and max results = 2000
# TODO figure out how to get all zones in one call, or warn there is more than 1000 and add an option for second set of results etc.
#call_cf_v4 GET /zones -- .result %"%s$TA%s$TA#%s$TA%s$TA%s$NL" ,name,status,id,original_name_servers,name_servers
_cf_zone_list ""
;;
# -- settings
setting|settings)
_pre_flight_check CF_
[ -z "$1" ] && { help show; _die "Missing sub-command for $CMD2"; }
CLI_ZONE="$1"
_cf_zone_exists "$CLI_ZONE"
ZONE_ID="$(_cf_zone_id "$CLI_ZONE")"
if [ $? ]; then
_loading2 "Getting settings for $CLI_ZONE"
else
_die "No zone found for $CLI_ZONE"
fi
if [ "$details" = 1 ]; then
# shellcheck disable=SC2016 # field template, expanded by the decoder
fieldspec=,id,value,'?editable?"Editable"?""','?modified_on?<",, mod: $modified_on"?""'
else
fieldspec=,id,value,\"\",\"\"
fi
call_cf_v4 GET /zones/"$ZONE_ID"/settings -- .result %"%-30s %s$TA%s%s$NL" "$fieldspec"
;;
# -- records (all records for a zone)
records)
_pre_flight_check CF_
_loading "Running: cloudflare $CMD1 records $*"
[ -z "$1" ] && ui_err "Usage: cloudflare $CMD1 records <zone>"
CLI_ZONE="$1"
_cf_zone_exists "$CLI_ZONE"
ZONE_ID="$(_cf_zone_id "$CLI_ZONE")"
# -- Get zone data
_debug "- Getting zone data for $ZONE_ID"
#call_cf_v4 GET /zones/$ZONE_ID/dns_records -- .result %"%-20s %11s %-8s %s %s$TA; %s #%s$NL" \
# ',@zone_name@name,?<$ttl==1?"auto"?ttl,type,||priority||data.priority||"",content,!!proxiable proxied locked,id'
_cf_zone_records "$ZONE_ID"
;;
# -- record (individual record by name)
record)
_pre_flight_check CF_
[ -z "$1" ] && ui_err "Usage: cloudflare $CMD1 record <record_name> (e.g., test.example.com)"
_loading "Getting record details for $1"
_cf_get_record_by_name "$1"
;;
# -- access-rules
access-rules|listing|listings|blocking|blockings)
_pre_flight_check CF_
# shellcheck disable=SC2016 # field template, expanded by the decoder
call_cf_v4 GET /user/firewall/access_rules/rules -- .result %"%s$TA%s$TA%s$TA# %s$NL" ',<$configuration["value"],mode,modified_on,notes'
;;
email-routing)
_pre_flight_check CF_
[ -z "$1" ] && { help show; _die "Missing zone for $CMD2"; }
CLI_ZONE="$1"
_cf_zone_exists "$CLI_ZONE"
ZONE_ID="$(_cf_zone_id "$CLI_ZONE")"
#call_cf_v4 GET /zones/$ZONE_ID/email/routing -- %"%-30s %s$TA%s%s$NL" ',name,enabled,created,modified,status'
# shellcheck disable=SC2016 # field template, expanded by the decoder
call_cf_v4 GET /zones/"$ZONE_ID"/email/routing -- .result '&<"name: $name"' '&<"status: $status"' '&<"created: $created"' '&<"modified: $modified"' '&<"enabled: $enabled"'
;;
# -- no command catchall
*)
help show
if [[ -n $CMD2 ]]; then
_die "Unknown command $CMD2" 1
else
_die "No command provided for $1" 1
fi
;;
esac
;;
# =================================================================================================
# -- add command @ADD
# =================================================================================================
add)
_debug "sub-command: add ${*}"
CMD2=$1
shift
case "$CMD2" in
record)
# -- Parse add-record options before anything that needs credentials
opt_ttl=''
opt_proxy=''
opt_ttl_set=0
opt_proxy_set=0
declare -a record_args=()
while [ $# -gt 0 ]; do
case "$1" in
--ttl|--ttl=*)
if [[ "$1" == --ttl=* ]]; then
opt_ttl="${1#*=}"
shift
else
[ $# -lt 2 ] && { help add record; _die "--ttl requires a value: auto or a number of seconds"; }
opt_ttl="$2"
shift 2
fi
opt_ttl_set=1
;;
--proxy|--proxy=*)
if [[ "$1" == --proxy=* ]]; then
opt_proxy="${1#*=}"
shift
else
[ $# -lt 2 ] && { help add record; _die "--proxy requires a value: yes or no"; }
opt_proxy="$2"
shift 2
fi
opt_proxy_set=1
;;
--)
shift
record_args+=("$@")
break
;;
-*)
help add record
_die "Unknown option '$1' for add record"
;;
*)
record_args+=("$1")
shift
;;
esac
done
set -- "${record_args[@]}"
[ $# -lt 4 ] && { help add record;_die "Missing arguments - $CMD_ALL"; }
ZONE=$1
shift
type=${1^^}
shift
name=$1
shift
content=$1
shift
type_upper="${type^^}"
# -- Positional arguments after <content> are type-specific
case "$type_upper" in
MX)
prio=$1; shift || true
;;
SRV)
prio=$1; shift || true
service=$1; shift || true
protocol=$1; shift || true
weight=$1; shift || true
port=$1; shift || true
;;
esac
if [ $# -gt 0 ]; then
help add record
_die "Unexpected argument '$1'. Use --ttl and --proxy for TTL and proxying."
fi
# -- TTL: flag, terminal prompt, or auto when it cannot prompt
if [[ $opt_ttl_set -eq 1 ]]; then
ttl_input="$opt_ttl"
elif _cf_prompt_enabled; then
ttl_input=$(_cf_prompt_record_ttl auto)
else
ttl_input='auto'
fi
ttl=$(_cf_normalize_record_ttl "$ttl_input") || {
help add record
_die "Invalid ttl '$ttl_input'. ttl must be a number or 'auto'."
}
# -- Proxying only exists for A, AAAA and CNAME records
proxied=''
if [[ "$type_upper" == "A" || "$type_upper" == "AAAA" || "$type_upper" == "CNAME" ]]; then
if [[ $opt_proxy_set -eq 1 ]]; then
proxy_input="$opt_proxy"
elif _cf_prompt_enabled; then
proxy_input=$(_cf_prompt_record_proxy yes)
else
proxy_input='yes'
fi
proxied=$(_cf_normalize_proxy "$proxy_input") || {
help add record
_die "Invalid proxy '$proxy_input' for $type_upper record. Use yes or no."
}
elif [[ $opt_proxy_set -eq 1 ]]; then
ui_warn "--proxy is ignored for $type_upper records; Cloudflare only proxies A, AAAA and CNAME."
fi
if [[ "$type_upper" == "MX" || "$type_upper" == "SRV" ]]; then
[ -n "$prio" ] || prio=10
if ! _cf_validate_record_priority "$prio"; then
help add record
_die "Invalid priority '$prio' for $type_upper record. priority must be a number."
fi
fi
if [[ $content =~ ^127.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] && [[ "$type" == "A" ]]; then ui_err "Can't proxy 127.0.0.0/8 using an A record"; fi
_pre_flight_check CF_
_debug "Running with API_METHOD: $API_METHOD"
_loading2 "Getting zone_id for $ZONE"
_cf_zone_exists "$ZONE"
ZONE_ID="$(_cf_zone_id "$ZONE")"
_loading2 " - Found zone $ZONE with id $ZONE_ID"
# -- Check for existing record and prompt to continue if found
if _cf_check_record_exists "$ZONE_ID" "$name" "$type"; then
if [[ "${FORCE_YES:-0}" != "1" ]]; then
if ! ui_confirm "A matching record already exists. Continue creating a new record?" n; then
_die "Aborted by user."
fi
else
ui_warn "Existing record found but --force/-y was specified, continuing."
fi
fi
RECORD_CREATE_OUTPUT="ID\tZone Name\tName\tType\tContent\tProxiable\tProxied\tTTL"
RECORD_CREATE_OUTPUT+="\n--\t---------\t----\t----\t-------\t---------\t-------\t---\n"
case "$type" in
MX)
_loading2 " -- Creating MX record: $name $content $ttl $prio"
RECORD_CREATE_OUTPUT+=$(call_cf_v4 POST /zones/"$ZONE_ID"/dns_records "{\"type\":\"$type\",\"name\":\"$name\",\"content\":\"$content\",\"ttl\":$ttl,\"priority\":$prio}")
echo -e "$RECORD_CREATE_OUTPUT" | column -t -s $'\t'
;;
LOC)
locdata=''
# shellcheck disable=SC2086 # LOC content is a space-separated field list
set -- $content
for key in lat_degrees lat_minutes lat_seconds lat_direction \
long_degrees long_minutes long_seconds long_direction \
altitude size precision_horz precision_vert
do
value=$1
value=${value%m}
locdata="$locdata${locdata:+,}\"$key\":\"$value\""
shift
done
_loading2 " -- Creating LOC record: $name $content $ttl"
RECORD_CREATE_OUTPUT+=$(call_cf_v4 POST /zones/"$ZONE_ID"/dns_records "{\"type\":\"$type\",\"ttl\":$ttl,\"name\":\"$name\",\"data\":{$locdata}}")
echo -e "$RECORD_CREATE_OUTPUT" | column -t -s $'\t'
;;
SRV)
[ "${service:0:1}" = _ ] || service="_$service"
[ "${protocol:0:1}" = _ ] || protocol="_$protocol"
[ -n "$weight" ] || weight=1
target=$content
call_cf_v4 POST /zones/"$ZONE_ID"/dns_records "{
\"type\":\"$type\",
\"ttl\":$ttl,
\"data\":{
\"service\":\"$service\",
\"proto\":\"$protocol\",
\"name\":\"$name\",
\"priority\":$prio,
\"weight\":$weight,
\"port\":$port,
\"target\":\"$target\"
}
}"
;;
TXT)
_loading2 " -- Creating TXT record: $name $content $ttl"
RECORD_CREATE_OUTPUT+=$(call_cf_v4 POST /zones/"$ZONE_ID"/dns_records "{\"type\":\"$type\",\"name\":\"$name\",\"content\":\"$content\",\"ttl\":$ttl}" -- %"%s$TA%s$TA%s$TA%s$TA%s$TA%s$TA%s$TA%s$NL" ,id,zone_name,name,type,content,proxiable,proxied,ttl)
echo -e "$RECORD_CREATE_OUTPUT" | column -t -s $'\t'
;;
A|AAAA)
_loading2 " -- Creating $type record: $name $content $ttl $proxied"
if cf_api POST /client/v4/zones/"$ZONE_ID"/dns_records "{\"type\":\"$type\",\"name\":\"$name\",\"content\":\"$content\",\"ttl\":$ttl,\"proxied\":$proxied}"; then
ui_ok "Record created"
echo "$API_OUTPUT" | jq -r '.result | "\(.id)\t\(.zone_name)\t\(.name)\t\(.type)\t\(.content)\t\(.proxiable)\t\(.proxied)\t\(.ttl)"' | column -t -s $'\t'
else
ui_err "Error creating $type record"
echo "$API_OUTPUT"
fi
;;
CNAME)
_loading2 " -- Creating CNAME record: $name $content $ttl $proxied"
RECORD_CREATE_OUTPUT+=$(call_cf_v4 POST /zones/"$ZONE_ID"/dns_records "{\"type\":\"$type\",\"name\":\"$name\",\"content\":\"$content\",\"ttl\":$ttl,\"proxied\":$proxied}" -- %"%s$TA%s$TA%s$TA%s$TA%s$TA%s$TA%s$TA%s$NL" ,id,zone_name,name,type,content,proxiable,proxied,ttl)
echo -e "$RECORD_CREATE_OUTPUT" | column -t -s $'\t'
;;
*)
_loading2 " -- Creating record: $name $content $ttl"
# ,id,zone_name,name,type,content,proxiable,proxied,ttl
RECORD_CREATE_OUTPUT+=$(call_cf_v4 POST /zones/"$ZONE_ID"/dns_records "{\"type\":\"$type\",\"name\":\"$name\",\"content\":\"$content\",\"ttl\":$ttl}" -- %"%s$TA%s$TA%s$TA%s$TA%s$TA%s$TA%s$TA%s$NL" ,id,zone_name,name,type,content,proxiable,proxied,ttl)
echo -e "$RECORD_CREATE_OUTPUT" | column -t -s $'\t'
;;
esac
;;
whitelist|blacklist|block|challenge)
_pre_flight_check CF_
trg=$1
trg_type=''
shift
notes=$*
case "$CMD2" in
whitelist) mode=whitelist;;
blacklist|block) mode=block;;
challenge) mode=challenge;;
esac
if expr "$trg" : '[0-9\.]\+$' >/dev/null
then
trg_type=ip
elif expr "$trg" : '[0-9\.]\+/[0-9]\+$' >/dev/null
then
trg_type=ip_range
elif expr "$trg" : '[A-Z]\+$' >/dev/null
then
trg_type=country
fi
[[ -z $trg || -z $trg_type ]] && _die "Usage: cloudflare add [<whitelist | blacklist | challenge>] [<IP | IP/mask | country_code>] [note]"
call_cf_v4 POST /user/firewall/access_rules/rules mode="$mode" "configuration[target]=$trg_type" "configuration[value]=$trg" notes="$notes"
;;
zone)
_pre_flight_check CF_
# Usage: cloudflare add zone <zone> [account-id]
DOMAIN="$1"
ACCOUNT_ID="$2"
# Prefer explicit --account-id over positional
if [[ -n "$CLI_ACCOUNT_ID" ]]; then
ACCOUNT_ID="$CLI_ACCOUNT_ID"
fi
# Bulk mode: if zones were specified via -z/-f and no domain is given
# Also support: cloudflare -f zones.txt add zone <account-id>
if [[ ${#ZONES_TO_PROCESS[@]} -gt 0 && ( -z "$DOMAIN" || ( ${#DOMAIN} -eq 32 && "$DOMAIN" != *.* ) ) ]]; then
# If DOMAIN looks like an account id and no explicit account id given, treat it as account id
if [[ -z "$ACCOUNT_ID" && -n "$DOMAIN" && ${#DOMAIN} -eq 32 && "$DOMAIN" != *.* ]]; then
ACCOUNT_ID="$DOMAIN"
DOMAIN=""
fi
_loading2 "Creating ${#ZONES_TO_PROCESS[@]} zone(s)${ACCOUNT_ID:+ under account $ACCOUNT_ID}"
echo -e "Zone\tID\tName Servers"
echo -e "----\t--\t------------"
# This entry point is a flat case dispatcher, not a function, so
# `return` here only prints "can only `return' from a function or
# sourced script" and lets execution fall through into the
# single-zone path below (empty DOMAIN -> usage error, exit 1).
# Exit with the real multi-zone status instead.
_process_multi_zone _cf_zone_create_v4 "$ACCOUNT_ID"
MULTI_ZONE_RC=$?
exit "$MULTI_ZONE_RC"
fi
if [ -z "$DOMAIN" ]; then
_die "Usage: cloudflare add zone <zone> [account-id]"
fi
# Check if zone already exists
_loading2 "Checking if zone $DOMAIN already exists"
ZONE_ID=$(_cf_zone_id "$DOMAIN")
if [[ -n "$ZONE_ID" ]]; then
ui_err "Zone $DOMAIN already exists with ID $ZONE_ID"
exit 1
fi
# -- Check if account id is provided
if [ -n "$ACCOUNT_ID" ]; then
_loading2 "Account ID provided: $ACCOUNT_ID"
_debug "Account ID provided: $ACCOUNT_ID"
JSON="{\"account\":{\"id\":\"$ACCOUNT_ID\"},\"name\":\"$DOMAIN\",\"jump_start\":true}"
else
_loading2 "No Account ID provided, creating in default account"
_debug "No Account ID provided"
JSON="{\"name\":\"$DOMAIN\",\"jump_start\":true}"
fi
# -- Create a new zone
CREATE_ZONE_OUTPUT_CMD=$(call_cf_v4 POST /zones "$JSON" -- %"%s$TA%s$TA%s$TA%s$TA%s$NL" ,name,status,type,id,name_servers)
CREATE_ZONE_OUTPUT="Name\tStatus\tType\tID\tName Servers\n"
CREATE_ZONE_OUTPUT+="----\t------\t----\t--\t------------\n"
CREATE_ZONE_OUTPUT+=$CREATE_ZONE_OUTPUT_CMD
ui_ok "Zone created"
echo -e "$CREATE_ZONE_OUTPUT" | column -t -s $'\t'
echo ""
_notice "Please make sure to update your name servers to the following:"
# Get name servers (field 5 is name_servers; keep it tab-safe)
echo "$CREATE_ZONE_OUTPUT_CMD" | awk -F'\t' '{print $5}' | tr ', ' '\n' | sed '/^$/d' | sed 's/^/ - /'
;;
*)
help add;
echo ""
_die "Missing sub-command"
esac
;;
# =================================================================================================
# -- bulk command
# =================================================================================================
bulk)
CMD2=$1
shift || true
case "$CMD2" in
zone|zones)
CMD3=$1
shift || true
case "$CMD3" in
add)
_pre_flight_check CF_
ACCOUNT_ID="${CLI_ACCOUNT_ID:-}"
if [[ -z "$ACCOUNT_ID" ]]; then
ACCOUNT_ID="${1:-}"
fi
if [[ ${#ZONES_TO_PROCESS[@]} -eq 0 ]]; then
_die "Usage: cloudflare (-f <zones-file> | -z <zone> [-z <zone> ...]) [--account-id <account_id>] bulk zone add [account_id]"
fi
if [[ -z "$ACCOUNT_ID" ]]; then
_die "Missing account id. Use --account-id <account_id> or provide it as the final argument."
fi
_loading2 "Bulk creating ${#ZONES_TO_PROCESS[@]} zone(s) under account $ACCOUNT_ID"
echo -e "Zone\tID\tName Servers"
echo -e "----\t--\t------------"
_process_multi_zone _cf_zone_create_v4 "$ACCOUNT_ID"
# Exit explicitly so the status never depends on this
# branch being the last statement in the dispatcher.
MULTI_ZONE_RC=$?
exit "$MULTI_ZONE_RC"
;;
*)
help bulk zone add
_die "Usage: cloudflare bulk zone add" 1
;;
esac
;;
*)
help bulk zone add
_die "Usage: cloudflare bulk zone add" 1
;;
esac
;;
# =================================================================================================
# -- delete command
# =================================================================================================
delete)
CMD2=$1
shift
case "$CMD2" in
record)
_pre_flight_check CF_
prm1=$1
prm2=$2
shift
shift
if [ ${#prm2} = 32 ] && is_hex "$prm2"
then
if [ -n "$1" ]
then
_die "Unknown parameters: ${*}"
fi
if is_hex "$prm1"
then
zone_id=$prm1
else
ZONE_ID=$(_cf_zone_id "$prm1")
fi
record_id=$prm2
else
record_type=''
first_match=0
[ -z "$prm1" ] && _die "Usage: cloudflare delete record [<record-name> [<record-type> | first] | [<zone-name>|<zone-id>] <record-id>]"
if [ "$prm2" = first ]
then
first_match=1
else
record_type=${prm2^^}
fi
findout_record "$prm1" "$record_type" "$first_match"
case $? in
0) true;;
2) _die "No suitable DNS zone found for \`$prm1'";;
3) _die "DNS record \`$prm1' not found";;
4) _die "Ambiguous record spec: \`$prm1'";;
*) _die "Internal error";;
esac
fi
call_cf_v4 DELETE /zones/"$ZONE_ID"/dns_records/"$record_id"
;;
listing)
_pre_flight_check CF_
[ -z "$1" ] && _die "Usage: cloudflare delete listing [<IP | IP range | country code | ID | note fragment>] [first]"
call_cf_v4 GET /user/firewall/access_rules/rules -- .result ,id,configuration.value,notes |\
while read -r ruleid trg notes; do
if [[ $ruleid == "$1" || $trg == "$1" ]] || grep -qF "$1" <<<"$notes"
then
call_cf_v4 DELETE /user/firewall/access_rules/rules/"$ruleid"
if [ "$2" = first ]
then
break
fi
fi
done
;;
zone)
_pre_flight_check CF_
if [ $# != 1 ]
then
_die "Usage: cloudflare delete zone <name>"
fi
DOMAIN="$1"
_cf_zone_exists "$DOMAIN"
ZONE_ID=$(_cf_zone_id "$DOMAIN")
if [[ -z "$ZONE_ID" ]]; then
_die "No zone found for $DOMAIN"
fi
_loading2 "Deleting zone $DOMAIN with ID $ZONE_ID"
# Confirm deletion
echo ""
echo "===================================================================="
ui_err "This will delete zone $DOMAIN with ID $ZONE_ID"
DELETE_ZONE_ACCOUNT_DETAILS="Name\tStatus\tType\tID\tName Servers\tOriginal Name Servers\n"
DELETE_ZONE_ACCOUNT_DETAILS+="----\t------\t----\t--\t------------\t-------------------\n"
DELETE_ZONE_ACCOUNT_DETAILS+=$(call_cf_v4 GET /zones/"$ZONE_ID" -- %"%s$TA%s$TA%s$TA%s$TA%s$TA%s$NL" ,name,status,type,id,name_servers,original_name_servers)
echo -e "$DELETE_ZONE_ACCOUNT_DETAILS" | column -t -s $'\t'
echo "===================================================================="
echo ""
_loading2 "Are you sure you want to delete zone $DOMAIN with ID $ZONE_ID?"
if ui_confirm "Continue?" n; then
_debug "Continuing"
else
_die "Aborting"
fi
_loading2 "Deleting zone $DOMAIN with ID $ZONE_ID"
call_cf_v4 DELETE /zones/"$ZONE_ID"
;;
*)
_die "Parameters:
zone, record, listing"
esac
;;
# =================================================================================================
# -- change|set command
# =================================================================================================
change|set)
CMD2=$1
shift
case "$CMD2" in
# -- Zone
zone)
_pre_flight_check CF_
[ -z "$1" ] && { help change; _die "Missing arguments"; }
[ -z "$2" ] && { help change; _die "Missing arguments"; }
CLI_ZONE="$1"
_cf_zone_exists "$CLI_ZONE"
ZONE_ID="$(_cf_zone_id "$CLI_ZONE")"
shift
setting_items=''
# -- Map settings
declare -A map
map[security_level]="security_level"
map[cache_level]="cache_level"
map[rocket_loader]="rocket_loader"
map[minify]="minify"
map[development_mode]="development_mode"
map[mirage]="mirage"
map[ipv6]="ipv6"
# -- Loop through settings
while [ -n "$1" ]; do
_debug "Changing $1 on $CLI_ZONE"
setting=$1
shift
if [ -n "${map[$setting]}" ]; then
setting=${map[$setting]}
else
help change
_die "Error: Setting '$setting' is not a valid setting"
fi
setting_value=$1
shift
case "$setting" in
minify)
css=off
html=off
js=off
for s in ${setting_value//,/ }; do
case "$s" in
css|html|js) eval "$s"=on;;
*) _die "E.g: cloudflare $CMD1 zone <zone> minify css,html,js"
esac
done
setting_value="{\"css\":\"$css\",\"html\":\"$html\",\"js\":\"$js\"}"
;;
esac
if [ "${setting_value:0:1}" != '{' ]; then
setting_value="\"$setting_value\""
fi
setting_items="$setting_items${setting_items:+,}{\"id\":\"$setting\",\"value\":$setting_value}"
done
call_cf_v4 PATCH /zones/"$ZONE_ID"/settings "{\"items\":[$setting_items]}"
if [[ $? != 1 ]]; then
echo " -- $CURL_OUTPUT_GLOBAL"
fi
;;
record)
_pre_flight_check CF_
[ -z "$1" ] && { help change; _die "Missing arguments"; }
prm1=$1
prm2=$2
# Check if using direct ID mode: <zone-name|zone-id> <record-id> <setting> <value>...
if [ ${#prm2} = 32 ] && is_hex "$prm2"; then
shift 2 # consume prm1 and prm2
# Determine zone_id
if is_hex "$prm1"; then
zone_id=$prm1
else
zone_id=$(_cf_zone_id "$prm1")
[[ -z "$zone_id" ]] && _die "No zone found for \`$prm1'"
fi
record_id=$prm2
# Fetch record data using direct API call
if ! _cf_get_record "$zone_id" "$record_id"; then
_die "Failed to fetch record \`$record_id'"
fi
else
# Name-based mode: use findout_record
record_name=$1
shift
record_type=''
first_match=0
record_oldcontent=''
while [ -n "$1" ]
do
case "$1" in
first) first_match=1;;
type) shift; record_type=${1^^};;
oldcontent) shift; record_oldcontent=$1;;
*) break;;
esac
shift
done
[ -z "$1" ] && { help change; _die "Missing arguments"; }
findout_record "$record_name" "$record_type" "$first_match" "$record_oldcontent"
e=$?
case $e in
0) true;;
2) _die "No suitable DNS zone found for \`$record_name'";;
3) _die "DNS record \`$record_name' not found";;
4) _die "Ambiguous record name: \`$record_name'";;
*) _die "Internal error";;
esac
fi
record_content_esc=${record_content//\"/\\\"}
old_data="\"name\":\"$record_name\",\"type\":\"$record_type\",\"ttl\":$record_ttl,\"content\":\"$record_content_esc\""
new_data=''
while [ -n "$1" ]; do
setting=$1
shift
value=$1
shift
[ "$setting" = service_mode ] && setting="proxied"
[[ $setting == newtype || $setting == new_type ]] && setting="type"
[[ $setting == newname || $setting == new_name ]] && setting="name"
[ "$setting" = newcontent ] && setting="content"
# Validate setting is a known DNS record field
case "$setting" in
content|ttl|name|type|proxied|priority|comment) ;;
*) _die "Unknown record setting: \`$setting'. Valid settings: content, ttl, name, type, proxied, priority, comment";;
esac
if [ "$setting" = proxied ]; then
value=${value,,}
[[ $value == on || $value == 1 ]] && value=true
[[ $value == off || $value == 0 ]] && value=false
fi
[ "$setting" = type ] && value=${value^^}
if [ "$setting" != content ] && ( expr "$value" : '[0-9]\+$' >/dev/null || expr "$value" : '[0-9]\+\.[0-9]\+$' >/dev/null || [[ $value == true || $value == false ]] )
then
value_escq=$value
else
value_escq=\"${value//\"/\\\"}\"
fi
new_data="$new_data${new_data:+,}\"$setting\":$value_escq"
done
_loading2 "Updating record $record_name ($record_id)"
if call_cf_v4 PUT /zones/"$zone_id"/dns_records/"$record_id" "{$old_data,$new_data}" -- \
%" ID: %s$NL Name: %s$NL Type: %s$NL Content: %s$NL TTL: %s$NL Proxied: %s$NL" ,id,name,type,content,ttl,proxied; then
ui_ok "Record updated successfully"
else
ui_err "Failed to update record"
fi
;;
*)
help change
_die "Missing argument."
esac
;;
# =================================================================================================
# -- clear command
# =================================================================================================
clear)
case "$1" in
cache)
shift
[ -z "$1" ] && { help clear; exit 1;}
_pre_flight_check CF_
CLI_ZONE="$1"
_cf_zone_exists "$CLI_ZONE"
ZONE_ID=$(_cf_zone_id "$CLI_ZONE")
call_cf_v4 DELETE /zones/"$ZONE_ID"/purge_cache '{"purge_everything":true}'
;;
*)
help clear
exit 1;
;;
esac
;;
# =================================================================================================
# -- invalidate command
# =================================================================================================
invalidate)
if [ -n "$1" ]
then
_pre_flight_check CF_
urls=''
zone_id=''
for url in "${*[@]}"; do
urls="${urls:+$urls,}\"$url\""
if [ -z "$zone_id" ]
then
if [[ "$url" =~ ^([^:]+:)?/*([^:/]+) ]]
then
re_grps=${#BASH_REMATCH[@]}
domain=${BASH_REMATCH[re_grps-1]}