Skip to content

OCI Kubernetes (OKE)

cloudspells.providers.oci.kubernetes

OKE (Oracle Kubernetes Engine) cluster spell for CloudSpells.

Provides OkeCluster, a high-level Pulumi component that creates a complete OKE cluster with a node pool, all required OCI security list rules, and four Network Security Groups (NSGs) that segment traffic by component role.

Subnet mapping:

OKE resources are placed across two of the four VCN tiers:

  • Public subnet — API endpoint (public IP for kubectl) + OCI Load Balancers created by LoadBalancer services.
  • Private subnet — Worker node VNICs and pod VNICs (OCI_VCN_IP_NATIVE). Workers and pods share this subnet's CIDR. NSGs discriminate between them at the VNIC level so the control plane, load balancer, and pods each see only the resources they are permitted to reach. Intra-subnet (pod-to-pod, node-to-node) traffic that stays within the same CIDR bypasses security list rules and is governed exclusively by NSGs.
  • Secure subnet — Not used by OKE; reserved for databases and secrets managers that must not initiate any internet connection.
  • Management subnet — Not used by OKE directly; reserved for bastion hosts, monitoring agents, and VPN/FastConnect endpoints.

Security strategy — two complementary layers:

  1. Security lists (subnet-level): enforce coarse-grained, subnet-to-subnet routing policy. OkeCluster adds its rules directly to the VCN's shared security lists via Vcn.add_security_list_rules, consuming only 1 list per subnet and leaving 4 slots free for additional services.

  2. Network Security Groups (VNIC-level): enforce fine-grained, component-to-component rules. Four NSGs are created and assigned to OKE resources:

  3. api_nsg → attached to the Kubernetes API endpoint.

  4. lb_nsg → intended for OCI Load Balancers created by Service type: LoadBalancer. Reference cluster.lb_nsg.id in the Kubernetes service annotation oci.oraclecloud.com/security-group-ids to activate it.
  5. worker_nsg → attached to all worker node VNICs.
  6. pod_nsg → attached to all pod VNICs (OCI CNI VNIC-native pods).

Because workers and pods carry different NSGs, the API endpoint can reach pods on arbitrary ports (webhooks) while the load balancer is restricted to NodePort and kube-proxy health-check ports on workers only — even though both share the same private subnet CIDR.

Security list rules added by this spell:

Public subnet (API endpoint + Load Balancer):

  • Ingress: Kubernetes API (6443) and control-plane port (12250) from private.
  • Ingress: HTTPS (443) and HTTP (80) from internet (Load Balancer).
  • Ingress: Kubernetes API (6443) from internet (kubectl).
  • Egress: OCI services (cluster management and telemetry).
  • Egress: Kubelet (10250), NodePort (30000-32767), kube-proxy (10256) to private.
  • Egress: All traffic to private subnet (webhooks, admission controllers).

Private subnet (Worker nodes + Pods):

  • Ingress: Kubelet (10250), NodePort (30000-32767), kube-proxy (10256) from public.
  • Ingress: All traffic from public subnet (control plane to pods: webhooks).
  • Egress: OCI services (OCIR image pulls, monitoring, logging).
  • Egress: Kubernetes API (6443) and control-plane port (12250) to public subnet.
  • Egress: HTTPS (443) and HTTP (80) to internet (image pulls + pod external API calls).

NodePoolConfig dataclass

Configuration for a single OKE node pool.

Pass a list of NodePoolConfig instances to OkeCluster(node_pools=[...]) to create one or more node pools on the same cluster. Each entry produces one oci.containerengine.NodePool placed in the private subnet and spread across all availability domains.

Attributes:

Name Type Description
name str

Short identifier for this pool (e.g. "system", "app"). Used as the Pulumi resource name suffix and OCI display name component. Must be unique within the list.

shape Input[str]

Compute shape for worker node VMs (e.g. "VM.Standard.E4.Flex").

image Input[str]

Boot image OCID for worker nodes.

node_count int

Number of worker nodes. Spread evenly across all availability domains in the region.

ocpus Input[float]

Number of OCPUs per worker node.

memory_in_gbs Input[float]

RAM in GiB per worker node.

ssh_public_key Input[str] | None

Optional SSH public key installed on worker nodes. Enables direct SSH access for debugging. Defaults to None.

boot_volume_size_in_gbs int | None

Boot volume size in GiB for each worker node. When None (default) OCI uses the minimum size defined by the image. Must be at least 50 GiB when specified.

initial_node_labels dict[str, str] | None

Kubernetes labels applied to every node at join time (e.g. {"role": "app"}). Used by node selectors and affinity rules. Defaults to None.

node_metadata dict[str, str] | None

OCI instance metadata key/value pairs propagated to every worker node. Pass {"user_data": "<base64>"} to inject a cloud-init script. Defaults to None.

defined_tags dict[str, Any] | None

OCI defined tags applied to the node pool resource (e.g. {"Operations": {"CostCenter": "42"}}). Defaults to None.

eviction_grace_duration str | None

ISO 8601 duration OCI waits for workloads to drain before terminating a node (e.g. "PT1H"). When None OCI uses its built-in default.

force_delete_after_grace bool

When True, OCI force-deletes the node even if workloads remain after eviction_grace_duration. Defaults to False.

cycling_enabled bool

Enable rolling node replacement on pool updates. When True, OCI replaces nodes in batches controlled by cycling_max_surge and cycling_max_unavailable. Defaults to False.

cycling_max_surge str | None

Maximum extra nodes provisioned during cycling (e.g. "1" or "10%"). Defaults to None (OCI default).

cycling_max_unavailable str | None

Maximum nodes unavailable during cycling (e.g. "0" or "10%"). Defaults to None (OCI default).

Example
node_pools = [
    NodePoolConfig(
        name="system",
        shape="VM.Standard.E4.Flex",
        image="ocid1.image.oc1...",
        node_count=3,
        ocpus=2,
        memory_in_gbs=16,
    ),
    NodePoolConfig(
        name="app",
        shape="VM.Standard.E4.Flex",
        image="ocid1.image.oc1...",
        node_count=5,
        ocpus=8,
        memory_in_gbs=64,
    ),
]
cluster = OkeCluster(name="k8s", node_pools=node_pools, ...)
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/kubernetes.py
 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
@dataclass
class NodePoolConfig:
    """Configuration for a single OKE node pool.

    Pass a list of `NodePoolConfig` instances to `OkeCluster(node_pools=[...])`
    to create one or more node pools on the same cluster.  Each entry produces
    one `oci.containerengine.NodePool` placed in the private subnet and spread
    across all availability domains.

    Attributes:
        name: Short identifier for this pool (e.g. `"system"`, `"app"`).
            Used as the Pulumi resource name suffix and OCI display name
            component.  Must be unique within the list.
        shape: Compute shape for worker node VMs
            (e.g. `"VM.Standard.E4.Flex"`).
        image: Boot image OCID for worker nodes.
        node_count: Number of worker nodes.  Spread evenly across all
            availability domains in the region.
        ocpus: Number of OCPUs per worker node.
        memory_in_gbs: RAM in GiB per worker node.
        ssh_public_key: Optional SSH public key installed on worker nodes.
            Enables direct SSH access for debugging.  Defaults to `None`.
        boot_volume_size_in_gbs: Boot volume size in GiB for each worker
            node.  When `None` (default) OCI uses the minimum size defined
            by the image.  Must be at least 50 GiB when specified.
        initial_node_labels: Kubernetes labels applied to every node at
            join time (e.g. `{"role": "app"}`).  Used by node selectors
            and affinity rules.  Defaults to `None`.
        node_metadata: OCI instance metadata key/value pairs propagated to
            every worker node.  Pass `{"user_data": "<base64>"}` to inject
            a cloud-init script.  Defaults to `None`.
        defined_tags: OCI defined tags applied to the node pool resource
            (e.g. `{"Operations": {"CostCenter": "42"}}`).  Defaults to
            `None`.
        eviction_grace_duration: ISO 8601 duration OCI waits for workloads
            to drain before terminating a node (e.g. `"PT1H"`).  When
            `None` OCI uses its built-in default.
        force_delete_after_grace: When `True`, OCI force-deletes the node
            even if workloads remain after `eviction_grace_duration`.
            Defaults to `False`.
        cycling_enabled: Enable rolling node replacement on pool updates.
            When `True`, OCI replaces nodes in batches controlled by
            `cycling_max_surge` and `cycling_max_unavailable`.  Defaults
            to `False`.
        cycling_max_surge: Maximum extra nodes provisioned during cycling
            (e.g. `"1"` or `"10%"`).  Defaults to `None` (OCI default).
        cycling_max_unavailable: Maximum nodes unavailable during cycling
            (e.g. `"0"` or `"10%"`).  Defaults to `None` (OCI default).

    Example:
        ```python
        node_pools = [
            NodePoolConfig(
                name="system",
                shape="VM.Standard.E4.Flex",
                image="ocid1.image.oc1...",
                node_count=3,
                ocpus=2,
                memory_in_gbs=16,
            ),
            NodePoolConfig(
                name="app",
                shape="VM.Standard.E4.Flex",
                image="ocid1.image.oc1...",
                node_count=5,
                ocpus=8,
                memory_in_gbs=64,
            ),
        ]
        cluster = OkeCluster(name="k8s", node_pools=node_pools, ...)
        ```
    """

    name: str
    shape: pulumi.Input[str]
    image: pulumi.Input[str]
    node_count: int
    ocpus: pulumi.Input[float]
    memory_in_gbs: pulumi.Input[float]
    ssh_public_key: pulumi.Input[str] | None = None
    boot_volume_size_in_gbs: int | None = None
    initial_node_labels: dict[str, str] | None = None
    node_metadata: dict[str, str] | None = None
    defined_tags: dict[str, Any] | None = None
    eviction_grace_duration: str | None = None
    force_delete_after_grace: bool = False
    cycling_enabled: bool = False
    cycling_max_surge: str | None = None
    cycling_max_unavailable: str | None = None

