-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathaks.azcli
1784 lines (1635 loc) · 63.9 KB
/
aks.azcli
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
#################################
# Created by Jose Moreno
# July 2020
#
# Some useful commands around AKS
#################################
# Variables
rg=akstest
location=eastus2
wait_interval=5s
use_msi=yes
# AKS
aks_name=akscilium
aks_rbac=yes
aks_service_cidr=10.0.0.0/16
vm_size=Standard_B2ms # Some possible values: Standard_B2ms, Standard_D2_v3
preview_version=yes
network_plugin=azure_cilium # azure/kubenet/none/azure_overlay/azure_cilium
network_policy=cilium # azure/calico/cilium/none
azure_cni_pod_subnet=no # yes/no
az_monitor=no
# Vnet
vnet_name=aksVnet
vnet_prefix=10.13.0.0/16
aks_subnet_name=aks1stpool
aks_subnet_prefix=10.13.76.0/24 # Min /25 with Azure CNI!
aks2_subnet_name=aks2ndpool
aks2_subnet_prefix=10.13.75.0/24
aks2_pod_subnet_name=aks2ndpoolpods
aks2_pod_subnet_prefix=10.13.65.0/24
pod_subnet_name=pods
pod_subnet_prefix=10.13.80.0/24
vm_subnet_name=vm
vm_subnet_prefix=10.13.1.0/24
bastion_subnet_name=AzureBastionSubnet
bastion_subnet_prefix=10.13.15.0/24
bastion_name=aksbastion
appgw_subnet_name=AppGateway
appgw_subnet_prefix=10.13.10.0/24
azfw_subnet_prefix=10.13.11.0/24
apim_subnet_prefix=10.13.12.0/24
db_subnet_prefix=10.13.50.0/24
akslb_subnet_prefix=10.13.77.0/24
arm_subnet_prefix=10.13.79.0/24
aci_subnet_name=aci
aci_subnet_prefix=10.13.100.0/24
ep_subnet_name=aci
ep_subnet_prefix=10.13.101.0/24
# Other resources
kv_name=erjositoKeyvault
acr_name=erjositoAcr
####################
# Helper functions #
####################
# Wait for resource to be created
function wait_until_finished {
wait_interval=15
resource_id=$1
resource_name=$(echo $resource_id | cut -d/ -f 9)
echo "Waiting for resource $resource_name to finish provisioning..."
start_time=`date +%s`
state=$(az resource show --id $resource_id --query properties.provisioningState -o tsv)
until [[ "$state" == "Succeeded" ]] || [[ "$state" == "Failed" ]] || [[ -z "$state" ]]
do
sleep $wait_interval
state=$(az resource show --id $resource_id --query properties.provisioningState -o tsv)
done
if [[ -z "$state" ]]
then
echo "Something really bad happened..."
else
run_time=$(expr `date +%s` - $start_time)
((minutes=${run_time}/60))
((seconds=${run_time}%60))
echo "Resource $resource_name provisioning state is $state, wait time $minutes minutes and $seconds seconds"
fi
}
###################
# Enable features #
###################
function enableAksFeature () {
feature_name=$1
state=$(az feature list -o table --query "[?contains(name, 'microsoft.containerservice/$feature_name')].properties.state" -o tsv)
if [[ "$state" == "Registered" ]]
then
echo "$feature_name is already registered"
else
echo "Registering feature $feature_name..."
az feature register --name "$feature_name" --namespace microsoft.containerservice -o none --only-show-errors
state=$(az feature list -o table --query "[?contains(name, 'microsoft.containerservice/$feature_name')].properties.state" -o tsv)
echo "Waiting for feature $feature_name to finish registering..."
wait_interval=15
until [[ "$state" == "Registered" ]]
do
sleep $wait_interval
state=$(az feature list -o table --query "[?contains(name, 'microsoft.containerservice/$feature_name')].properties.state" -o tsv)
echo "Current registration status for feature $feature_name is $state"
done
echo "Registering resource provider Microsoft.ContainerService now..."
az provider register --namespace Microsoft.ContainerService -o none --only-show-errors
fi
}
# enableAksFeature "AKS-IngressApplicationGatewayAddon"
# enableAksFeature "EnablePodIdentityPreview"
# enableAksFeature "MigrateToMSIClusterPreview"
# enableAksFeature "PodSubnetPreview"
# enableAksFeature "EnableAPIServerVnetIntegrationPreview"
# enableAksFeature "CiliumDataplanePreview"
# enableAksFeature "AzureServiceMeshPreview"
enableAksFeature "NetworkObservabilityPreview"
# Update extension
echo "Updating aks-preview extension..."
az extension update -n aks-preview
########
# Main #
########
# Create RG, LA workspace, vnet, AKS
echo "Creating RG and VNet..."
az group create -n $rg -l $location -o none
acr_rg=$(az acr list -o tsv --query "[?name=='$acr_name'].resourceGroup") && echo "ACR RG is '$acr_rg'"
if [[ -n "$acr_rg" ]]; then
acr_id=$(az acr show -n erjositoAcr -g $acr_rg --query id -o tsv)
fi
az network vnet create -g $rg -n $vnet_name --address-prefix $vnet_prefix -l $location -o none
az network vnet subnet create -g $rg -n $aks_subnet_name --vnet-name $vnet_name --address-prefix $aks_subnet_prefix -o none
az network vnet subnet create -g $rg -n $pod_subnet_name --vnet-name $vnet_name --address-prefix $pod_subnet_prefix -o none
aks_subnet_id=$(az network vnet subnet show -n $aks_subnet_name --vnet-name $vnet_name -g $rg --query id -o tsv)
pod_subnet_id=$(az network vnet subnet show -n $pod_subnet_name --vnet-name $vnet_name -g $rg --query id -o tsv)
# Create LA workspace
if [[ "$az_monitor" == 'yes' ]]; then
logws_name=$(az monitor log-analytics workspace list -g $rg --query '[0].name' -o tsv)
if [[ -z "$logws_name" ]]
then
logws_name=log$RANDOM
echo "INFO: Creating log analytics workspace ${logws_name}..."
az monitor log-analytics workspace create -n $logws_name -g $rg -o none
else
echo "INFO: Log Analytics workspace $logws_name found in resource group $rg"
fi
logws_id=$(az resource list -g $rg -n $logws_name --query '[].id' -o tsv)
logws_customerid=$(az monitor log-analytics workspace show -n $logws_name -g $rg --query customerId -o tsv)
fi
# Get latest supported/preview version
# k8s_versions=$(az aks get-versions -l $location -o json --only-show-errors)
# if [[ "$preview_version" == "yes" ]]
# then
# k8s_version=$(echo $k8s_versions | jq -r '.values | map(select(.isPreview == true))[0] | .version')
# echo "Latest supported k8s version is $k8s_version (in preview)"
# else
# k8s_version=$(echo $k8s_versions | jq -r '.values | map(select(.isPreview == null))[0] | .version')
# echo "Latest supported k8s version (not in preview) is $k8s_version"
# fi
# Setting identity flags (managed identity or SP)
if [[ "$use_msi" == no ]]
then
# Get SP from AKV
keyvault_name=joseakv-airs
purpose=aks
keyvault_appid_secret_name=$purpose-sp-appid
keyvault_password_secret_name=$purpose-sp-secret
sp_app_id=$(az keyvault secret show --vault-name $keyvault_name -n $keyvault_appid_secret_name --query 'value' -o tsv) && echo $sp_app_id
sp_app_secret=$(az keyvault secret show --vault-name $keyvault_name -n $keyvault_password_secret_name --query 'value' -o tsv)
# Assign contributor role to the vnet
vnet_id=$(az network vnet show -n $vnet_name -g $rg --query id -o tsv)
az role assignment create --scope $vnet_id --assignee $sp_app_id --role Contributor
# az aks create flags
identity_options="--service-principal $sp_app_id --client-secret $sp_app_secret --skip-subnet-role-assignment"
else
# User identity
id_name=aksid
id_id=$(az identity show -n $id_name -g $rg --query id -o tsv 2>/dev/null)
if [[ -z "$id_id" ]]
then
echo "Identity $id_name not found, creating a new one..."
az identity create -n $id_name -g $rg -o none
id_id=$(az identity show -n $id_name -g $rg --query id -o tsv)
else
echo "Identity $id_name found with ID $id_id"
fi
id_principal_id=$(az identity show -n $id_name -g $rg --query principalId -o tsv)
vnet_id=$(az network vnet show -n $vnet_name -g $rg --query id -o tsv)
sleep 15 # Time for creation to propagate
az role assignment create --scope $vnet_id --assignee $id_principal_id --role Contributor -o none
# User identity
identity_options="--enable-managed-identity --assign-identity $id_id"
# System identity
# identity_options="--enable-managed-identity"
fi
# Change network policy format if none specified
if [[ "$network_policy" == 'none' ]]; then
network_policy="''"
fi
# CNI options
if [[ "$network_plugin" == 'azure' ]]; then
if [[ "$azure_cni_pod_subnet" == "yes" ]]; then
cni_options="--network-plugin azure --pod-subnet-id $pod_subnet_id"
else
cni_options="--network-plugin azure"
fi
elif [[ "$network_plugin" == 'kubenet' ]]; then
cni_options="--network-plugin kubenet"
elif [[ "$network_plugin" == 'azure_cilium' ]]; then
cni_options="--network-plugin azure --network-dataplane cilium --pod-subnet-id $pod_subnet_id"
if [[ "$network_policy" != "cilium" ]]; then
echo "Network policy must be cilium when using azure_cilium. Setting network policy to cilium..."
network_policy=cilium
fi
elif [[ "$network_plugin" == 'azure_overlay' ]]; then
cni_options="--network-plugin azure --network-dataplane cilium --network-plugin-mode overlay"
if [[ "$network_policy" != "cilium" ]]; then
echo "Network policy must be cilium when using azure_cilium. Setting network policy to cilium..."
network_policy=cilium
fi
else
echo "ERROR: Network plugin $network_plugin not supported"
exit 1
fi
# Error control because the code to get the k8s version is broken
if [[ -z "$k8s_version" ]]; then
k8s_version_options=""
else
k8s_version_options="-k $k8s_version"
fi
# Create AKS
echo "Deploying cluster..."
az aks create -g $rg -n $aks_name -l $location -o none --only-show-errors \
-c 1 -s $vm_size --generate-ssh-keys -u $(whoami) \
${(z)identity_options} \
${(z)cni_options} \
--vnet-subnet-id $aks_subnet_id --service-cidr $aks_service_cidr \
--network-policy $network_policy \
--load-balancer-sku Standard \
--node-resource-group "wl-$aks_name"-iaas-"$RANDOM" \
--dns-name-prefix cloudtrooper --no-wait
# Other options you can use in the previous command
# ${(z)k8s_version_options} \
# --enable-private-cluster --private-dns-zone none --disable-public-fqdn \
# --enable-apiserver-vnet-integration \
# --enable-cilium-dataplane \ # https://techcommunity.microsoft.com/t5/azure-networking-blog/azure-cni-powered-by-cilium-for-azure-kubernetes-service-aks/ba-p/3662341
# --pod-subnet-id $pod_subnet_id \
# --enable-pod-security-policy \ # Deprecated
# --enable-cluster-autoscaler --min-count 1 --max-count 3 \
# --cluster-autoscaler-profile scan-interval=30s \
# --dns-name-prefix cloudtrooper \
# --node-osdisk-type ephemeral --node-osdisk-size 30 \
# --outbound-type userDefinedRouting \
# --aks-custom-headers EnableAzureDiskFileCSIDriver=true \
# --os-sku Mariner \
# --uptime-sla \
# --network-policy 'calico' \
# --no-wait
########
# Wait #
########
aks_id=$(az aks show -n $aks_name -g $rg --query id -o tsv)
wait_until_finished $aks_id
# Get credentials for kubectl
az aks list -o table
az aks get-credentials -n $aks_name -g $rg --overwrite
kubectl get nodes
######################
# Modify the cluster #
######################
# Enable monitoring addon
if [[ "$az_monitor" == 'yes' ]]; then
az aks enable-addons -g $rg -n $aks_name --addons monitoring --workspace-resource-id "$logws_id"
fi
# Enable AKV addon (Work In Progress)
az aks enable-addons -g $rg -n $aks_name --addons azure-keyvault-secrets-provider
# Add cluster autoscaler (requires the monitoring addon)
az aks update -g $rg -n $aks_name --enable-cluster-autoscaler --min-count 1 --max-count 4
# Modify autoscaler profile (see https://docs.microsoft.com/azure/aks/cluster-autoscaler#using-the-autoscaler-profile)
az aks update -g $rg -n $aks_name --cluster-autoscaler-profile scale-down-unneeded-time=1m
# Enable virtual node
az network vnet subnet create -g $rg -n $aci_subnet_name --vnet-name $vnet_name --address-prefix $aci_subnet_prefix
az aks enable-addons --addons virtual-node -n $aks_name -g $rg --subnet-name $aci_subnet_name
# Enable Azure Policy
az aks enable-addons --addons azure-policy -n $aks_name -g $rg
# Add diag settings for cluster logs
aks_id=$(az aks show -n $aks_name -g $rg --query id -o tsv)
az monitor diagnostic-settings create -n mydiag --resource $aks_id --workspace $logws_id \
--metrics '[{"category": "AllMetrics", "enabled": true, "retentionPolicy": {"days": 0, "enabled": false }, "timeGrain": null}]' \
--logs '[{"category": "kube-apiserver", "enabled": true, "retentionPolicy": {"days": 0, "enabled": false}},
{"category": "kube-audit", "enabled": true, "retentionPolicy": {"days": 0, "enabled": false}},
{"category": "kube-audit-admin", "enabled": true, "retentionPolicy": {"days": 0, "enabled": false}},
{"category": "kube-controller-manager", "enabled": true, "retentionPolicy": {"days": 0, "enabled": false}},
{"category": "kube-scheduler", "enabled": true, "retentionPolicy": {"days": 0, "enabled": false}},
{"category": "cluster-autoscaler", "enabled": true, "retentionPolicy": {"days": 0, "enabled": false}},
{"category": "guard", "enabled": true, "retentionPolicy": {"days": 0, "enabled": false}}]'
# Migrate to MSI
az aks update -g $rg -n $aks_name --enable-managed-identity -y
# Update to new version
new_aks_version=1.21.2
az aks upgrade -n $aks_name -g $rg -k $new_aks_version -y
################################
# Managed Prometheus/Grafana #
################################
# Variables
grafana_name="${aks_name}-grafana-${RANDOM}"
monitor_ws_name="${aks_name}-monitor-${RANDOM}"
# Create Grafana/Prometheus
az grafana create -n $grafana_name -g $rg -o none
az monitor account create -n $monitor_ws_name -g $rg -l $location -o none
grafana_id=$(az grafana show -n $grafana_name -g $rg -o none --query id -o tsv)
monitor_ws_id=$(az monitor account show -n $monitor_ws_name -g $rg -o none --query id -o tsv)
az aks update --disable-azure-monitor-metrics -n $aks_name -g $rg -o none
az aks update --enable-azure-monitor-metrics -n $aks_name -g $rg --azure-monitor-workspace-resource-id $monitor_ws_id --grafana-resource-id $grafana_id -o none
# Browse
grafana_url=$(az grafana show -n $grafana_name -g $rg -o tsv --query properties.endpoint)
echo "Grafana URL is $grafana_url"
# Verify
kubectl get po -owide -n kube-system | grep ama-
kubectl get ds ama-metrics-node --namespace=kube-system
##################
# Retina #
##################
# https://retina.sh/docs/installation/setup
# Basic
VERSION=$( curl -sL https://api.github.com/repos/microsoft/retina/releases/latest | jq -r .name)
helm upgrade --install retina oci://ghcr.io/microsoft/retina/charts/retina \
--version $VERSION \
--namespace kube-system \
--set image.tag=$VERSION \
--set operator.tag=$VERSION \
--set logLevel=info \
--set enabledPlugin_linux="\[dropreason\,packetforward\,linuxutil\,dns\]"
# Advanced with local context (with capture support)
VERSION=$( curl -sL https://api.github.com/repos/microsoft/retina/releases/latest | jq -r .name)
helm upgrade --install retina oci://ghcr.io/microsoft/retina/charts/retina \
--version $VERSION \
--namespace kube-system \
--set image.tag=$VERSION \
--set operator.tag=$VERSION \
--set image.pullPolicy=Always \
--set logLevel=info \
--set os.windows=true \
--set operator.enabled=true \
--set operator.enableRetinaEndpoint=true \
--skip-crds \
--set enabledPlugin_linux="\[dropreason\,packetforward\,linuxutil\,dns\,packetparser\]" \
--set enablePodLevel=true \
--set enableAnnotations=true
# Uninstall
helm -n kube-system uninstall retina
# Import Retina dashboard to grafana
# dashboard_id=16611 # From https://learn.microsoft.com/en-us/azure/aks/network-observability-managed-cli?tabs=cilium#enable-visualization-on-grafana
dashboard_id=18814 # From https://retina.sh/docs/installation/grafana
az grafana dashboard import -g $rg -n $grafana_name --definition $dashboard_id -o none
# 412 Client Error: Precondition Failed for url: https://aks-grafana-5436-bvh4e6hagxfka2h4.eus2.grafana.azure.com/api/dashboards/import
####################
# Install Cilium #
####################
if [[ "$network_plugin" == 'none' ]]; then
CILIUM_CLI_VERSION=$(curl -s https://raw.githubusercontent.com/cilium/cilium-cli/master/stable.txt)
CLI_ARCH=amd64
if [ "$(uname -m)" = "aarch64" ]; then CLI_ARCH=arm64; fi
curl -L --fail --remote-name-all "https://github.com/cilium/cilium-cli/releases/download/${CILIUM_CLI_VERSION}/cilium-linux-${CLI_ARCH}.tar.gz{,.sha256sum}"
sha256sum --check cilium-linux-${CLI_ARCH}.tar.gz.sha256sum
sudo tar xzvfC cilium-linux-${CLI_ARCH}.tar.gz /usr/local/bin
rm cilium-linux-${CLI_ARCH}.tar.gz{,.sha256sum}
# Deploy Cilium
cilium install --azure-resource-group $rg
# Check status
cilium status
cilium connectivity test
k get no
fi
#######################
# Troubleshoot Cilium #
#######################
kubectl -n kube-system get pods -l k8s-app=cilium
cilium version
cilium status
cilium status --verbose
k get cep
kubectl get cep -o jsonpath='{range .items[*]}{@.status.id}{"="}{@.status.status.policy.spec.policy-enabled}{"\n"}{end}'
# From https://github.com/cilium/cilium/blob/main/contrib/k8s/k8s-cilium-exec.sh
function get_cilium_pods {
kubectl -n kube-system get pods -l k8s-app=cilium -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName | \
grep cilium
}
function run_command {
while read -r podName nodeName ; do
(
title="==== Detail from pod ${podName}, on node ${nodeName}"
msg=$( kubectl -n "kube-system" exec -c "cilium-agent" "${podName}" -- "${@}" 2>&1 )
echo -e "$title \n$msg\n"
)&
done <<< "$(get_cilium_pods)"
wait
}
run_command cilium status
run_command cilium-health status
# Cilium container logs:
# level=info msg="Imported CiliumNetworkPolicy" ciliumNetworkPolicyName=api-netpol k8sApiVersion= k8sNamespace=default subsys=k8s-watcher
# level=info msg="Policy imported via API, recalculating..." policyAddRequest=512e7deb-c02c-4e5a-b9bd-79481ebee0af policyRevision=19 subsys=daemon
# level=info msg="Rewrote endpoint BPF program" containerID= datapathPolicyRevision=18 desiredPolicyRevision=19 endpointID=644 identity=23553 ipv4= ipv6= k8sPodName=/ subsys=endpoint
# Monitor
label="run=api"
workload_pod_name=$(kubectl get pods -l $label -o jsonpath='{.items[0].metadata.name}')
workload_node_name=$(kubectl get pods -l $label -o jsonpath='{.items[0].spec.nodeName}')
cilium_pod_name=$(kubectl -n kube-system get pods -l k8s-app=cilium -o jsonpath="{.items[?(@.spec.nodeName=='$workload_node_name')].metadata.name}")
apipod_ip=$(kubectl get pods -l run=api -o jsonpath='{.items[0].status.podIP}')
# See https://docs.cilium.io/en/stable/cmdref/cilium_monitor/
kubectl -n kube-system exec -ti $cilium_pod_name -- cilium monitor
kubectl -n kube-system exec -ti $cilium_pod_name -- cilium monitor --type drop
kubectl -n kube-system exec -ti $cilium_pod_name -- cilium monitor --from 567
kubectl -n kube-system exec -ti $cilium_pod_name -- cilium monitor --from $apipod_ip --type drop
kubectl -n kube-system exec -ti $cilium_pod_name -- cilium monitor | grep -v 168.63.129.16 | grep "$apipod_ip" | grep "$webpod_ip"
# Sample outputs
# xx drop (Policy denied) flow 0x48bbc6f0 to endpoint 644, file bpf_lxc.c line 2001, , identity world->23553: 168.63.129.16:53042 -> 10.13.80.36:8080 tcp SYN
# xx drop (Policy denied) flow 0x290953e8 to endpoint 0, file bpf_lxc.c line 1182, , identity 23553->11944: 10.13.80.36:35161 -> 10.13.80.15:53 udp
# xx drop (Policy denied) flow 0xaccce700 to endpoint 0, file bpf_lxc.c line 1182, , identity 23553->world: 10.13.80.36:49057 -> 13.71.193.33:1433 tcp SYN
# xx drop (Policy denied) flow 0xd7fa1fe8 to endpoint 0, file bpf_lxc.c line 1182, , identity 23553->world: 10.13.80.36:52243 -> 13.78.248.58:11039 tcp SYN
# Finding pod ID (from ceps)
apipod_id=$(k get cep -l run=api -o jsonpath='{.items[0].status.id}') && echo "API pod has ID $apipod_id"
# Finding pod ID (from the cilium pod)
kubectl -n kube-system exec -ti $cilium_pod_name -- cilium endpoint list -o jsonpath='{range [*]}{.id}{"\t"}{.status.external-identifiers.pod-name}{"\n"}{end}'
ns=default
apipod_name=$(kubectl get pods -n $ns -l run=api -o jsonpath='{.items[0].metadata.name}')
apipod_id=$(kubectl -n kube-system exec -ti $pod_name -- cilium endpoint list -o jsonpath="{[?(@.status.external-identifiers.pod-name=='$ns/$apipod_name')].id}") && echo $apipod_id
kubectl -n kube-system exec -ti $cilium_pod_name -- cilium monitor --from $apipod_id --type drop
# From cilium pod
kubectl -n kube-system exec -ti $cilium_pod_name -- bash
root@aks-nodepool1-34838928-vmss000000:/home/cilium# cilium endpoint get 644 -o jsonpath='{range ..status.policy.realized.l4.ingress[*].derived-from-rules}{@}{"\n"}{end}'|tr -d ']['
"k8s:io.cilium.k8s.policy.derived-from=CiliumNetworkPolicy","k8s:io.cilium.k8s.policy.name=api-netpol","k8s:io.cilium.k8s.policy.namespace=default","k8s:io.cilium.k8s.policy.uid=ddd4a267-38c1-411a-883f-3f52a176cfc5"
root@aks-nodepool1-34838928-vmss000000:/home/cilium# cilium policy get k8s:io.cilium.k8s.policy.uid=ddd4a267-38c1-411a-883f-3f52a176cfc5
root@aks-nodepool1-34838928-vmss000000:/home/cilium# cilium endpoint get 644 -o jsonpath='{range ..status.policy.realized.l4.egress[*].derived-from-rules}{@}{"\n"}{end}'|tr -d ']['
"k8s:io.cilium.k8s.policy.derived-from=CiliumNetworkPolicy","k8s:io.cilium.k8s.policy.name=api-netpol","k8s:io.cilium.k8s.policy.namespace=default","k8s:io.cilium.k8s.policy.uid=ddd4a267-38c1-411a-883f-3f52a176cfc5"
"k8s:io.cilium.k8s.policy.derived-from=CiliumNetworkPolicy","k8s:io.cilium.k8s.policy.name=api-netpol","k8s:io.cilium.k8s.policy.namespace=default","k8s:io.cilium.k8s.policy.uid=ddd4a267-38c1-411a-883f-3f52a176cfc5"
#####################
# Egress Gateway #
#####################
az aks nodepool add --cluster-name $aks_name -g $rg -n egressgws --node-count 1 -s $vm_size --mode User \
--node-taints "kubeegressgateway.azure.com/mode=true:NoSchedule" --labels "kubeegressgateway.azure.com/mode=true" -o none
# Prepare Helm chart values file (using MSI created for the cluster)
config_file='/tmp/azure_config.yaml'
# Config file for MSI
url=https://raw.githubusercontent.com/Azure/kube-egress-gateway/main/docs/samples/sample_azure_config_msi.yaml
# config:
# azureCloudConfig:
# cloud: "AzurePublicCloud"
# tenantId: "<tenant ID>"
# subscriptionId: "<subscription ID>"
# useManagedIdentityExtension: true
# userAssignedIdentityID: "<user assigned msi clientID>"
# userAgent: "kube-egress-gateway-controller"
# resourceGroup: "<resource group name>"
# location: "<resource group location>"
# gatewayLoadBalancerName: "kubeegressgateway-ilb"
# loadBalancerResourceGroup: ""
# vnetName: "<virtual network name>"
# vnetResourceGroup: ""
# subnetName: "<subnet name>"
wget $url -q -O $config_file
tenant_id=$(az account show -o tsv --query tenantId)
subscription_id=$(az account show --query id -o tsv)
id_id=$(az identity show -g $rg -n $id_name -o tsv --query id)
sed -i "s|<tenant ID>|${tenant_id}|g" $config_file
sed -i "s|<subscription ID>|${subscription_id}|g" $config_file
sed -i "s|<resource group name>|${rg}|g" $config_file
sed -i "s|<virtual network name>|${vnet_name}|g" $config_file
sed -i "s|<subnet name>|${aks_subnet_name}|g" $config_file
sed -i "s|<user assigned msi clientID>|${id_id}|g" $config_file
sed -i "s|<resource group location>|${location}|g" $config_file
# Config file for SP
url=https://raw.githubusercontent.com/Azure/kube-egress-gateway/main/docs/samples/sample_azure_config_sp.yaml
# config:
# azureCloudConfig:
# cloud: "AzurePublicCloud"
# tenantId: "<tenant ID>"
# subscriptionId: "<subscription ID>"
# useManagedIdentityExtension: false
# aadClientId: "<sp clientID>"
# aadClientSecret: "<sp secret>"
# userAgent: "kube-egress-gateway-controller"
# resourceGroup: "<resource group name>"
# location: "<resource group location>"
# gatewayLoadBalancerName: "kubeegressgateway-ilb"
# loadBalancerResourceGroup: ""
# vnetName: "<virtual network name>"
# vnetResourceGroup: ""
# subnetName: "<subnet name>"
app_name=egressgwsp
rg_id=$(az group show -n $rg -o tsv --query id)
sp_output=$(az ad sp create-for-rbac -n $app_name --role Contributor --scopes $rg_id)
sp_appid=$(echo $sp_output | jq -r '.appId')
sp_password=$(echo $sp_output | jq -r '.password')
wget $url -q -O $config_file
tenant_id=$(az account show -o tsv --query tenantId)
subscription_id=$(az account show --query id -o tsv)
id_id=$(az identity show -g $rg -n $id_name -o tsv --query id)
sed -i "s|<sp clientID>|${sp_appid}|g" $config_file
sed -i "s|<sp secret>|${sp_password}|g" $config_file
sed -i "s|<tenant ID>|${tenant_id}|g" $config_file
sed -i "s|<subscription ID>|${subscription_id}|g" $config_file
sed -i "s|<resource group name>|${rg}|g" $config_file
sed -i "s|<virtual network name>|${vnet_name}|g" $config_file
sed -i "s|<subnet name>|${aks_subnet_name}|g" $config_file
sed -i "s|<resource group location>|${location}|g" $config_file
# Helm chart install
git clone https://github.com/Azure/kube-egress-gateway.git
helm delete -n kube-egress-gateway-system kube-egress-gateway # In case you are re-installing the helm chart
helm install kube-egress-gateway ./kube-egress-gateway/helm/kube-egress-gateway \
--namespace kube-egress-gateway-system \
--create-namespace \
--set "common.imageRepository=mcr.microsoft.com/aks" --set "common.imageTag=v0.0.1" \
--values "$config_file"
# Deploy Gateway config
# https://github.com/azure/kube-egress-gateway
kubectl apply -f - <<EOF
apiVersion: egressgateway.kubernetes.azure.com/v1alpha1
kind: StaticGatewayConfiguration
metadata:
name: mystaticegressgateway
namespace: default
spec:
gatewayVmssProfile:
vmssResourceGroup: $rg
vmssName: myGatewayPool
publicIpPrefixSize: 31
provisionPublicIps: true
EOF
# Create pod
kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
name: yadaapi
labels:
app: yadaapi
annotations:
kubernetes.azure.com/static-gateway-configuration: mystaticegressgateway
spec:
containers:
- name: yadaapi
image: erjosito/yadaapi:1.0
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: yadapi
spec:
type: LoadBalancer
ports:
- port: 8080
selector:
app: yada
EOF
#####################
# Istio #
#####################
# Seems not to work wiht Cilium
# Enable Istio
echo "Enabling Istio addon..."
az aks mesh enable -n $aks_name -g $rg -o none
kubectl get pods -n aks-istio-system
# Enable ingress gateway
az aks mesh enable-ingress-gateway -n $aks_name -g $rg --ingress-gateway-type external -o none
kubectl get svc -n aks-istio-ingress
# Disable ingress gateway
az aks mesh disable-ingress-gateway -n $aks_name -g $rg --ingress-gateway-type external -y
# Deploy Gateway
# https://learn.microsoft.com/en-us/azure/aks/istio-deploy-ingress
kubectl apply -f - <<EOF
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
name: api-gateway-external
spec:
selector:
istio: aks-istio-ingressgateway-external
servers:
- port:
number: 80
name: http
protocol: HTTP
hosts:
- "*"
EOF
# Virtual Service
kubectl apply -f - <<EOF
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: api-external
spec:
hosts:
- "*"
gateways:
- api-gateway-external
http:
- match:
- uri:
prefix: /api/
route:
- destination:
host: yadaapi
port:
number: 80
EOF
# https://istio.io/latest/docs/tasks/traffic-management/request-routing/
kubectl apply -f - <<EOF
apiVersion: gateway.networking.k8s.io/v1beta1
kind: HTTPRoute
metadata:
name: yadaapi
spec:
parentRefs:
- group: ""
kind: Service
name: reviews
port: 8080
rules:
- backendRefs:
- name: reviews-v1
port: 9080
EOF
# TCP routing
# ===========
# Deploy TCP echo service
kubectl apply -f - <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
name: tcp-echo-deployment
labels:
app: tcp-echo
system: example
spec:
replicas: 1
selector:
matchLabels:
app: tcp-echo
template:
metadata:
labels:
app: tcp-echo
system: example
spec:
containers:
- name: tcp-echo-container
image: cjimti/go-echo:latest
imagePullPolicy: IfNotPresent
env:
- name: TCP_PORT
value: "2701"
- name: NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: SERVICE_ACCOUNT
valueFrom:
fieldRef:
fieldPath: spec.serviceAccountName
ports:
- name: tcp-echo-port
containerPort: 2701
---
apiVersion: v1
kind: Service
metadata:
name: "tcp-echo-service"
labels:
app: tcp-echo
system: example
spec:
selector:
app: "tcp-echo"
ports:
- protocol: "TCP"
port: 2701
targetPort: 2701
EOF
# Gateway
kubectl apply -f - <<EOF
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
name: echo-tcp-gateway
spec:
selector:
istio: aks-istio-ingressgateway-external
servers:
- port:
number: 31400
name: tcp-echo
protocol: TCP
hosts:
- "*"
EOF
# Virtual Service
kubectl apply -f - <<EOF
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: tcp-echo-vs-from-gw
spec:
hosts:
- "*"
gateways:
- echo-tcp-gateway
tcp:
- match:
- port: 31400
route:
- destination:
host: tcp-echo-service
port:
number: 2701
EOF
# Port 31400 had to be manually added to the SVC in aks-istio-ingress!!
# - name: tcpecho
# port: 31400
# protocol: TCP
# targetPort: 31400
# (the nodeport will be added automatically)
# From https://istio.io/latest/docs/tasks/traffic-management/request-routing/
# Not working with the AKS addon!
kubectl get crd gateways.gateway.networking.k8s.io &> /dev/null || \
{ kubectl kustomize "github.com/kubernetes-sigs/gateway-api/config/crd?ref=v0.8.0" | kubectl apply -f -; }
kubectl kustomize "github.com/kubernetes-sigs/gateway-api/config/crd/experimental?ref=v0.8.0" | kubectl apply -f
kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.19/samples/tcp-echo/tcp-echo-services.yaml
kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.19/samples/tcp-echo/gateway-api/tcp-echo-all-v1.yaml
#####################
# Create Az Bastion #
#####################
echo "Creating Azure Bastion..."
bastion_pip_name="${bastion_name}-pip"
az network vnet subnet create -g $rg -n $bastion_subnet_name --vnet-name $vnet_name --address-prefix $bastion_subnet_prefix -o none
az network public-ip create -g $rg -n $bastion_pip_name --sku Standard -l $location -o none
az network bastion create -n $bastion_name --public-ip-address $bastion_pip_name -g $rg --vnet-name $vnet_name -l $location \
--enable-ip-connect true --enable-tunneling true -o none
vm_id=$(az vm show -n $vm_name -g $rg --query id -o tsv)
az vm user update -u azureuser -p 'Microsoft123!' -n $vm_name -g $rg -o none
az network bastion tunnel -n $bastion_name -g $rg --target-resource-id $vm_id --resource-port 22 --port 2022
#####################
# IP restrictions #
#####################
myip=$(curl -s4 ifconfig.co) && echo $myip
az aks update -g $rg -n $aks_name --api-server-authorized-ip-ranges "${myip}/32"
#####################
# Add a second pool #
#####################
az network vnet subnet create -g $rg -n $aks2_subnet_name --vnet-name $vnet_name --address-prefix $aks2_subnet_prefix -o none
az network vnet subnet create -g $rg -n $aks2_pod_subnet_name --vnet-name $vnet_name --address-prefix $aks2_pod_subnet_prefix -o none
# vm_size=Standard_DS3_v2
vm_size=Standard_B2ms
aks2_subnet_id=$(az network vnet subnet show -n $aks2_subnet_name --vnet-name $vnet_name -g $rg --query id -o tsv)
aks2_pod_subnet_id=$(az network vnet subnet show -n $aks2_pod_subnet_name --vnet-name $vnet_name -g $rg --query id -o tsv)
az aks nodepool add --cluster-name $aks_name -g $rg -n pool2 --node-count 1 -s $vm_size \
-k $k8s_version --mode User --vnet-subnet-id $aks2_subnet_id \
--pod-subnet-id $aks2_pod_subnet_id
# --node-osdisk-type Ephemeral
# --enable-cluster-autoscaler --min-count 1 --max-count 2 \
az aks nodepool list --cluster-name $aks_name -g $rg -o table
###########################
# Deploy sample workloads #
###########################
az aks get-credentials -n $aks_name -g $rg --overwrite
kubectl create deployment kuard --image=gcr.io/kuar-demo/kuard-amd64:blue --port=8080 --replicas=1
kubectl create deployment yadaapi --image=erjosito/yadaapi:1.0 --port=8080 --replicas=1
# kubectl run yadaapi --image=erjosito/yadaapi:1.0 --port=8080 --env="SQL_SERVER_FQDN=${sql_server_fqdn}" --env="SQL_SERVER_USERNAME=${sql_username}" --env="SQL_SERVER_PASSWORD=${sql_password}"
# Full YADA app
sql_server_name=sqlserver$RANDOM
sql_db_name=mydb
sql_username=azure
sql_password=$(openssl rand -base64 10) # 10-character random password
echo "Creating SQL Server $sql_server_name..."
az sql server create -n $sql_server_name -g $rg -l $location --admin-user "$sql_username" --admin-password "$sql_password" -o none
az sql db create -n $sql_db_name -s $sql_server_name -g $rg -e Basic -c 5 --no-wait -o none
sql_server_fqdn=$(az sql server show -n $sql_server_name -g $rg -o tsv --query fullyQualifiedDomainName)
echo "SQL server created: $sql_server_fqdn"
echo "Creating API..."
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Secret
metadata:
name: sqlpassword
type: Opaque
stringData:
password: $sql_password
---
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
run: api
name: api
spec:
replicas: 1
selector:
matchLabels:
run: api
template:
metadata:
labels:
run: api
spec:
containers:
- image: erjosito/yadaapi:1.0
name: api
ports:
- containerPort: 8080
protocol: TCP
env:
- name: SQL_SERVER_USERNAME
value: "$sql_username"
- name: SQL_SERVER_FQDN
value: "$sql_server_fqdn"
- name: SQL_SERVER_PASSWORD
valueFrom:
secretKeyRef:
name: sqlpassword
key: password
restartPolicy: Always
---
apiVersion: v1
kind: Service
metadata:
name: api
spec:
type: LoadBalancer
ports:
- port: 8080
targetPort: 8080
selector:
run: api
EOF
echo "Creating Web..."
cat <<EOF | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
run: web
name: web
spec:
replicas: 1
selector:
matchLabels:
run: web
template:
metadata:
labels:
run: web
spec:
containers:
- image: erjosito/yadaweb:1.0
name: web
ports:
- containerPort: 80
protocol: TCP
env:
- name: API_URL
value: "http://api:8080"
restartPolicy: Always
---
apiVersion: v1
kind: Service
metadata:
name: web
spec:
type: LoadBalancer
ports:
- port: 80
targetPort: 80
selector:
run: web
EOF
cat <<EOF | kubectl apply -f -
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-netpol
namespace: default
spec:
podSelector:
matchLabels:
run: api
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
run: web
- ipBlock:
cidr: 10.13.76.0/24
- ipBlock:
cidr: 168.63.129.16/32
ports:
- protocol: TCP
port: 8080
egress: