forked from erjosito/azcli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aks.azcli
1371 lines (1257 loc) · 51.6 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=wl-akstest
location=westcentralus
wait_interval=5s
use_msi=yes
# AKS
aks_name=aks
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=calico # azure/calico/cilium/none
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
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
fi
}
# enableAksFeature "AKS-IngressApplicationGatewayAddon"
# enableAksFeature "EnablePodIdentityPreview"
# enableAksFeature "MigrateToMSIClusterPreview"
# enableAksFeature "PodSubnetPreview"
# enableAksFeature "EnableAPIServerVnetIntegrationPreview"
# enableAksFeature "CiliumDataplanePreview"
# 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")
acr_id=$(az acr show -n erjositoAcr -g $acr_rg --query id -o tsv)
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)
if [[ "$preview_version" == "yes" ]]
then
k8s_version=$(echo $k8s_versions | jq '.orchestrators[]' | jq -rsc 'sort_by(.orchestratorVersion) | reverse[0] | .orchestratorVersion')
echo "Latest supported k8s version is $k8s_version (in preview)"
else
k8s_version=$(echo $k8s_versions | jq '.orchestrators[] | select(.isPreview == null)' | jq -rsc 'sort_by(.orchestratorVersion) | reverse[0] | .orchestratorVersion')
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
cni_options="--network-plugin azure"
elif [[ "$network_plugin" == 'kubenet' ]]; then
cni_options="--network-plugin kubenet"
elif [[ "$network_plugin" == 'azure_cilium' ]]; then
cni_options="--network-plugin azure --network-dataplane cilium"
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
# Create AKS
echo "Deploying cluster..."
az aks create -g $rg -n $aks_name -l $location -o none \
--pod-subnet-id $pod_subnet_id \
-c 1 -s $vm_size -k $k8s_version --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
# --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
####################
# 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"
#####################
# 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:
- to:
- ipBlock:
cidr: 0.0.0.0/0
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
podSelector:
matchLabels:
k8s-app: kube-dns
ports:
- protocol: TCP
port: 443
- protocol: TCP
port: 1433
- protocol: UDP
port: 53
EOF
cat <<EOF | kubectl apply -f -
apiVersion: "cilium.io/v2"
kind: CiliumNetworkPolicy
metadata:
name: api-netpol
namespace: default
spec:
endpointSelector:
matchLabels:
run: api
ingress:
- fromEndpoints:
- matchLabels:
run: web
toPorts:
- ports:
- port: "8081"
protocol: "TCP"
egress:
- toEndpoints:
- matchLabels:
"k8s:io.kubernetes.pod.namespace": kube-system
"k8s:k8s-app": kube-dns
toPorts:
- ports:
- port: "53"
protocol: ANY
EOF
yadaapi_ip=$(kubectl get svc/api -o json | jq -rc '.status.loadBalancer.ingress[0].ip' 2>/dev/null) && echo $yadaapi_ip
yadaweb_ip=$(kubectl get svc/web -o json | jq -rc '.status.loadBalancer.ingress[0].ip' 2>/dev/null) && echo $yadaweb_ip
curl -s4 "http://${yadaapi_ip}:8080/api/healthcheck"
curl -s4 "http://${yadaweb_ip}/healthcheck.html"
yadaapi_egress_ip=$(curl -s "http://${yadaapi_ip}:8080/api/ip" | jq -r .my_public_ip)
echo "YADA API egress IP: $yadaapi_egress_ip"
az sql server firewall-rule create -g "$rg" -s "$sql_server_name" -n public_api_aci-source --start-ip-address "$yadaapi_egress_ip" --end-ip-address "$yadaapi_egress_ip"
# Service with kubectl
kubectl expose deploy yadaapi --port=80 --target-port=8080
# Service
app_name=sqlapi
yaml_file=/tmp/svc.yaml
cat <<EOF > $yaml_file
apiVersion: v1
kind: Service
metadata:
annotations:
service.beta.kubernetes.io/azure-load-balancer-internal: "true"
service.beta.kubernetes.io/azure-load-balancer-internal-subnet: "akslb"
name: $app_name
spec:
type: ClusterIP
ports:
- port: 8080
selector:
app: $app_name
EOF
kubectl apply -f $yaml_file
# Service with Static PIP
svc_pip_name=k8ssvcpip
az network public-ip create -g $rg -n $svc_pip_name --sku Standard --allocation-method static
svc_pip_ip=$(az network public-ip show -n $svc_pip_name -g $rg --query ipAddress -o tsv) && echo $svc_pip_ip
svc_pip_id=$(az network public-ip show -n $svc_pip_name -g $rg --query id -o tsv) && echo $svc_pip_id
if [[ "$use_msi" == no ]]
then
client_id=$sp_app_id
else
client_id=$id_principal_id
fi
az role assignment create --assignee $client_id --role "Network Contributor" --scope $svc_pip_id
yaml_file=/tmp/svc.yaml
cat <<EOF > $yaml_file
apiVersion: v1
kind: Service
metadata:
annotations:
service.beta.kubernetes.io/azure-load-balancer-resource-group: $rg
name: kuard
spec:
loadBalancerIP: $svc_pip_ip
type: LoadBalancer
ports:
- port: 8080
selector:
app: kuard
EOF
kubectl apply -f $yaml_file
echo "Browse to http://$svc_pip_ip:8080"
# Workload with PV/PVC
yaml_file=/tmp/pvc.yaml
cat <<EOF > $yaml_file
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: premiumpvc
spec:
accessModes:
- ReadWriteOnce
storageClassName: managed-premium
resources:
requests:
storage: 5Gi
---
kind: Pod
apiVersion: v1
metadata:
name: sqlapi
labels:
run: sqlapi
spec:
containers:
- name: mypod
image: erjosito/sqlapi:1.0
imagePullPolicy: Always
resources:
requests:
cpu: 250m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
volumeMounts:
- mountPath: "/mnt/azure"
name: volume
volumes:
- name: volume
persistentVolumeClaim:
claimName: premiumpvc
---
apiVersion: v1
kind: Service
metadata:
labels:
run: sqlapi
name: sqlapi
spec:
ports:
- port: 80
protocol: TCP
targetPort: 8080
selector:
run: sqlapi
sessionAffinity: None
type: LoadBalancer
EOF
kubectl apply -f $yaml_file
# Diagnostics
k get sc
k get pvc
k get pv
k get svc
node1_name=$(k get node -o jsonpath='{.items[0].metadata.name}') && echo $node1_name
node1_drivers=$(kubectl get CSINode $node1_name -o jsonpath="{.spec.drivers}") && echo $node1_drivers
node1_disk_count=$(kubectl get CSINode $node1_name -o jsonpath="{.spec.drivers[1].allocatable.count}") && echo $node1_disk_count
svc_ip=$(kubectl get svc/sqlapi -o json | jq -rc '.status.loadBalancer.ingress[0].ip' 2>/dev/null) && echo $svc_ip
curl "http://${svc_ip}/api/healthcheck"
curl "http://${svc_ip}/api/healthcheck/api/ioperf?file=%2Fmnt%2Fazure%2Fiotest"
###########################
# AGIC #
###########################
# Create AGIC addon
echo "Creating subnet for AppGW..."
az network vnet subnet create -n $appgw_subnet_name --vnet-name $vnet_name -g $rg --address-prefixes $appgw_subnet_prefix -o none
appgw_subnet_id=$(az network vnet subnet show -n $appgw_subnet_name --vnet-name $vnet_name -g $rg --query id -o tsv)
echo "Enabling AGIC..."
az aks enable-addons -a ingress-appgw -n $aks_name -g $rg --appgw-subnet-id $appgw_subnet_id -o none
# Create ingress rule
node_rg=$(az aks show -n $aks_name -g $rg --query nodeResourceGroup -o tsv)
appgw_name=$(az network application-gateway list -g $node_rg --query '[0].name' -o tsv)
appgw_pip_id=$(az network application-gateway frontend-ip list --gateway-name $appgw_name -g $node_rg --query '[0].publicIpAddress.id' -o tsv)
appgw_pip=$(az network public-ip show --ids $appgw_pip_id --query 'ipAddress' -o tsv)
cat <<EOF | kubectl apply -f -
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: sqlapi
annotations:
kubernetes.io/ingress.class: azure/application-gateway
appgw.ingress.kubernetes.io/health-probe-path: "/api/healthcheck"
spec:
rules:
- host: sqlapi.${appgw_pip}.nip.io
http:
paths:
- path: /api/
pathType: Prefix
backend:
service:
name: sqlapi
port:
number: 8080
EOF
curl "http://sqlapi.${appgw_pip}.nip.io/api/healthcheck"
curl "http://sqlapi.${appgw_pip}.nip.io/api/ip"
##################
# Private Link #
##################
# Create subnet
az network vnet subnet create -n $ep_subnet_name --vnet-name $vnet_name -g $rg --address-prefixes $ep_subnet_prefix -o none
# Create SQL Database
sql_server_name=sqlserver$RANDOM
sql_db_name=mydb
sql_username=azure
sql_password='Microsoft123!'
az sql server create -n $sql_server_name -g $rg -l $location --admin-user $sql_username --admin-password $sql_password -o none
sql_server_fqdn=$(az sql server show -n $sql_server_name -g $rg -o tsv --query fullyQualifiedDomainName)
az sql db create -n $sql_db_name -s $sql_server_name -g $rg -e Basic -c 5 --no-wait
# Create endpoint
echo "Creating SQL Server endpoint..."
sql_endpoint_name=sqlep
sql_server_id=$(az sql server show -n $sql_server_name -g $rg -o tsv --query id)
az network private-endpoint create -n $sql_endpoint_name -g $rg -o none\
--vnet-name $vnet_name --subnet $ep_subnet_name \
--private-connection-resource-id $sql_server_id --group-id sqlServer --connection-name sqlConnection
# Create Azure DNS private zone and records
dns_zone_name=privatelink.database.windows.net
echo "Creating DNS zone $dns_zone_name..."
az network private-dns zone create -n $dns_zone_name -g $rg -o none
az network private-dns link vnet create -g $rg -z $dns_zone_name -n myDnsLink --virtual-network $vnet_name --registration-enabled false -o none
az network private-endpoint dns-zone-group create --endpoint-name $sql_endpoint_name -g $rg -n sqlzonegroup --zone-name zone1 --private-dns-zone $dns_zone_name -o none
# Create a deployment:
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:
app: sqlapi
name: sqlapi
spec:
replicas: 1
selector:
matchLabels:
app: sqlapi
template:
metadata:
labels:
app: sqlapi
spec:
containers:
- image: erjosito/sqlapi:1.0
name: sqlapi
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: sqlapi
spec:
type: ClusterIP
ports:
- port: 8080
targetPort: 8080
selector:
app: sqlapi
EOF
# Test
curl "http://sqlapi.${appgw_pip}.nip.io/api/dns?fqdn=${sql_server_fqdn}"
curl "http://sqlapi.${appgw_pip}.nip.io/api/sqlsrcip"
##############################
# Daemonset to install stuff #
##############################
kubectl create ns node-installer
yaml_file=/tmp/podid.yaml
cat <<EOF > $yaml_file
apiVersion: v1
kind: ConfigMap
metadata:
name: sample-installer-config
namespace: node-installer
data:
install.sh: |
#!/bin/bash
# echo "Updating repositories..."
# sudo touch /var/lib/man-db/auto-update
# apt-get update
# echo "Installing sample app..."
# apt-get install cowsay -y
echo "Restarting containerd..."
# service containerd restart
systemctl restart containerd
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: installer
namespace: node-installer
spec:
selector:
matchLabels:
job: installer
template:
metadata:
labels:
job: installer
spec:
hostPID: true
restartPolicy: Always
containers:
- image: patnaikshekhar/node-installer:1.3
name: installer
securityContext:
privileged: true
volumeMounts:
- name: install-script
mountPath: /tmp
- name: host-mount
mountPath: /host
volumes:
- name: install-script
configMap:
name: sample-installer-config
- name: host-mount
hostPath:
path: /tmp/install
EOF
kubectl apply -f $yaml_file
#####################
# Azure Advisor #
#####################
aks_id=$(az aks show -n $aks_name -g $rg --query id -o tsv)
az advisor recommendation list --ids $aks_id -o table
#######################
# Workload Identity #
#######################
# Variables
workload_id_name=workloadidtest # Name of the User-Assigned Managed Identity
federated_id_name=federatedid # Name for the identity federation
akv_name=erjositoKeyvault # Keyvault to test
akv_secret_name=defaultPassword # Secret to test
sa_name=myserviceaccount
sa_namespace=default
# Enable workload identity and create identity
enableAksFeature EnableWorkloadIdentityPreview
echo "Enabling workload identity in cluster..."
az aks update -n $aks_name -g $rg --enable-oidc-issuer --enable-workload-identity true -o none
aks_oidc_issuer="$(az aks show -n $aks_name -g $rg --query "oidcIssuerProfile.issuerUrl" -o tsv)"
echo "Creating managed identity..."
az identity create -n $workload_id_name -g $rg -o none
workload_id_id="$(az identity show -n $workload_id_name -g $rg --query 'clientId' -o tsv)"
sleep 30 # Sometimes it takes some time to properly create the identity
az keyvault set-policy -n $akv_name --secret-permissions get --spn "${workload_id_id}" -o none
# Create service account
echo "Creating service account in AKS cluster..."
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: ServiceAccount
metadata:
annotations:
azure.workload.identity/client-id: ${workload_id_id}
labels:
azure.workload.identity/use: "true"
name: $sa_name