OkeCluster

Bases: BaseResource, AbstractKubernetes

Oracle Kubernetes Engine cluster with node pool, security configuration, and NSGs.

Deploys a BASIC_CLUSTER OKE cluster with OCI VCN-native pod networking (OCI_VCN_IP_NATIVE CNI) and a node pool spread across all availability domains in the region.

Workers and pods share the private subnet CIDR. Four NSGs provide VNIC-level segmentation:

  • api_nsg controls who may reach the Kubernetes API endpoint.
  • lb_nsg is intended for OCI Load Balancers (attach via service annotation oci.oraclecloud.com/security-group-ids).
  • worker_nsg is assigned to every worker node VNIC.
  • pod_nsg is assigned to every pod VNIC (OCI CNI VCN-native).

Attributes:

Name Type Description
vcn Vcn | VcnRef

The Vcn this cluster is deployed into.

kubernetes_version Input[str]

Kubernetes version string (e.g. "v1.30.1").

display_name str

Human-readable cluster display name.

api_nsg NetworkSecurityGroup

NSG attached to the Kubernetes API endpoint VNIC.

lb_nsg NetworkSecurityGroup

NSG for OCI Load Balancers; apply via service annotation.

worker_nsg NetworkSecurityGroup

NSG attached to every worker node VNIC.

pod_nsg NetworkSecurityGroup

NSG attached to every pod VNIC (OCI CNI).

oke_public_security_list Any

Alias for the VCN's public security list (populated with OKE rules after initialisation).

oke_private_security_list Any

Alias for the VCN's private security list (populated with OKE rules after initialisation).

cluster Cluster

The underlying oci.containerengine.Cluster resource.

node_pools list[NodePool]

List of oci.containerengine.NodePool resources, one per NodePoolConfig passed at construction time.

id Output[str]

pulumi.Output[str] of the cluster OCID.

Example
vcn = Vcn(name="lab", compartment_id=comp_id, stack_name="prod")

cluster = OkeCluster(
    name="k8s",
    compartment_id=comp_id,
    vcn=vcn,
    kubernetes_version="v1.30.1",
    display_name="prod-k8s",
    node_pools=[
        NodePoolConfig(
            name="default",
            shape="VM.Standard.E4.Flex",
            image="ocid1.image.oc1...",
            node_count=3,
            ocpus=2,
            memory_in_gbs=32,
        ),
    ],
)

# Attach lb_nsg to Load Balancer services via annotation:
# oci.oraclecloud.com/security-group-ids: "<cluster.lb_nsg.id>"
cluster.create_kubeconfig("/tmp/kubeconfig")
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/kubernetes.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
class OkeCluster(BaseResource, AbstractKubernetes):
    """Oracle Kubernetes Engine cluster with node pool, security configuration, and NSGs.

    Deploys a `BASIC_CLUSTER` OKE cluster with OCI VCN-native pod networking
    (`OCI_VCN_IP_NATIVE` CNI) and a node pool spread across all availability
    domains in the region.

    Workers and pods share the private subnet CIDR. Four NSGs provide
    VNIC-level segmentation:

    - `api_nsg` controls who may reach the Kubernetes API endpoint.
    - `lb_nsg` is intended for OCI Load Balancers (attach via service
      annotation `oci.oraclecloud.com/security-group-ids`).
    - `worker_nsg` is assigned to every worker node VNIC.
    - `pod_nsg` is assigned to every pod VNIC (OCI CNI VCN-native).

    Attributes:
        vcn: The `Vcn` this cluster is deployed into.
        kubernetes_version: Kubernetes version string (e.g. `"v1.30.1"`).
        display_name: Human-readable cluster display name.
        api_nsg: NSG attached to the Kubernetes API endpoint VNIC.
        lb_nsg: NSG for OCI Load Balancers; apply via service annotation.
        worker_nsg: NSG attached to every worker node VNIC.
        pod_nsg: NSG attached to every pod VNIC (OCI CNI).
        oke_public_security_list: Alias for the VCN's public security list
            (populated with OKE rules after initialisation).
        oke_private_security_list: Alias for the VCN's private security list
            (populated with OKE rules after initialisation).
        cluster: The underlying `oci.containerengine.Cluster` resource.
        node_pools: List of `oci.containerengine.NodePool` resources, one
            per `NodePoolConfig` passed at construction time.
        id: `pulumi.Output[str]` of the cluster OCID.

    Example:
        ```python
        vcn = Vcn(name="lab", compartment_id=comp_id, stack_name="prod")

        cluster = OkeCluster(
            name="k8s",
            compartment_id=comp_id,
            vcn=vcn,
            kubernetes_version="v1.30.1",
            display_name="prod-k8s",
            node_pools=[
                NodePoolConfig(
                    name="default",
                    shape="VM.Standard.E4.Flex",
                    image="ocid1.image.oc1...",
                    node_count=3,
                    ocpus=2,
                    memory_in_gbs=32,
                ),
            ],
        )

        # Attach lb_nsg to Load Balancer services via annotation:
        # oci.oraclecloud.com/security-group-ids: "<cluster.lb_nsg.id>"
        cluster.create_kubeconfig("/tmp/kubeconfig")
        ```
    """

    vcn: Vcn | VcnRef
    kubernetes_version: pulumi.Input[str]
    display_name: str
    api_nsg: oci.core.NetworkSecurityGroup
    lb_nsg: oci.core.NetworkSecurityGroup
    worker_nsg: oci.core.NetworkSecurityGroup
    pod_nsg: oci.core.NetworkSecurityGroup
    # Aliases pointing to the VCN security lists (Any to cover Vcn and VcnRef)
    oke_public_security_list: Any
    oke_private_security_list: Any
    cluster: oci.containerengine.Cluster
    node_pools: list[oci.containerengine.NodePool]
    id: pulumi.Output[str]

    def __init__(
        self,
        name: str,
        compartment_id: pulumi.Input[str],
        vcn: Vcn | VcnRef,
        kubernetes_version: pulumi.Input[str],
        display_name: pulumi.Input[str],
        node_pools: list[NodePoolConfig],
        stack_name: str | None = None,
        enhanced: bool = False,
        endpoint_subnet: oci.core.Subnet | None = None,
        defined_tags: dict[str, Any] | None = None,
        opts: pulumi.ResourceOptions | None = None,
    ) -> None:
        """Create a complete OKE cluster infrastructure.

        Adds all required OKE security rules to the VCN, finalises the network,
        creates four NSGs (api, lb, worker, pod) with NSG-to-NSG rules, and
        then creates the Kubernetes control plane and node pool.

        Args:
            name: Logical name for the cluster resource (e.g. `"k8s"`).
            compartment_id: OCID of the OCI compartment to deploy into.
            vcn: `Vcn` instance that provides the public and private subnets.
            kubernetes_version: Kubernetes version string
                (e.g. `"v1.32.1"`).
            display_name: Human-readable name used for the cluster OCI
                resource.
            node_pools: One or more `NodePoolConfig` descriptors.  Each
                entry creates a separate node pool on the cluster, enabling
                mixed shapes (e.g. a small system pool and a large app pool).
                At least one entry is required.
            stack_name: Pulumi stack name.  Defaults to
                `pulumi.get_stack()` when `None`.
            enhanced: When `True`, creates an `ENHANCED_CLUSTER` instead of
                the default `BASIC_CLUSTER`.  Enhanced clusters support OCI
                Workload Identity (pod-level OCI API auth without embedded
                credentials), cluster add-on lifecycle management, and OCI
                DevOps integration.  Defaults to `False`.
            endpoint_subnet: Subnet where the Kubernetes API endpoint VNIC
                is placed.  Defaults to `None`, which uses `vcn.public_subnet`
                and assigns a public IP (reachable from the internet on 6443).
                Pass `vcn.private_subnet` (or any other subnet) for a
                private-only endpoint reachable only from within the VCN or
                connected networks (FastConnect, VPN).
            defined_tags: OCI defined tags applied to the cluster resource
                (e.g. `{"Operations": {"CostCenter": "42"}}`).  Defaults
                to `None`.
            opts: Pulumi resource options forwarded to the component.
        """
        super().__init__("custom:oke:Cluster", name, compartment_id, stack_name, opts)

        self.display_name = str(display_name) if not isinstance(display_name, str) else display_name
        self.name = name
        self.vcn = vcn
        self.compartment_id = compartment_id
        self.kubernetes_version = kubernetes_version

        # Layer 1: subnet-level security list rules
        self._add_oke_security_lists_rules()
        self.vcn.finalize_network()

        # Aliases pointing to the VCN security lists (None when using VcnRef)
        self.oke_public_security_list = self.vcn.public_security_list  # type: ignore[assignment]
        self.oke_private_security_list = self.vcn.private_security_list  # type: ignore[assignment]

        assert self.vcn.public_subnet is not None, "VCN public subnet must exist after finalization"
        assert self.vcn.private_subnet is not None, "VCN private subnet must exist after finalization"

        # Layer 2: VNIC-level NSGs — must be created before cluster/node pool
        self._create_oke_nsgs()

        child_opts = pulumi.ResourceOptions(parent=self)

        self.cluster = oci.containerengine.Cluster(
            "Cluster",
            compartment_id=self.compartment_id,
            name=f"Cluster-{self.display_name}",
            kubernetes_version=self.kubernetes_version,
            options=oci.containerengine.ClusterOptionsArgs(
                service_lb_subnet_ids=[self.vcn.public_subnet.id],
                kubernetes_network_config=oci.containerengine.ClusterOptionsKubernetesNetworkConfigArgs(
                    pods_cidr="172.16.0.0/16",
                    services_cidr="172.17.0.0/16",
                ),
            ),
            cluster_pod_network_options=[
                oci.containerengine.ClusterClusterPodNetworkOptionArgs(
                    cni_type="OCI_VCN_IP_NATIVE",
                )
            ],
            type="ENHANCED_CLUSTER" if enhanced else "BASIC_CLUSTER",
            vcn_id=self.vcn.id,
            endpoint_config=oci.containerengine.ClusterEndpointConfigArgs(
                subnet_id=(endpoint_subnet or self.vcn.public_subnet).id,  # type: ignore[union-attr]
                is_public_ip_enabled=endpoint_subnet is None,
                nsg_ids=[self.api_nsg.id],
            ),
            freeform_tags=self.create_freeform_tags(f"Cluster-{self.display_name}", "oke-cluster"),
            defined_tags=defined_tags,
            opts=child_opts,
        )

        self.id = self.cluster.id

        h: OciHelper = OciHelper()
        get_ad_names = oci.identity.get_availability_domains_output(compartment_id=self.compartment_id)
        ads = get_ad_names.availability_domains

        self.node_pools = []
        for cfg in node_pools:
            pool = oci.containerengine.NodePool(
                f"NodePool-{cfg.name}",
                name=f"NodePool-{cfg.name}-{self.display_name}",
                cluster_id=self.cluster.id,
                compartment_id=self.compartment_id,
                kubernetes_version=self.kubernetes_version,
                node_config_details=oci.containerengine.NodePoolNodeConfigDetailsArgs(
                    placement_configs=ads.apply(lambda ads_list: h.get_ads(ads_list, self.vcn.private_subnet.id)),  # type: ignore[arg-type, union-attr, return-value]
                    size=cfg.node_count,
                    nsg_ids=[self.worker_nsg.id],
                    node_pool_pod_network_option_details=oci.containerengine.NodePoolNodeConfigDetailsNodePoolPodNetworkOptionDetailsArgs(
                        cni_type="OCI_VCN_IP_NATIVE",
                        pod_subnet_ids=[self.vcn.private_subnet.id],  # type: ignore[union-attr]
                        pod_nsg_ids=[self.pod_nsg.id],
                    ),
                    defined_tags=cfg.defined_tags,
                ),
                node_shape=cfg.shape,
                node_shape_config=oci.containerengine.NodePoolNodeShapeConfigArgs(
                    memory_in_gbs=cfg.memory_in_gbs,
                    ocpus=cfg.ocpus,
                ),
                node_source_details=oci.containerengine.NodePoolNodeSourceDetailsArgs(
                    image_id=cfg.image,
                    source_type="IMAGE",
                    boot_volume_size_in_gbs=(
                        str(cfg.boot_volume_size_in_gbs) if cfg.boot_volume_size_in_gbs is not None else None
                    ),
                ),
                initial_node_labels=[
                    oci.containerengine.NodePoolInitialNodeLabelArgs(key=k, value=v)
                    for k, v in cfg.initial_node_labels.items()
                ]
                if cfg.initial_node_labels
                else None,
                node_metadata=cfg.node_metadata,
                node_eviction_node_pool_settings=oci.containerengine.NodePoolNodeEvictionNodePoolSettingsArgs(
                    eviction_grace_duration=cfg.eviction_grace_duration,
                    is_force_delete_after_grace_duration=cfg.force_delete_after_grace,
                )
                if cfg.eviction_grace_duration is not None or cfg.force_delete_after_grace
                else None,
                node_pool_cycling_details=oci.containerengine.NodePoolNodePoolCyclingDetailsArgs(
                    is_node_cycling_enabled=cfg.cycling_enabled,
                    maximum_surge=cfg.cycling_max_surge,
                    maximum_unavailable=cfg.cycling_max_unavailable,
                )
                if cfg.cycling_enabled
                else None,
                ssh_public_key=cfg.ssh_public_key or None,
                freeform_tags=self.create_freeform_tags(f"NodePool-{cfg.name}", "oke-node-pool"),
                defined_tags=cfg.defined_tags,
                opts=child_opts,
            )
            self.node_pools.append(pool)

        self.register_outputs({})

    # ------------------------------------------------------------------
    # Private: security list rules (subnet-level, Layer 1)
    # ------------------------------------------------------------------

    def _add_oke_security_lists_rules(self) -> None:
        """Add all OKE-required security rules to the VCN security lists.

        Calls `Vcn.add_security_list_rules` once with the complete set of
        ingress and egress rules for the public (API endpoint + Load Balancer)
        and private (worker nodes + pods) subnets.

        Must be called before `Vcn.finalize_network`.

        Rules added:

        Public subnet ingress: Kubernetes API (6443) and control-plane port
        (12250) from private subnet (workers + pods); HTTPS (443) and HTTP (80)
        from internet (Load Balancer); Kubernetes API (6443) from internet
        (kubectl).

        Public subnet egress: OCI services (telemetry, management); kubelet
        (10250), NodePort (30000-32767), and kube-proxy (10256) to private;
        all traffic to private (webhooks, admission controllers).

        Private subnet ingress: kubelet (10250), NodePort (30000-32767), and
        kube-proxy (10256) from public; all traffic from public (control plane
        to pods for webhooks).

        Private subnet egress: OCI services (OCIR, monitoring, logging);
        Kubernetes API (6443) and control-plane port (12250) to public;
        HTTPS (443) and HTTP (80) to internet (image pulls and pod external
        API calls).
        """
        # ═══════════════════════════════════════════════════════════════
        # PUBLIC SUBNET – API Endpoint + Load Balancer
        # ═══════════════════════════════════════════════════════════════

        private_subnet_cidr: pulumi.Input[str] = self.vcn.get_private_subnet_cidr()
        public_subnet_cidr: pulumi.Input[str] = self.vcn.get_public_subnet_cidr()
        svc_cidr: pulumi.Output[str] = SVC_CIDR

        # ───────────────────────────────────────────────────────────────
        # PUBLIC – INGRESS
        # ───────────────────────────────────────────────────────────────
        public_ingress_rules: list[oci.core.SecurityListIngressSecurityRuleArgs] = [
            # Workers + pods → API server
            oci.core.SecurityListIngressSecurityRuleArgs(
                description="Workers and pods communicate with Kubernetes API server for cluster operations and service discovery",  # noqa: E501
                protocol="6",  # TCP
                source=private_subnet_cidr,
                source_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListIngressSecurityRuleTcpOptionsArgs(
                    min=6443,
                    max=6443,
                ),
            ),
            # Workers + pods → control plane internal port
            oci.core.SecurityListIngressSecurityRuleArgs(
                description="Workers and pods communicate with Kubernetes control plane for internal cluster operations",  # noqa: E501
                protocol="6",  # TCP
                source=private_subnet_cidr,
                source_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListIngressSecurityRuleTcpOptionsArgs(
                    min=12250,
                    max=12250,
                ),
            ),
            # External clients (kubectl) → API server
            oci.core.SecurityListIngressSecurityRuleArgs(
                description="Allow external access to Kubernetes API for kubectl and cluster management tools",
                protocol="6",  # TCP
                source="0.0.0.0/0",
                source_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListIngressSecurityRuleTcpOptionsArgs(
                    min=6443,
                    max=6443,
                ),
            ),
            # Internet → Load Balancer HTTPS
            oci.core.SecurityListIngressSecurityRuleArgs(
                description="Load Balancer receives HTTPS traffic from internet for public web applications and APIs",
                protocol="6",  # TCP
                source="0.0.0.0/0",
                source_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListIngressSecurityRuleTcpOptionsArgs(
                    min=443,
                    max=443,
                ),
            ),
            # Internet → Load Balancer HTTP
            oci.core.SecurityListIngressSecurityRuleArgs(
                description="Load Balancer receives HTTP traffic from internet for public applications (consider HTTPS redirect)",  # noqa: E501
                protocol="6",  # TCP
                source="0.0.0.0/0",
                source_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListIngressSecurityRuleTcpOptionsArgs(
                    min=80,
                    max=80,
                ),
            ),
        ]

        # ───────────────────────────────────────────────────────────────
        # PUBLIC – EGRESS
        # ───────────────────────────────────────────────────────────────
        public_egress_rules: list[oci.core.SecurityListEgressSecurityRuleArgs] = [
            # Control plane → OCI services (telemetry, management)
            oci.core.SecurityListEgressSecurityRuleArgs(
                description="Control plane communicates with OCI services for cluster management and telemetry",
                protocol="6",  # TCP
                destination=svc_cidr,
                destination_type="SERVICE_CIDR_BLOCK",
            ),
            # Control plane → kubelet API on worker nodes
            oci.core.SecurityListEgressSecurityRuleArgs(
                description="Control plane manages worker nodes via kubelet for pod operations and health monitoring",
                protocol="6",  # TCP
                destination=private_subnet_cidr,
                destination_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListEgressSecurityRuleTcpOptionsArgs(
                    min=10250,
                    max=10250,
                ),
            ),
            # LB → NodePort range on worker nodes
            oci.core.SecurityListEgressSecurityRuleArgs(
                description="Load Balancer forwards traffic to worker nodes via NodePort for Kubernetes service routing",  # noqa: E501
                protocol="6",  # TCP
                destination=private_subnet_cidr,
                destination_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListEgressSecurityRuleTcpOptionsArgs(
                    min=30000,
                    max=32767,
                ),
            ),
            # LB → kube-proxy health check
            oci.core.SecurityListEgressSecurityRuleArgs(
                description="Load Balancer checks worker node health via kube-proxy to ensure traffic routing availability",  # noqa: E501
                protocol="6",  # TCP
                destination=private_subnet_cidr,
                destination_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListEgressSecurityRuleTcpOptionsArgs(
                    min=10256,
                    max=10256,
                ),
            ),
            # Control plane → pods (webhooks, admission controllers, metrics)
            # Admission controller webhook ports are arbitrary; allow all protocols.
            oci.core.SecurityListEgressSecurityRuleArgs(
                description="Control plane reaches pods on arbitrary ports for webhooks, admission controllers, and metrics",  # noqa: E501
                protocol="all",
                destination=private_subnet_cidr,
                destination_type="CIDR_BLOCK",
            ),
        ]

        # ═══════════════════════════════════════════════════════════════
        # PRIVATE SUBNET – Worker Nodes + Pods
        # ═══════════════════════════════════════════════════════════════

        # ───────────────────────────────────────────────────────────────
        # PRIVATE – INGRESS
        # ───────────────────────────────────────────────────────────────
        private_ingress_rules: list[oci.core.SecurityListIngressSecurityRuleArgs] = [
            # Control plane → kubelet API
            oci.core.SecurityListIngressSecurityRuleArgs(
                description="Control plane manages pods on worker nodes via kubelet for commands, logs, and health monitoring",  # noqa: E501
                protocol="6",  # TCP
                source=public_subnet_cidr,
                source_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListIngressSecurityRuleTcpOptionsArgs(
                    min=10250,
                    max=10250,
                ),
            ),
            # LB → NodePort range
            oci.core.SecurityListIngressSecurityRuleArgs(
                description="Load Balancer forwards traffic to worker nodes via NodePort to reach Kubernetes services",
                protocol="6",  # TCP
                source=public_subnet_cidr,
                source_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListIngressSecurityRuleTcpOptionsArgs(
                    min=30000,
                    max=32767,
                ),
            ),
            # LB → kube-proxy health check
            oci.core.SecurityListIngressSecurityRuleArgs(
                description="Load Balancer verifies worker node health via kube-proxy endpoint before routing traffic",
                protocol="6",  # TCP
                source=public_subnet_cidr,
                source_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListIngressSecurityRuleTcpOptionsArgs(
                    min=10256,
                    max=10256,
                ),
            ),
            # Control plane → pods (webhooks, admission controllers)
            # Ports are arbitrary per admission controller; allow all from public.
            oci.core.SecurityListIngressSecurityRuleArgs(
                description="Control plane reaches pods on arbitrary ports for webhooks and admission controllers",
                protocol="all",
                source=public_subnet_cidr,
                source_type="CIDR_BLOCK",
            ),
        ]

        # ───────────────────────────────────────────────────────────────
        # PRIVATE – EGRESS
        # ───────────────────────────────────────────────────────────────
        private_egress_rules: list[oci.core.SecurityListEgressSecurityRuleArgs] = [
            # Workers + pods → OCI services (OCIR, monitoring, logging)
            oci.core.SecurityListEgressSecurityRuleArgs(
                description="Workers and pods communicate with OCI services for container images, logging, and monitoring",  # noqa: E501
                protocol="6",  # TCP
                destination=svc_cidr,
                destination_type="SERVICE_CIDR_BLOCK",
            ),
            # Workers + pods → Kubernetes API server
            oci.core.SecurityListEgressSecurityRuleArgs(
                description="Workers and pods communicate with Kubernetes API to register, report status, and access resources",  # noqa: E501
                protocol="6",  # TCP
                destination=public_subnet_cidr,
                destination_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListEgressSecurityRuleTcpOptionsArgs(
                    min=6443,
                    max=6443,
                ),
            ),
            # Workers + pods → control plane internal port
            oci.core.SecurityListEgressSecurityRuleArgs(
                description="Workers and pods communicate with control plane for internal cluster operations",
                protocol="6",  # TCP
                destination=public_subnet_cidr,
                destination_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListEgressSecurityRuleTcpOptionsArgs(
                    min=12250,
                    max=12250,
                ),
            ),
            # Workers + pods → internet via HTTPS (image pulls, external APIs)
            oci.core.SecurityListEgressSecurityRuleArgs(
                description="Workers pull container images and pods call external APIs via HTTPS",
                protocol="6",  # TCP
                destination="0.0.0.0/0",
                destination_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListEgressSecurityRuleTcpOptionsArgs(
                    min=443,
                    max=443,
                ),
            ),
            # Workers + pods → internet via HTTP (some registries, OCI pre-auth URLs)
            oci.core.SecurityListEgressSecurityRuleArgs(
                description="Workers pull container images from HTTP registries and access OCI pre-authenticated URLs",
                protocol="6",  # TCP
                destination="0.0.0.0/0",
                destination_type="CIDR_BLOCK",
                tcp_options=oci.core.SecurityListEgressSecurityRuleTcpOptionsArgs(
                    min=80,
                    max=80,
                ),
            ),
        ]

        # Add all collected rules to the VCN security lists in a single call
        self.vcn.add_security_list_rules(
            public_ingress=public_ingress_rules,
            public_egress=public_egress_rules,
            private_ingress=private_ingress_rules,
            private_egress=private_egress_rules,
        )

    # ------------------------------------------------------------------
    # Private: NSG creation and rules (VNIC-level, Layer 2)
    # ------------------------------------------------------------------

    def _create_oke_nsgs(self) -> None:
        """Create the four OKE NSGs and wire all NSG-to-NSG rules.

        Creates `api_nsg`, `lb_nsg`, `worker_nsg`, and `pod_nsg` as child
        resources of this component, then adds all necessary stateful ingress
        and egress rules using NSG OCIDs as source/destination so that
        workers and pods — which share the same private subnet CIDR — are
        independently reachable only by the components that are authorised
        to reach them.

        Must be called after `Vcn.finalize_network` and before cluster/node
        pool creation so that NSG IDs are available for `endpoint_config.nsg_ids`
        and `node_config_details.nsg_ids`.
        """
        opts = pulumi.ResourceOptions(parent=self)

        # ── Create the four NSG objects ────────────────────────────────
        self.api_nsg = oci.core.NetworkSecurityGroup(
            "OkeApiNsg",
            compartment_id=self.compartment_id,
            vcn_id=self.vcn.id,
            display_name=f"{self.display_name}-api-nsg",
            opts=opts,
        )
        self.lb_nsg = oci.core.NetworkSecurityGroup(
            "OkeLbNsg",
            compartment_id=self.compartment_id,
            vcn_id=self.vcn.id,
            display_name=f"{self.display_name}-lb-nsg",
            opts=opts,
        )
        self.worker_nsg = oci.core.NetworkSecurityGroup(
            "OkeWorkerNsg",
            compartment_id=self.compartment_id,
            vcn_id=self.vcn.id,
            display_name=f"{self.display_name}-worker-nsg",
            opts=opts,
        )
        self.pod_nsg = oci.core.NetworkSecurityGroup(
            "OkePodNsg",
            compartment_id=self.compartment_id,
            vcn_id=self.vcn.id,
            display_name=f"{self.display_name}-pod-nsg",
            opts=opts,
        )

        # ── Wire rules — all four NSGs must exist before any rules ────
        self._add_api_nsg_rules(opts)
        self._add_lb_nsg_rules(opts)
        self._add_worker_nsg_rules(opts)
        self._add_pod_nsg_rules(opts)

    def _r(
        self,
        name: str,
        nsg_id: pulumi.Input[str],
        *,
        direction: str,
        protocol: str,
        source: pulumi.Input[str] | None = None,
        source_type: str | None = None,
        destination: pulumi.Input[str] | None = None,
        destination_type: str | None = None,
        tcp_options: oci.core.NetworkSecurityGroupSecurityRuleTcpOptionsArgs | None = None,
        icmp_options: oci.core.NetworkSecurityGroupSecurityRuleIcmpOptionsArgs | None = None,
        description: str = "",
        opts: pulumi.ResourceOptions | None = None,
    ) -> oci.core.NetworkSecurityGroupSecurityRule:
        """Create a single stateful NSG security rule.

        Private shorthand used by `_add_*_nsg_rules` helpers to reduce
        boilerplate.  `name` must be unique within this `OkeCluster` component.

        Args:
            name: Pulumi resource name, unique within this component.
            nsg_id: OCID of the NSG that owns this rule.
            direction: `"INGRESS"` or `"EGRESS"`.
            protocol: OCI protocol string — `TCP`, `ICMP`, or `ALL`.
            source: Source CIDR or NSG OCID (ingress rules).
            source_type: `"CIDR_BLOCK"` or `"NETWORK_SECURITY_GROUP"`.
            destination: Destination CIDR or NSG OCID (egress rules).
            destination_type: `"CIDR_BLOCK"`, `"NETWORK_SECURITY_GROUP"`,
                or `"SERVICE_CIDR_BLOCK"`.
            tcp_options: TCP port restriction — build with `tcp_port` or
                `tcp_port_range`.
            icmp_options: ICMP type/code — build with `icmp_opts`.
            description: Human-readable description shown in the OCI Console.
            opts: Pulumi resource options forwarded to the rule resource.

        Returns:
            The created `oci.core.NetworkSecurityGroupSecurityRule` resource.
        """
        return oci.core.NetworkSecurityGroupSecurityRule(
            name,
            network_security_group_id=nsg_id,
            direction=direction,
            protocol=protocol,
            source=source,
            source_type=source_type,
            destination=destination,
            destination_type=destination_type,
            tcp_options=tcp_options,
            icmp_options=icmp_options,
            stateless=False,
            description=description or name,
            opts=opts,
        )

    def _add_api_nsg_rules(self, opts: pulumi.ResourceOptions) -> None:
        """Add ingress and egress rules to `api_nsg`.

        Ingress: workers and pods reach the API server (6443) and internal
        control-plane port (12250); external clients (kubectl) reach the API
        on 6443.

        Egress: control plane reaches OCI services (telemetry), kubelet on
        workers (10250), and all ports on pods (webhooks, exec, metrics).

        Args:
            opts: Pulumi resource options applied to every rule resource.
        """
        nsg = self.api_nsg.id

        # ── INGRESS ────────────────────────────────────────────────────
        self._r(
            "OkeApiNsgIngress-worker-6443",
            nsg,
            direction="INGRESS",
            protocol=TCP,
            source=self.worker_nsg.id,
            source_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(6443),
            description="Worker nodes reach Kubernetes API server",
            opts=opts,
        )
        self._r(
            "OkeApiNsgIngress-worker-12250",
            nsg,
            direction="INGRESS",
            protocol=TCP,
            source=self.worker_nsg.id,
            source_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(12250),
            description="Worker nodes reach Kubernetes control-plane internal port",
            opts=opts,
        )
        self._r(
            "OkeApiNsgIngress-pod-6443",
            nsg,
            direction="INGRESS",
            protocol=TCP,
            source=self.pod_nsg.id,
            source_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(6443),
            description="Pods reach Kubernetes API server for service discovery and RBAC",
            opts=opts,
        )
        self._r(
            "OkeApiNsgIngress-pod-12250",
            nsg,
            direction="INGRESS",
            protocol=TCP,
            source=self.pod_nsg.id,
            source_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(12250),
            description="Pods reach Kubernetes control-plane internal port",
            opts=opts,
        )
        self._r(
            "OkeApiNsgIngress-kubectl",
            nsg,
            direction="INGRESS",
            protocol=TCP,
            source=INTERNET,
            source_type="CIDR_BLOCK",
            tcp_options=tcp_port(6443),
            description="External kubectl and CI tooling reach the Kubernetes API",
            opts=opts,
        )

        # ── EGRESS ─────────────────────────────────────────────────────
        self._r(
            "OkeApiNsgEgress-services",
            nsg,
            direction="EGRESS",
            protocol=ALL,
            destination=SVC_CIDR,
            destination_type="SERVICE_CIDR_BLOCK",
            description="Control plane sends telemetry and management traffic to OCI services",
            opts=opts,
        )
        self._r(
            "OkeApiNsgEgress-worker-kubelet",
            nsg,
            direction="EGRESS",
            protocol=TCP,
            destination=self.worker_nsg.id,
            destination_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(10250),
            description="Control plane calls kubelet on worker nodes for pod lifecycle operations",
            opts=opts,
        )
        self._r(
            "OkeApiNsgEgress-pod-all",
            nsg,
            direction="EGRESS",
            protocol=ALL,
            destination=self.pod_nsg.id,
            destination_type="NETWORK_SECURITY_GROUP",
            description="Control plane reaches pods on arbitrary ports for webhooks, exec, and metrics",
            opts=opts,
        )

    def _add_lb_nsg_rules(self, opts: pulumi.ResourceOptions) -> None:
        """Add ingress and egress rules to `lb_nsg`.

        Ingress: internet reaches the load balancer on HTTPS (443) and HTTP (80).

        Egress: load balancer forwards traffic to worker nodes on the NodePort
        range (30000-32767) and queries kube-proxy health (10256).

        Args:
            opts: Pulumi resource options applied to every rule resource.
        """
        nsg = self.lb_nsg.id

        # ── INGRESS ────────────────────────────────────────────────────
        self._r(
            "OkeLbNsgIngress-https",
            nsg,
            direction="INGRESS",
            protocol=TCP,
            source=INTERNET,
            source_type="CIDR_BLOCK",
            tcp_options=tcp_port(443),
            description="Internet reaches the load balancer on HTTPS",
            opts=opts,
        )
        self._r(
            "OkeLbNsgIngress-http",
            nsg,
            direction="INGRESS",
            protocol=TCP,
            source=INTERNET,
            source_type="CIDR_BLOCK",
            tcp_options=tcp_port(80),
            description="Internet reaches the load balancer on HTTP",
            opts=opts,
        )

        # ── EGRESS ─────────────────────────────────────────────────────
        self._r(
            "OkeLbNsgEgress-nodeport",
            nsg,
            direction="EGRESS",
            protocol=TCP,
            destination=self.worker_nsg.id,
            destination_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port_range(30000, 32767),
            description="Load balancer forwards requests to worker nodes via NodePort",
            opts=opts,
        )
        self._r(
            "OkeLbNsgEgress-kubeproxy",
            nsg,
            direction="EGRESS",
            protocol=TCP,
            destination=self.worker_nsg.id,
            destination_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(10256),
            description="Load balancer queries kube-proxy health check before routing",
            opts=opts,
        )

    def _add_worker_nsg_rules(self, opts: pulumi.ResourceOptions) -> None:
        """Add ingress and egress rules to `worker_nsg`.

        Ingress: API endpoint reaches kubelet (10250); load balancer reaches
        NodePort range and kube-proxy health; pods reach workers (OCI CNI VNIC
        communication); nodes reach each other (pod traffic across nodes).

        Egress: workers reach the API server (6443, 12250); OCI services (OCIR,
        monitoring); pods (OCI CNI); other workers (node-to-node); internet on
        HTTPS (443) and HTTP (80) for image pulls.

        Args:
            opts: Pulumi resource options applied to every rule resource.
        """
        nsg = self.worker_nsg.id

        # ── INGRESS ────────────────────────────────────────────────────
        self._r(
            "OkeWorkerNsgIngress-api-kubelet",
            nsg,
            direction="INGRESS",
            protocol=TCP,
            source=self.api_nsg.id,
            source_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(10250),
            description="Control plane calls kubelet for pod lifecycle, logs, and exec",
            opts=opts,
        )
        self._r(
            "OkeWorkerNsgIngress-lb-nodeport",
            nsg,
            direction="INGRESS",
            protocol=TCP,
            source=self.lb_nsg.id,
            source_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port_range(30000, 32767),
            description="Load balancer forwards requests to workers via NodePort",
            opts=opts,
        )
        self._r(
            "OkeWorkerNsgIngress-lb-kubeproxy",
            nsg,
            direction="INGRESS",
            protocol=TCP,
            source=self.lb_nsg.id,
            source_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(10256),
            description="Load balancer health-checks worker via kube-proxy",
            opts=opts,
        )
        self._r(
            "OkeWorkerNsgIngress-pod-all",
            nsg,
            direction="INGRESS",
            protocol=ALL,
            source=self.pod_nsg.id,
            source_type="NETWORK_SECURITY_GROUP",
            description="Pods communicate with worker VNIC for OCI CNI VNIC-native networking",
            opts=opts,
        )
        self._r(
            "OkeWorkerNsgIngress-worker-all",
            nsg,
            direction="INGRESS",
            protocol=ALL,
            source=self.worker_nsg.id,
            source_type="NETWORK_SECURITY_GROUP",
            description="Node-to-node traffic for OCI CNI pod communication across availability domains",
            opts=opts,
        )
        # ── EGRESS ─────────────────────────────────────────────────────
        self._r(
            "OkeWorkerNsgEgress-api-6443",
            nsg,
            direction="EGRESS",
            protocol=TCP,
            destination=self.api_nsg.id,
            destination_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(6443),
            description="Workers register with and query the Kubernetes API server",
            opts=opts,
        )
        self._r(
            "OkeWorkerNsgEgress-api-12250",
            nsg,
            direction="EGRESS",
            protocol=TCP,
            destination=self.api_nsg.id,
            destination_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(12250),
            description="Workers communicate with control plane on internal port",
            opts=opts,
        )
        self._r(
            "OkeWorkerNsgEgress-services",
            nsg,
            direction="EGRESS",
            protocol=ALL,
            destination=SVC_CIDR,
            destination_type="SERVICE_CIDR_BLOCK",
            description="Workers pull images from OCIR and send metrics and logs to OCI services",
            opts=opts,
        )
        self._r(
            "OkeWorkerNsgEgress-pod-all",
            nsg,
            direction="EGRESS",
            protocol=ALL,
            destination=self.pod_nsg.id,
            destination_type="NETWORK_SECURITY_GROUP",
            description="Workers reach pod VNICs for OCI CNI VNIC-native networking",
            opts=opts,
        )
        self._r(
            "OkeWorkerNsgEgress-worker-all",
            nsg,
            direction="EGRESS",
            protocol=ALL,
            destination=self.worker_nsg.id,
            destination_type="NETWORK_SECURITY_GROUP",
            description="Node-to-node traffic for OCI CNI pod communication across availability domains",
            opts=opts,
        )
        self._r(
            "OkeWorkerNsgEgress-inet-443",
            nsg,
            direction="EGRESS",
            protocol=TCP,
            destination=INTERNET,
            destination_type="CIDR_BLOCK",
            tcp_options=tcp_port(443),
            description="Workers pull container images and call external APIs via HTTPS",
            opts=opts,
        )
        self._r(
            "OkeWorkerNsgEgress-inet-80",
            nsg,
            direction="EGRESS",
            protocol=TCP,
            destination=INTERNET,
            destination_type="CIDR_BLOCK",
            tcp_options=tcp_port(80),
            description="Workers pull images from HTTP registries and access OCI pre-authenticated URLs",
            opts=opts,
        )

    def _add_pod_nsg_rules(self, opts: pulumi.ResourceOptions) -> None:
        """Add ingress and egress rules to `pod_nsg`.

        Ingress: API endpoint reaches pods on all ports (webhooks, exec,
        metrics); workers reach pod VNICs (OCI CNI); pods reach each other
        (pod-to-pod).

        Egress: pods reach each other; pods reach worker VNICs (OCI CNI);
        pods reach the API server (6443, 12250); OCI services (OCIR,
        monitoring); internet on HTTPS (443) and HTTP (80).

        Args:
            opts: Pulumi resource options applied to every rule resource.
        """
        nsg = self.pod_nsg.id

        # ── INGRESS ────────────────────────────────────────────────────
        self._r(
            "OkePodNsgIngress-api-all",
            nsg,
            direction="INGRESS",
            protocol=ALL,
            source=self.api_nsg.id,
            source_type="NETWORK_SECURITY_GROUP",
            description="Control plane reaches pods on arbitrary ports for webhooks, exec, and metrics scraping",
            opts=opts,
        )
        self._r(
            "OkePodNsgIngress-worker-all",
            nsg,
            direction="INGRESS",
            protocol=ALL,
            source=self.worker_nsg.id,
            source_type="NETWORK_SECURITY_GROUP",
            description="Worker nodes reach pod VNICs for OCI CNI VNIC-native networking",
            opts=opts,
        )
        self._r(
            "OkePodNsgIngress-pod-all",
            nsg,
            direction="INGRESS",
            protocol=ALL,
            source=self.pod_nsg.id,
            source_type="NETWORK_SECURITY_GROUP",
            description="Pod-to-pod communication (east-west traffic between workloads)",
            opts=opts,
        )

        # ── EGRESS ─────────────────────────────────────────────────────
        self._r(
            "OkePodNsgEgress-pod-all",
            nsg,
            direction="EGRESS",
            protocol=ALL,
            destination=self.pod_nsg.id,
            destination_type="NETWORK_SECURITY_GROUP",
            description="Pod-to-pod communication (east-west traffic between workloads)",
            opts=opts,
        )
        self._r(
            "OkePodNsgEgress-worker-all",
            nsg,
            direction="EGRESS",
            protocol=ALL,
            destination=self.worker_nsg.id,
            destination_type="NETWORK_SECURITY_GROUP",
            description="Pods reach worker VNICs for OCI CNI VNIC-native networking",
            opts=opts,
        )
        self._r(
            "OkePodNsgEgress-api-6443",
            nsg,
            direction="EGRESS",
            protocol=TCP,
            destination=self.api_nsg.id,
            destination_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(6443),
            description="Pods reach Kubernetes API server for service discovery and RBAC",
            opts=opts,
        )
        self._r(
            "OkePodNsgEgress-api-12250",
            nsg,
            direction="EGRESS",
            protocol=TCP,
            destination=self.api_nsg.id,
            destination_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(12250),
            description="Pods reach control-plane internal port",
            opts=opts,
        )
        self._r(
            "OkePodNsgEgress-services",
            nsg,
            direction="EGRESS",
            protocol=ALL,
            destination=SVC_CIDR,
            destination_type="SERVICE_CIDR_BLOCK",
            description="Pods reach OCI services for object storage, monitoring, and logging",
            opts=opts,
        )
        self._r(
            "OkePodNsgEgress-inet-443",
            nsg,
            direction="EGRESS",
            protocol=TCP,
            destination=INTERNET,
            destination_type="CIDR_BLOCK",
            tcp_options=tcp_port(443),
            description="Pods call external APIs and download dependencies via HTTPS",
            opts=opts,
        )
        self._r(
            "OkePodNsgEgress-inet-80",
            nsg,
            direction="EGRESS",
            protocol=TCP,
            destination=INTERNET,
            destination_type="CIDR_BLOCK",
            tcp_options=tcp_port(80),
            description="Pods access HTTP endpoints and OCI pre-authenticated URLs",
            opts=opts,
        )

    # ------------------------------------------------------------------
    # Public accessors
    # ------------------------------------------------------------------

    def export(self) -> None:
        """Export standard OKE cluster stack outputs.

        Publishes outputs derived from the spell's logical name:

        - `{name}_cluster_id` — OCID of the OKE cluster.
        - `{name}_kubernetes_version` — Kubernetes version deployed.
        - `{name}_lb_nsg_id` — OCID of the load-balancer NSG.  Reference this
          value in the Kubernetes service annotation
          `oci.oraclecloud.com/security-group-ids` so that OCI attaches the
          correct NSG to every managed load balancer.

        Example:
            ```python
            oke = OkeCluster(name="okeinfra", ...)
            oke.export()
            # Exports: okeinfra_cluster_id, okeinfra_kubernetes_version, okeinfra_lb_nsg_id
            ```
        """
        prefix = self.name.replace("-", "_")
        pulumi.export(f"{prefix}_cluster_id", self.id)
        pulumi.export(f"{prefix}_kubernetes_version", self.kubernetes_version)
        pulumi.export(f"{prefix}_lb_nsg_id", self.lb_nsg.id)

    def get_public_security_list_ids(self) -> list[pulumi.Output[str]]:
        """Return the ID of the public security list (populated with OKE rules).

        Returns:
            Single-element list containing the VCN public security list OCID
            as a `pulumi.Output[str]`, or an empty list when using `VcnRef`
            without a security list export.
        """
        sl = self.vcn.public_security_list
        return [sl.id] if sl is not None else []

    def get_private_security_list_ids(self) -> list[pulumi.Output[str]]:
        """Return the ID of the private security list (populated with OKE rules).

        Returns:
            Single-element list containing the VCN private security list OCID
            as a `pulumi.Output[str]`, or an empty list when using `VcnRef`
            without a security list export.
        """
        sl = self.vcn.private_security_list
        return [sl.id] if sl is not None else []

    def create_kubeconfig(self, filename: str) -> None:
        """Write a kubeconfig file for this OKE cluster.

        Fetches the cluster's kubeconfig content from the OCI API and writes
        it to `filename`.  The file is created or overwritten if it already
        exists.

        Args:
            filename: Absolute or relative path where the kubeconfig file
                should be written (e.g. `"/tmp/kubeconfig"`).
        """
        cluster_kube_config = self.cluster.id.apply(
            lambda cid: oci.containerengine.get_cluster_kube_config(cluster_id=cid)
        )

        def _write(cc: str) -> None:
            with open(filename, "w") as f:
                f.write(cc)

        cluster_kube_config.content.apply(_write)  # type: ignore[union-attr]

__init__(name: str, compartment_id: pulumi.Input[str], vcn: Vcn | VcnRef, kubernetes_version: pulumi.Input[str], display_name: pulumi.Input[str], node_pools: list[NodePoolConfig], stack_name: str | None = None, enhanced: bool = False, endpoint_subnet: oci.core.Subnet | None = None, defined_tags: dict[str, Any] | None = None, opts: pulumi.ResourceOptions | None = None) -> None

Create a complete OKE cluster infrastructure.

Adds all required OKE security rules to the VCN, finalises the network, creates four NSGs (api, lb, worker, pod) with NSG-to-NSG rules, and then creates the Kubernetes control plane and node pool.

Parameters:

Name Type Description Default
name str

Logical name for the cluster resource (e.g. "k8s").

required
compartment_id Input[str]

OCID of the OCI compartment to deploy into.

required
vcn Vcn | VcnRef

Vcn instance that provides the public and private subnets.

required
kubernetes_version Input[str]

Kubernetes version string (e.g. "v1.32.1").

required
display_name Input[str]

Human-readable name used for the cluster OCI resource.

required
node_pools list[NodePoolConfig]

One or more NodePoolConfig descriptors. Each entry creates a separate node pool on the cluster, enabling mixed shapes (e.g. a small system pool and a large app pool). At least one entry is required.

required
stack_name str | None

Pulumi stack name. Defaults to pulumi.get_stack() when None.

None
enhanced bool

When True, creates an ENHANCED_CLUSTER instead of the default BASIC_CLUSTER. Enhanced clusters support OCI Workload Identity (pod-level OCI API auth without embedded credentials), cluster add-on lifecycle management, and OCI DevOps integration. Defaults to False.

False
endpoint_subnet Subnet | None

Subnet where the Kubernetes API endpoint VNIC is placed. Defaults to None, which uses vcn.public_subnet and assigns a public IP (reachable from the internet on 6443). Pass vcn.private_subnet (or any other subnet) for a private-only endpoint reachable only from within the VCN or connected networks (FastConnect, VPN).

None
defined_tags dict[str, Any] | None

OCI defined tags applied to the cluster resource (e.g. {"Operations": {"CostCenter": "42"}}). Defaults to None.

None
opts ResourceOptions | None

Pulumi resource options forwarded to the component.

None
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/kubernetes.py
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
def __init__(
    self,
    name: str,
    compartment_id: pulumi.Input[str],
    vcn: Vcn | VcnRef,
    kubernetes_version: pulumi.Input[str],
    display_name: pulumi.Input[str],
    node_pools: list[NodePoolConfig],
    stack_name: str | None = None,
    enhanced: bool = False,
    endpoint_subnet: oci.core.Subnet | None = None,
    defined_tags: dict[str, Any] | None = None,
    opts: pulumi.ResourceOptions | None = None,
) -> None:
    """Create a complete OKE cluster infrastructure.

    Adds all required OKE security rules to the VCN, finalises the network,
    creates four NSGs (api, lb, worker, pod) with NSG-to-NSG rules, and
    then creates the Kubernetes control plane and node pool.

    Args:
        name: Logical name for the cluster resource (e.g. `"k8s"`).
        compartment_id: OCID of the OCI compartment to deploy into.
        vcn: `Vcn` instance that provides the public and private subnets.
        kubernetes_version: Kubernetes version string
            (e.g. `"v1.32.1"`).
        display_name: Human-readable name used for the cluster OCI
            resource.
        node_pools: One or more `NodePoolConfig` descriptors.  Each
            entry creates a separate node pool on the cluster, enabling
            mixed shapes (e.g. a small system pool and a large app pool).
            At least one entry is required.
        stack_name: Pulumi stack name.  Defaults to
            `pulumi.get_stack()` when `None`.
        enhanced: When `True`, creates an `ENHANCED_CLUSTER` instead of
            the default `BASIC_CLUSTER`.  Enhanced clusters support OCI
            Workload Identity (pod-level OCI API auth without embedded
            credentials), cluster add-on lifecycle management, and OCI
            DevOps integration.  Defaults to `False`.
        endpoint_subnet: Subnet where the Kubernetes API endpoint VNIC
            is placed.  Defaults to `None`, which uses `vcn.public_subnet`
            and assigns a public IP (reachable from the internet on 6443).
            Pass `vcn.private_subnet` (or any other subnet) for a
            private-only endpoint reachable only from within the VCN or
            connected networks (FastConnect, VPN).
        defined_tags: OCI defined tags applied to the cluster resource
            (e.g. `{"Operations": {"CostCenter": "42"}}`).  Defaults
            to `None`.
        opts: Pulumi resource options forwarded to the component.
    """
    super().__init__("custom:oke:Cluster", name, compartment_id, stack_name, opts)

    self.display_name = str(display_name) if not isinstance(display_name, str) else display_name
    self.name = name
    self.vcn = vcn
    self.compartment_id = compartment_id
    self.kubernetes_version = kubernetes_version

    # Layer 1: subnet-level security list rules
    self._add_oke_security_lists_rules()
    self.vcn.finalize_network()

    # Aliases pointing to the VCN security lists (None when using VcnRef)
    self.oke_public_security_list = self.vcn.public_security_list  # type: ignore[assignment]
    self.oke_private_security_list = self.vcn.private_security_list  # type: ignore[assignment]

    assert self.vcn.public_subnet is not None, "VCN public subnet must exist after finalization"
    assert self.vcn.private_subnet is not None, "VCN private subnet must exist after finalization"

    # Layer 2: VNIC-level NSGs — must be created before cluster/node pool
    self._create_oke_nsgs()

    child_opts = pulumi.ResourceOptions(parent=self)

    self.cluster = oci.containerengine.Cluster(
        "Cluster",
        compartment_id=self.compartment_id,
        name=f"Cluster-{self.display_name}",
        kubernetes_version=self.kubernetes_version,
        options=oci.containerengine.ClusterOptionsArgs(
            service_lb_subnet_ids=[self.vcn.public_subnet.id],
            kubernetes_network_config=oci.containerengine.ClusterOptionsKubernetesNetworkConfigArgs(
                pods_cidr="172.16.0.0/16",
                services_cidr="172.17.0.0/16",
            ),
        ),
        cluster_pod_network_options=[
            oci.containerengine.ClusterClusterPodNetworkOptionArgs(
                cni_type="OCI_VCN_IP_NATIVE",
            )
        ],
        type="ENHANCED_CLUSTER" if enhanced else "BASIC_CLUSTER",
        vcn_id=self.vcn.id,
        endpoint_config=oci.containerengine.ClusterEndpointConfigArgs(
            subnet_id=(endpoint_subnet or self.vcn.public_subnet).id,  # type: ignore[union-attr]
            is_public_ip_enabled=endpoint_subnet is None,
            nsg_ids=[self.api_nsg.id],
        ),
        freeform_tags=self.create_freeform_tags(f"Cluster-{self.display_name}", "oke-cluster"),
        defined_tags=defined_tags,
        opts=child_opts,
    )

    self.id = self.cluster.id

    h: OciHelper = OciHelper()
    get_ad_names = oci.identity.get_availability_domains_output(compartment_id=self.compartment_id)
    ads = get_ad_names.availability_domains

    self.node_pools = []
    for cfg in node_pools:
        pool = oci.containerengine.NodePool(
            f"NodePool-{cfg.name}",
            name=f"NodePool-{cfg.name}-{self.display_name}",
            cluster_id=self.cluster.id,
            compartment_id=self.compartment_id,
            kubernetes_version=self.kubernetes_version,
            node_config_details=oci.containerengine.NodePoolNodeConfigDetailsArgs(
                placement_configs=ads.apply(lambda ads_list: h.get_ads(ads_list, self.vcn.private_subnet.id)),  # type: ignore[arg-type, union-attr, return-value]
                size=cfg.node_count,
                nsg_ids=[self.worker_nsg.id],
                node_pool_pod_network_option_details=oci.containerengine.NodePoolNodeConfigDetailsNodePoolPodNetworkOptionDetailsArgs(
                    cni_type="OCI_VCN_IP_NATIVE",
                    pod_subnet_ids=[self.vcn.private_subnet.id],  # type: ignore[union-attr]
                    pod_nsg_ids=[self.pod_nsg.id],
                ),
                defined_tags=cfg.defined_tags,
            ),
            node_shape=cfg.shape,
            node_shape_config=oci.containerengine.NodePoolNodeShapeConfigArgs(
                memory_in_gbs=cfg.memory_in_gbs,
                ocpus=cfg.ocpus,
            ),
            node_source_details=oci.containerengine.NodePoolNodeSourceDetailsArgs(
                image_id=cfg.image,
                source_type="IMAGE",
                boot_volume_size_in_gbs=(
                    str(cfg.boot_volume_size_in_gbs) if cfg.boot_volume_size_in_gbs is not None else None
                ),
            ),
            initial_node_labels=[
                oci.containerengine.NodePoolInitialNodeLabelArgs(key=k, value=v)
                for k, v in cfg.initial_node_labels.items()
            ]
            if cfg.initial_node_labels
            else None,
            node_metadata=cfg.node_metadata,
            node_eviction_node_pool_settings=oci.containerengine.NodePoolNodeEvictionNodePoolSettingsArgs(
                eviction_grace_duration=cfg.eviction_grace_duration,
                is_force_delete_after_grace_duration=cfg.force_delete_after_grace,
            )
            if cfg.eviction_grace_duration is not None or cfg.force_delete_after_grace
            else None,
            node_pool_cycling_details=oci.containerengine.NodePoolNodePoolCyclingDetailsArgs(
                is_node_cycling_enabled=cfg.cycling_enabled,
                maximum_surge=cfg.cycling_max_surge,
                maximum_unavailable=cfg.cycling_max_unavailable,
            )
            if cfg.cycling_enabled
            else None,
            ssh_public_key=cfg.ssh_public_key or None,
            freeform_tags=self.create_freeform_tags(f"NodePool-{cfg.name}", "oke-node-pool"),
            defined_tags=cfg.defined_tags,
            opts=child_opts,
        )
        self.node_pools.append(pool)

    self.register_outputs({})

export() -> None

Export standard OKE cluster stack outputs.

Publishes outputs derived from the spell's logical name:

  • {name}_cluster_id — OCID of the OKE cluster.
  • {name}_kubernetes_version — Kubernetes version deployed.
  • {name}_lb_nsg_id — OCID of the load-balancer NSG. Reference this value in the Kubernetes service annotation oci.oraclecloud.com/security-group-ids so that OCI attaches the correct NSG to every managed load balancer.
Example
oke = OkeCluster(name="okeinfra", ...)
oke.export()
# Exports: okeinfra_cluster_id, okeinfra_kubernetes_version, okeinfra_lb_nsg_id
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/kubernetes.py
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
def export(self) -> None:
    """Export standard OKE cluster stack outputs.

    Publishes outputs derived from the spell's logical name:

    - `{name}_cluster_id` — OCID of the OKE cluster.
    - `{name}_kubernetes_version` — Kubernetes version deployed.
    - `{name}_lb_nsg_id` — OCID of the load-balancer NSG.  Reference this
      value in the Kubernetes service annotation
      `oci.oraclecloud.com/security-group-ids` so that OCI attaches the
      correct NSG to every managed load balancer.

    Example:
        ```python
        oke = OkeCluster(name="okeinfra", ...)
        oke.export()
        # Exports: okeinfra_cluster_id, okeinfra_kubernetes_version, okeinfra_lb_nsg_id
        ```
    """
    prefix = self.name.replace("-", "_")
    pulumi.export(f"{prefix}_cluster_id", self.id)
    pulumi.export(f"{prefix}_kubernetes_version", self.kubernetes_version)
    pulumi.export(f"{prefix}_lb_nsg_id", self.lb_nsg.id)

get_public_security_list_ids() -> list[pulumi.Output[str]]

Return the ID of the public security list (populated with OKE rules).

Returns:

Type Description
list[Output[str]]

Single-element list containing the VCN public security list OCID

list[Output[str]]

as a pulumi.Output[str], or an empty list when using VcnRef

list[Output[str]]

without a security list export.

Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/kubernetes.py
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
def get_public_security_list_ids(self) -> list[pulumi.Output[str]]:
    """Return the ID of the public security list (populated with OKE rules).

    Returns:
        Single-element list containing the VCN public security list OCID
        as a `pulumi.Output[str]`, or an empty list when using `VcnRef`
        without a security list export.
    """
    sl = self.vcn.public_security_list
    return [sl.id] if sl is not None else []

get_private_security_list_ids() -> list[pulumi.Output[str]]

Return the ID of the private security list (populated with OKE rules).

Returns:

Type Description
list[Output[str]]

Single-element list containing the VCN private security list OCID

list[Output[str]]

as a pulumi.Output[str], or an empty list when using VcnRef

list[Output[str]]

without a security list export.

Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/kubernetes.py
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
def get_private_security_list_ids(self) -> list[pulumi.Output[str]]:
    """Return the ID of the private security list (populated with OKE rules).

    Returns:
        Single-element list containing the VCN private security list OCID
        as a `pulumi.Output[str]`, or an empty list when using `VcnRef`
        without a security list export.
    """
    sl = self.vcn.private_security_list
    return [sl.id] if sl is not None else []

create_kubeconfig(filename: str) -> None

Write a kubeconfig file for this OKE cluster.

Fetches the cluster's kubeconfig content from the OCI API and writes it to filename. The file is created or overwritten if it already exists.

Parameters:

Name Type Description Default
filename str

Absolute or relative path where the kubeconfig file should be written (e.g. "/tmp/kubeconfig").

required
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/kubernetes.py
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
def create_kubeconfig(self, filename: str) -> None:
    """Write a kubeconfig file for this OKE cluster.

    Fetches the cluster's kubeconfig content from the OCI API and writes
    it to `filename`.  The file is created or overwritten if it already
    exists.

    Args:
        filename: Absolute or relative path where the kubeconfig file
            should be written (e.g. `"/tmp/kubeconfig"`).
    """
    cluster_kube_config = self.cluster.id.apply(
        lambda cid: oci.containerengine.get_cluster_kube_config(cluster_id=cid)
    )

    def _write(cc: str) -> None:
        with open(filename, "w") as f:
            f.write(cc)

    cluster_kube_config.content.apply(_write)  # type: ignore[union-attr]