Skip to content

OCI Network Security Groups

cloudspells.providers.oci.nsg

Network Security Group (NSG) spell for CloudSpells.

Provides Nsg, a single named Network Security Group with caller-defined rules. NSGs are role-based policies — one NSG represents the security policy for a class of resources (e.g. all web servers, all databases, all load balancers). The same NSG can be attached to any number of VMs, and a single VM can hold multiple NSGs.

This is intentionally not tied to subnet topology. Place the ComputeInstance in whatever subnet tier makes sense; attach the NSG that matches its role.

Typical usage:

from cloudspells.providers.oci.nsg import (
    Nsg, TCP, ALL, SVC_CIDR, INTERNET,
    HTTP, HTTPS, SSH, POSTGRES,
    tcp_port,
)

# One NSG per service role
lb_nsg  = Nsg("load-balancer", vcn=vcn, compartment_id=compartment_id)
web_nsg = Nsg("web-backend",   vcn=vcn, compartment_id=compartment_id)
db_nsg  = Nsg("database",      vcn=vcn, compartment_id=compartment_id)

# Internet edge — INTERNET constant replaces hard-coded "0.0.0.0/0"
lb_nsg.allow_from_cidr("https-in", HTTPS, INTERNET)
lb_nsg.allow_from_cidr("http-in",  HTTP,  INTERNET)
lb_nsg.allow_to_nsg("app-out", web_nsg, 8080)

web_nsg.allow_from_nsg("app-in", lb_nsg, 8080)
web_nsg.allow_from_nsg("ssh-in", lb_nsg, SSH)
web_nsg.allow_to_nsg("db-out",   db_nsg, POSTGRES)
web_nsg.allow_to_services("svc-out")
web_nsg.allow_to_cidr("inet-out", INTERNET)

db_nsg.allow_from_nsg("db-in",  web_nsg, POSTGRES)
db_nsg.allow_from_nsg("ssh-in", web_nsg, SSH)
db_nsg.allow_to_services("svc-out")

# Attach the right NSG to each VM — same NSG shared across identical roles
lb   = ComputeInstance("lb",    ..., nsg_ids=[lb_nsg.id])
web1 = ComputeInstance("web-1", ..., nsg_ids=[web_nsg.id])
web2 = ComputeInstance("web-2", ..., nsg_ids=[web_nsg.id])  # same NSG
db1  = ComputeInstance("db-1",  ..., nsg_ids=[db_nsg.id])
db2  = ComputeInstance("db-2",  ..., nsg_ids=[db_nsg.id])   # same NSG

# A VM with two roles gets two NSGs
combo = ComputeInstance("app", ..., nsg_ids=[web_nsg.id, db_nsg.id])
Exports

Nsg, TCP, UDP, ALL, SVC_CIDR, HTTP, HTTPS, SSH, MYSQL, POSTGRES, ORACLE_DB, REDIS, tcp_port, tcp_port_range, udp_port, udp_port_range, icmp_opts

CASSANDRA: int = 9042 module-attribute

Default Apache Cassandra CQL native transport port.

DNS: int = 53 module-attribute

DNS query port (TCP for zone transfers; UDP for queries).

ELASTICSEARCH: int = 9200 module-attribute

Elasticsearch HTTP REST API port.

HTTP: int = 80 module-attribute

Standard HTTP port.

HTTP_ALT: int = 8080 module-attribute

Alternate HTTP port commonly used by application servers.

HTTPS: int = 443 module-attribute

Standard HTTPS port.

HTTPS_ALT: int = 8443 module-attribute

Alternate HTTPS port commonly used by application servers.

KAFKA: int = 9092 module-attribute

Default Apache Kafka broker port.

LDAP: int = 389 module-attribute

Lightweight Directory Access Protocol port.

LDAPS: int = 636 module-attribute

LDAP over TLS port.

MEMCACHED: int = 11211 module-attribute

Default Memcached port.

MONGODB: int = 27017 module-attribute

Default MongoDB port.

MSSQL: int = 1433 module-attribute

Default Microsoft SQL Server port.

MYSQL: int = 3306 module-attribute

Default MySQL / Aurora port.

NFS: int = 2049 module-attribute

Network File System (NFSv3/v4) port.

ORACLE_DB: int = 1521 module-attribute

Default Oracle Database listener port.

POSTGRES: int = 5432 module-attribute

Default PostgreSQL port.

RABBITMQ: int = 5672 module-attribute

Default RabbitMQ AMQP port.

RDP: int = 3389 module-attribute

Remote Desktop Protocol port.

REDIS: int = 6379 module-attribute

Default Redis port.

SMB: int = 445 module-attribute

SMB / CIFS (Windows file sharing) port.

SMTP: int = 25 module-attribute

SMTP relay port.

SMTPS: int = 587 module-attribute

SMTP submission (STARTTLS) port.

SSH: int = 22 module-attribute

Standard SSH port.

TCP: str = '6' module-attribute

OCI protocol number for TCP.

UDP: str = '17' module-attribute

OCI protocol number for UDP.

ICMP: str = '1' module-attribute

OCI protocol number for ICMP.

ALL: str = 'all' module-attribute

OCI wildcard accepting all protocols.

SVC_CIDR: pulumi.Output[str] = oci.core.get_services_output().services.apply(lambda svcs: next((s.cidr_block) for s in svcs if s.cidr_block.startswith('all-'))) module-attribute

OCI All-Services CIDR block used for Service Gateway egress rules.

Resolved lazily at plan time via oci.core.get_services_output(). Type is pulumi.Output[str]; passes directly to any pulumi.Input[str] field.

INTERNET: str = '0.0.0.0/0' module-attribute

CIDR representing the public internet. Use with Nsg.allow_from_cidr and Nsg.allow_to_cidr for edge-facing rules.

Role dataclass

Security posture descriptor for a class of networked resources.

A Role encodes the ambient network behaviour of a security group — the rules that every resource of this type needs regardless of which peers it communicates with. Directional traffic relationships are declared separately by the provider's NSG/security-group implementation.

Attributes:

Name Type Description
subnet_tier SubnetTier

Which network tier resources carrying this role belong to. Used by compute spells to infer subnet placement when a role is supplied instead of an explicit subnet.

egress_internet bool

True adds an all-protocol egress rule to 0.0.0.0/0 (outbound via NAT Gateway or equivalent). Suitable for private-tier app servers that call external APIs. Not set for DATABASE, MANAGEMENT, or INTERNET_EDGE.

egress_services bool

True adds an all-protocol egress rule to the cloud provider's managed-services endpoint (OCI Service Gateway, AWS VPC Gateway, GCP Private Google Access). Required for any instance that calls provider-managed endpoints (object storage, container registry, etc.).

accept_management_ssh bool

True causes the provider NSG implementation to automatically include an SSH (port 22) management channel from the upstream NSG in addition to the application port. Set False for roles where SSH access arrives through a separate channel (e.g. a bastion service session).

Example
from cloudspells.core.abstractions import Role
from cloudspells.core.abstractions import SUBNET_PRIVATE

# Custom role: private tier, internet + service egress, no SSH from upstream.
proxy = Role(
    subnet_tier=SUBNET_PRIVATE,
    egress_internet=True,
    egress_services=True,
    accept_management_ssh=False,
)
Source code in packages/cloudspells-core/src/cloudspells/core/abstractions/roles.py
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
@dataclass
class Role:
    """Security posture descriptor for a class of networked resources.

    A `Role` encodes the ambient network behaviour of a security group — the
    rules that every resource of this type needs regardless of which peers it
    communicates with.  Directional traffic relationships are declared
    separately by the provider's NSG/security-group implementation.

    Attributes:
        subnet_tier: Which network tier resources carrying this role belong to.
            Used by compute spells to infer subnet placement when a role is
            supplied instead of an explicit subnet.
        egress_internet: `True` adds an all-protocol egress rule to
            `0.0.0.0/0` (outbound via NAT Gateway or equivalent).  Suitable
            for private-tier app servers that call external APIs.  Not set for
            `DATABASE`, `MANAGEMENT`, or `INTERNET_EDGE`.
        egress_services: `True` adds an all-protocol egress rule to the cloud
            provider's managed-services endpoint (OCI Service Gateway, AWS
            VPC Gateway, GCP Private Google Access).  Required for any
            instance that calls provider-managed endpoints (object storage,
            container registry, etc.).
        accept_management_ssh: `True` causes the provider NSG implementation
            to automatically include an SSH (port 22) management channel from
            the upstream NSG in addition to the application port.  Set `False`
            for roles where SSH access arrives through a separate channel (e.g.
            a bastion service session).

    Example:
        ```python
        from cloudspells.core.abstractions import Role
        from cloudspells.core.abstractions import SUBNET_PRIVATE

        # Custom role: private tier, internet + service egress, no SSH from upstream.
        proxy = Role(
            subnet_tier=SUBNET_PRIVATE,
            egress_internet=True,
            egress_services=True,
            accept_management_ssh=False,
        )
        ```
    """

    subnet_tier: SubnetTier
    egress_internet: bool = False
    egress_services: bool = False
    accept_management_ssh: bool = True

Nsg

Bases: BaseResource

A single named Network Security Group with caller-defined rules.

Represents the security policy for one service role (e.g. all web servers, all databases, all load balancers). Multiple VMs of the same role share the same Nsg; a VM with multiple roles receives multiple Nsg IDs via nsg_ids.

OCI enforces implicit deny-all for NSGs with no rules — every allowed traffic flow must be stated explicitly with add_rule.

Attributes:

Name Type Description
nsg NetworkSecurityGroup

The underlying oci.core.NetworkSecurityGroup resource.

id Output[str]

pulumi.Output[str] OCID of this NSG. Pass this to ComputeInstance via nsg_ids or reference it in another NSG's rule as source / destination.

Example
from cloudspells.providers.oci.nsg import Nsg, TCP, ALL, SVC_CIDR, tcp_port

lb_nsg  = Nsg("load-balancer", vcn=vcn, compartment_id=compartment_id)
web_nsg = Nsg("web-backend",   vcn=vcn, compartment_id=compartment_id)
db_nsg  = Nsg("database",      vcn=vcn, compartment_id=compartment_id)

# internet → load balancer
lb_nsg.add_rule("https-in",
                direction="INGRESS", protocol=TCP,
                source="0.0.0.0/0", source_type="CIDR_BLOCK",
                tcp_options=tcp_port(443))

# load balancer → web backends  (NSG-to-NSG, no CIDRs)
lb_nsg.add_rule("app-out",
                direction="EGRESS", protocol=TCP,
                destination=web_nsg.id,
                destination_type="NETWORK_SECURITY_GROUP",
                tcp_options=tcp_port(8080))
web_nsg.add_rule("app-in",
                 direction="INGRESS", protocol=TCP,
                 source=lb_nsg.id,
                 source_type="NETWORK_SECURITY_GROUP",
                 tcp_options=tcp_port(8080))

# web backends → databases  (NSG-to-NSG, no CIDRs)
web_nsg.add_rule("db-out",
                 direction="EGRESS", protocol=TCP,
                 destination=db_nsg.id,
                 destination_type="NETWORK_SECURITY_GROUP",
                 tcp_options=tcp_port(5432))
db_nsg.add_rule("db-in",
                direction="INGRESS", protocol=TCP,
                source=web_nsg.id,
                source_type="NETWORK_SECURITY_GROUP",
                tcp_options=tcp_port(5432))

# Attach — same NSG shared by all VMs of the same role
lb   = ComputeInstance("lb",    ..., nsg_ids=[lb_nsg.id])
web1 = ComputeInstance("web-1", ..., nsg_ids=[web_nsg.id])
web2 = ComputeInstance("web-2", ..., nsg_ids=[web_nsg.id])
db1  = ComputeInstance("db-1",  ..., nsg_ids=[db_nsg.id])
db2  = ComputeInstance("db-2",  ..., nsg_ids=[db_nsg.id])
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
 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
class Nsg(BaseResource):
    """A single named Network Security Group with caller-defined rules.

    Represents the security policy for one **service role** (e.g. all web
    servers, all databases, all load balancers).  Multiple VMs of the same
    role share the same `Nsg`; a VM with multiple roles receives multiple
    `Nsg` IDs via `nsg_ids`.

    OCI enforces implicit deny-all for NSGs with no rules — every allowed
    traffic flow must be stated explicitly with `add_rule`.

    Attributes:
        nsg: The underlying `oci.core.NetworkSecurityGroup` resource.
        id: `pulumi.Output[str]` OCID of this NSG.  Pass this to
            `ComputeInstance` via `nsg_ids` or reference it in another
            NSG's rule as `source` / `destination`.

    Example:
        ```python
        from cloudspells.providers.oci.nsg import Nsg, TCP, ALL, SVC_CIDR, tcp_port

        lb_nsg  = Nsg("load-balancer", vcn=vcn, compartment_id=compartment_id)
        web_nsg = Nsg("web-backend",   vcn=vcn, compartment_id=compartment_id)
        db_nsg  = Nsg("database",      vcn=vcn, compartment_id=compartment_id)

        # internet → load balancer
        lb_nsg.add_rule("https-in",
                        direction="INGRESS", protocol=TCP,
                        source="0.0.0.0/0", source_type="CIDR_BLOCK",
                        tcp_options=tcp_port(443))

        # load balancer → web backends  (NSG-to-NSG, no CIDRs)
        lb_nsg.add_rule("app-out",
                        direction="EGRESS", protocol=TCP,
                        destination=web_nsg.id,
                        destination_type="NETWORK_SECURITY_GROUP",
                        tcp_options=tcp_port(8080))
        web_nsg.add_rule("app-in",
                         direction="INGRESS", protocol=TCP,
                         source=lb_nsg.id,
                         source_type="NETWORK_SECURITY_GROUP",
                         tcp_options=tcp_port(8080))

        # web backends → databases  (NSG-to-NSG, no CIDRs)
        web_nsg.add_rule("db-out",
                         direction="EGRESS", protocol=TCP,
                         destination=db_nsg.id,
                         destination_type="NETWORK_SECURITY_GROUP",
                         tcp_options=tcp_port(5432))
        db_nsg.add_rule("db-in",
                        direction="INGRESS", protocol=TCP,
                        source=web_nsg.id,
                        source_type="NETWORK_SECURITY_GROUP",
                        tcp_options=tcp_port(5432))

        # Attach — same NSG shared by all VMs of the same role
        lb   = ComputeInstance("lb",    ..., nsg_ids=[lb_nsg.id])
        web1 = ComputeInstance("web-1", ..., nsg_ids=[web_nsg.id])
        web2 = ComputeInstance("web-2", ..., nsg_ids=[web_nsg.id])
        db1  = ComputeInstance("db-1",  ..., nsg_ids=[db_nsg.id])
        db2  = ComputeInstance("db-2",  ..., nsg_ids=[db_nsg.id])
        ```
    """

    nsg: oci.core.NetworkSecurityGroup
    id: pulumi.Output[str]

    def __init__(
        self,
        name: str,
        vcn: Vcn | VcnRef,
        compartment_id: pulumi.Input[str],
        stack_name: str | None = None,
        opts: pulumi.ResourceOptions | None = None,
        role: Role | None = None,
        ports: list[int] | None = None,
        defined_tags: dict[str, Any] | None = None,
    ) -> None:
        """Create a single NSG for a service role.

        When `role` is supplied the NSG self-configures: ambient rules are
        added automatically based on the posture declared in the role, and the
        corresponding VCN security list rules are registered so that
        `Vcn.finalize_network` can materialise them without any manual
        `Vcn.add_security_rules` call.

        When `role` is `None` the NSG is created empty and all rules must be
        added explicitly via `add_rule` and the convenience helpers.

        Args:
            name: Role name for this NSG (e.g. `"load-balancer"`,
                `"web-backend"`, `"database"`).  Used to derive the
                Pulumi resource name and OCI display name.
            vcn: The `Vcn` (or `VcnRef`) that hosts this NSG.
            compartment_id: OCID of the OCI compartment to deploy into.
            stack_name: Pulumi stack name.  Defaults to
                `pulumi.get_stack()` when `None`.
            opts: Pulumi resource options forwarded to the component.
            role: Optional `Role` that encodes the security posture of this
                NSG.  When set, ambient rules are generated automatically and
                subnet security list rules are registered with the VCN.
            ports: TCP port numbers that `INTERNET_EDGE` resources accept from
                the internet (e.g. `[HTTP, HTTPS, SSH]`).  Required when
                `role=INTERNET_EDGE`; ignored for other roles.
            defined_tags: OCI defined tags applied to the
                `NetworkSecurityGroup` resource, in
                `{"namespace": {"key": "value"}}` format.  Used for
                enterprise cost tracking and governance.  When `None` no
                defined tags are applied.

        Example:
            ```python
            from cloudspells.providers.oci import INTERNET_EDGE, APP_SERVER, DATABASE
            from cloudspells.providers.oci.nsg import Nsg, HTTP, HTTPS, SSH

            lb_nsg  = Nsg("load-balancer", role=INTERNET_EDGE, ports=[HTTP, HTTPS, SSH],
                          vcn=vcn, compartment_id=compartment_id)
            web_nsg = Nsg("web-backend",   role=APP_SERVER, vcn=vcn, compartment_id=compartment_id)
            db_nsg  = Nsg("database",      role=DATABASE,   vcn=vcn, compartment_id=compartment_id)

            lb_nsg.serves(web_nsg, port=8080)
            web_nsg.serves(db_nsg, port=5432)
            ```
        """
        super().__init__(
            "custom:network:Nsg",
            name,
            compartment_id,
            stack_name,
            opts,
        )

        self._vcn = vcn
        self.role = role

        resource_name = self.create_resource_name("nsg")
        self.nsg = oci.core.NetworkSecurityGroup(
            resource_name,
            compartment_id=self.compartment_id,
            vcn_id=vcn.id,
            display_name=resource_name,
            freeform_tags=self.create_freeform_tags(resource_name, "nsg"),
            # [GAP] G5: wire defined_tags into the NSG resource
            defined_tags=defined_tags,
            opts=pulumi.ResourceOptions(parent=self),
        )
        self.id = self.nsg.id

        if role is not None:
            self._apply_role_ambient_rules(role, ports or [])

    # ------------------------------------------------------------------
    # Role and relationship methods
    # ------------------------------------------------------------------

    def _sl_for_tier(
        self,
        fingerprint: str,
        tier: str,
        ingress: list[oci.core.SecurityListIngressSecurityRuleArgs] | None = None,
        egress: list[oci.core.SecurityListEgressSecurityRuleArgs] | None = None,
    ) -> None:
        """Dispatch a uniquely-fingerprinted security list rule to the correct tier.

        Wraps `Vcn._add_unique_security_list_rules` with an explicit
        `if`/`elif` tier dispatch so Pyright can verify that ingress args go
        to ingress parameters and egress args to egress parameters (dynamic
        `**kwargs` unpacking defeats the type checker).

        This is an internal helper; external callers should use `serves` or
        `_apply_role_ambient_rules`.

        Args:
            fingerprint: Unique key; subsequent calls with the same fingerprint
                are silently ignored by the VCN accumulator.
            tier: Subnet tier constant (`"public"`, `"private"`, `"secure"`,
                or `"management"`).
            ingress: Optional ingress rule list for the tier's security list.
            egress: Optional egress rule list for the tier's security list.
        """
        if not isinstance(self._vcn, Vcn):
            return
        vcn = self._vcn
        if tier == SUBNET_PUBLIC:
            vcn._add_unique_security_list_rules(fingerprint, public_ingress=ingress, public_egress=egress)
        elif tier == SUBNET_PRIVATE:
            vcn._add_unique_security_list_rules(fingerprint, private_ingress=ingress, private_egress=egress)
        elif tier == SUBNET_SECURE:
            vcn._add_unique_security_list_rules(fingerprint, secure_ingress=ingress, secure_egress=egress)
        elif tier == SUBNET_MANAGEMENT:
            vcn._add_unique_security_list_rules(fingerprint, management_ingress=ingress, management_egress=egress)

    def _apply_role_ambient_rules(self, role: Role, ports: list[int]) -> None:
        """Create ambient NSG rules and register security list rules for `role`.

        Called once from `__init__` when `role=` is supplied.  The caller
        must not invoke this method directly.

        NSG rules created per role:

        - **INTERNET_EDGE** (`subnet_tier == SUBNET_PUBLIC`): TCP ingress from
          `0.0.0.0/0` on each declared port, plus ICMP Type 3 Code 4 ingress
          from `0.0.0.0/0` for path-MTU discovery.
        - **APP_SERVER / CACHE** (`egress_internet=True`): all-protocol egress
          to `0.0.0.0/0` and to Oracle Services, plus ICMP Type 3 Code 4
          ingress from `0.0.0.0/0` for path-MTU discovery.
        - **DATABASE / MANAGEMENT** (`egress_services=True` only): all-protocol
          egress to Oracle Services only (no internet).

        When the backing network is a live `Vcn` (not a `VcnRef`), the
        equivalent subnet security list rules are also registered via
        `Vcn._add_unique_security_list_rules` so that `Vcn.finalize_network`
        can emit them without any manual `Vcn.add_security_rules` call by the
        user.

        Args:
            role: The `Role` to apply.
            ports: TCP ports for `INTERNET_EDGE` internet ingress.
        """
        tier = role.subnet_tier
        is_internet_edge = tier == SUBNET_PUBLIC

        # -- NSG rules --------------------------------------------------------
        if is_internet_edge:
            for port in ports:
                self.allow_from_cidr(f"internet-in-{port}", port, INTERNET)
            # GAP BRIDGE: ICMP path-MTU discovery ingress for INTERNET_EDGE.
            # Documented in the role's docstring but previously absent from the
            # implementation.  TCP connections from the internet stall silently
            # when the return path MTU is smaller than the instance MTU without
            # this rule.
            self.allow_icmp_from_cidr("pmtu-in", INTERNET, icmp_type=3, code=4)

        if role.egress_services:
            self.allow_to_services("svc-out")
        if role.egress_internet:
            self.allow_to_cidr("inet-out", INTERNET)
            # GAP BRIDGE: ICMP path-MTU discovery ingress for NAT-egress roles.
            # APP_SERVER and CACHE route outbound via NAT Gateway; the return
            # path MTU may differ.  Documented in the APP_SERVER docstring as
            # "ICMP path-MTU ingress from 0.0.0.0/0 on the NSG".
            self.allow_icmp_from_cidr("pmtu-in", INTERNET, icmp_type=3, code=4)

        # -- Security list rules (only for live Vcn, not VcnRef) --------------
        if not isinstance(self._vcn, Vcn):
            return

        if is_internet_edge:
            for port in ports:
                self._vcn._add_unique_security_list_rules(
                    f"public-ingress-tcp-{port}",
                    public_ingress=[_sl_ingress_tcp(port, "0.0.0.0/0", f"TCP {port} from internet")],
                )
            # GAP BRIDGE: ICMP path-MTU security list rule for the public subnet.
            # Mirrors the NSG rule registered above so that the public security
            # list also permits ICMP Type 3 Code 4 from the internet.
            self._sl_for_tier(
                "public-ingress-icmp-pmtu",
                SUBNET_PUBLIC,
                ingress=[_sl_ingress_icmp_pmtu("0.0.0.0/0", "ICMP path-MTU discovery from internet")],
            )

        if role.egress_services:
            self._sl_for_tier(f"{tier}-egress-all-services", tier, egress=[_sl_egress_all_services()])
        if role.egress_internet:
            self._sl_for_tier(f"{tier}-egress-all-internet", tier, egress=[_sl_egress_all_internet()])
            # GAP BRIDGE: ICMP path-MTU security list rule for NAT-egress tiers.
            # Mirrors the NSG rule registered above at the security list layer.
            self._sl_for_tier(
                f"{tier}-ingress-icmp-pmtu",
                tier,
                ingress=[_sl_ingress_icmp_pmtu("0.0.0.0/0", "ICMP path-MTU discovery via NAT")],
            )

    def serves(
        self,
        target: Nsg,
        port: int,
        *,
        with_ssh: bool = True,
    ) -> None:
        """Declare a directed traffic relationship from this NSG to `target`.

        A single call generates the full set of bilateral rules needed for the
        relationship:

        - Egress from this NSG to `target` on `port`.
        - Ingress on `target` from this NSG on `port`.
        - (When `with_ssh=True` and `target` has `role.accept_management_ssh`)
          Egress from this NSG to `target` on port 22.
        - (Same condition) Ingress on `target` from this NSG on port 22.

        When both NSGs carry `Role` instances and the backing network is a
        live `Vcn`, the corresponding subnet security list cross-subnet rules
        are also registered automatically.  Cross-subnet rules are only emitted
        when the two roles occupy different tiers (same-tier rules are handled
        entirely by the NSGs themselves).

        Args:
            target: The downstream `Nsg` that receives the traffic.
            port: TCP port number for the application-level connection.
            with_ssh: When `True` (default) an SSH (port 22) management
                channel is added alongside the application port — egress from
                this NSG to `target`, ingress on `target` from this NSG.  Set
                `False` to suppress the SSH channel (e.g. for read-only data
                paths or when SSH access is provided by a separate Bastion
                service).

        Example:
            ```python
            lb_nsg.serves(web_nsg, port=8080)          # app + SSH management
            web_nsg.serves(db_nsg, port=5432)          # app + SSH management
            lb_nsg.serves(web_nsg, port=443, with_ssh=False)  # HTTPS only
            ```
        """
        src = self.name
        tgt = target.name

        # Application port — both directions
        self.allow_to_nsg(f"out-{tgt}-{port}", target, port)
        target.allow_from_nsg(f"in-{src}-{port}", self, port)

        # SSH management channel
        needs_ssh = with_ssh and (target.role is None or target.role.accept_management_ssh)
        if needs_ssh:
            self.allow_to_nsg(f"out-{tgt}-ssh", target, SSH)
            target.allow_from_nsg(f"in-{src}-ssh", self, SSH)

        # Security list cross-subnet rules (only when both roles are known
        # and the network is a live Vcn — VcnRef manages its own rules)
        if self.role is None or target.role is None:
            return
        if not isinstance(self._vcn, Vcn):
            return
        src_tier = self.role.subnet_tier
        tgt_tier = target.role.subnet_tier
        if src_tier == tgt_tier:
            return  # same subnet — NSG rules are sufficient

        src_cidr = getattr(self._vcn, f"get_{src_tier}_subnet_cidr")()
        tgt_cidr = getattr(self._vcn, f"get_{tgt_tier}_subnet_cidr")()

        self._sl_for_tier(
            f"{src_tier}-egress-tcp-{port}-to-{tgt_tier}",
            src_tier,
            egress=[_sl_egress_tcp(port, tgt_cidr, f"TCP {port} to {tgt_tier} tier")],
        )
        self._sl_for_tier(
            f"{tgt_tier}-ingress-tcp-{port}-from-{src_tier}",
            tgt_tier,
            ingress=[_sl_ingress_tcp(port, src_cidr, f"TCP {port} from {src_tier} tier")],
        )

        if needs_ssh:
            self._sl_for_tier(
                f"{src_tier}-egress-tcp-22-to-{tgt_tier}",
                src_tier,
                egress=[_sl_egress_tcp(SSH, tgt_cidr, f"SSH to {tgt_tier} tier")],
            )
            self._sl_for_tier(
                f"{tgt_tier}-ingress-tcp-22-from-{src_tier}",
                tgt_tier,
                ingress=[_sl_ingress_tcp(SSH, src_cidr, f"SSH from {src_tier} tier")],
            )

    # ------------------------------------------------------------------
    # Public API
    # ------------------------------------------------------------------

    def add_rule(
        self,
        label: 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,
        udp_options: oci.core.NetworkSecurityGroupSecurityRuleUdpOptionsArgs | None = None,
        icmp_options: oci.core.NetworkSecurityGroupSecurityRuleIcmpOptionsArgs | None = None,
        description: str = "",
    ) -> oci.core.NetworkSecurityGroupSecurityRule:
        """Add a single stateful security rule to this NSG.

        The Pulumi resource name is `{stack}-{nsg-name}-nsg-rule-{label}`.
        `label` must be unique within this NSG.

        Args:
            label: Short unique label for this rule within the NSG
                (e.g. `"https-in"`, `"db-out"`).
            direction: `"INGRESS"` or `"EGRESS"`.
            protocol: OCI protocol string — use module constants `TCP`,
                `UDP`, `ICMP`, or `ALL`.
            source: Source CIDR string or NSG OCID.  Required for ingress.
            source_type: `"CIDR_BLOCK"`, `"NETWORK_SECURITY_GROUP"`,
                or `"SERVICE_CIDR_BLOCK"`.
            destination: Destination CIDR or NSG OCID.  Required for egress.
            destination_type: `"CIDR_BLOCK"`, `"NETWORK_SECURITY_GROUP"`,
                or `"SERVICE_CIDR_BLOCK"`.
            tcp_options: TCP port restriction — build with `tcp_port`
                or `tcp_port_range`.
            udp_options: UDP port restriction — build with `udp_port`
                or `udp_port_range`.
            icmp_options: ICMP type/code restriction — build with `icmp_opts`.
            description: Human-readable description shown in the OCI Console.

        Returns:
            The `oci.core.NetworkSecurityGroupSecurityRule` resource.

        Example:
            ```python
            web_nsg.add_rule(
                "app-in",
                direction="INGRESS", protocol=TCP,
                source=lb_nsg.id,
                source_type="NETWORK_SECURITY_GROUP",
                tcp_options=tcp_port(8080),
                description="HTTP traffic from load-balancer NSG",
            )

            # DNS over UDP (requires udp_options — previously impossible)
            dns_nsg.add_rule(
                "dns-out",
                direction="EGRESS", protocol=UDP,
                destination=resolver_ip, destination_type="CIDR_BLOCK",
                udp_options=udp_port(DNS),
            )
            ```
        """
        resource_name = self.create_resource_name(f"nsg-rule-{label}")
        return oci.core.NetworkSecurityGroupSecurityRule(
            resource_name,
            network_security_group_id=self.nsg.id,
            direction=direction,
            protocol=protocol,
            source=source,
            source_type=source_type,
            destination=destination,
            destination_type=destination_type,
            tcp_options=tcp_options,
            # GAP BRIDGE: udp_options wired in — previously missing from the
            # resource call, making port-restricted UDP rules impossible.
            udp_options=udp_options,
            icmp_options=icmp_options,
            stateless=False,
            description=description or resource_name,
            opts=pulumi.ResourceOptions(parent=self),
        )

    # ------------------------------------------------------------------
    # Convenience helpers — encode idiomatic OCI patterns
    # ------------------------------------------------------------------

    def allow_from_cidr(
        self,
        label: str,
        port: int,
        cidr: str,
        description: str = "",
    ) -> oci.core.NetworkSecurityGroupSecurityRule:
        """Add an INGRESS TCP rule allowing traffic from a CIDR block.

        Use `INTERNET` (`"0.0.0.0/0"`) for unrestricted internet access, or
        pass a specific CIDR for restricted sources such as an office IP, VPN
        range, or peered VCN CIDR.

        Args:
            label: Unique label for this rule within the NSG.
            port: Destination TCP port.
            cidr: Source CIDR block.  Use `INTERNET` for `"0.0.0.0/0"`.
            description: Optional human-readable description.  Defaults to
                `"TCP {port} from {cidr}"`.

        Returns:
            The `oci.core.NetworkSecurityGroupSecurityRule` resource.

        Example:
            ```python
            lb_nsg.allow_from_cidr("https-in",   HTTPS,    INTERNET)
            lb_nsg.allow_from_cidr("ssh-office",  SSH,      "203.0.113.42/32")
            db_nsg.allow_from_cidr("db-peered",   POSTGRES, "172.16.0.0/12")
            ```
        """
        return self.add_rule(
            label,
            direction="INGRESS",
            protocol=TCP,
            source=cidr,
            source_type="CIDR_BLOCK",
            tcp_options=tcp_port(port),
            description=description or f"TCP {port} from {cidr}",
        )

    def allow_from_nsg(
        self,
        label: str,
        source: Nsg,
        port: int,
        description: str = "",
    ) -> oci.core.NetworkSecurityGroupSecurityRule:
        """Add an INGRESS TCP rule allowing traffic from another NSG.

        Uses `source_type="NETWORK_SECURITY_GROUP"` so only VMs carrying
        `source` can send traffic — no CIDRs required.

        Args:
            label: Unique label for this rule within the NSG.
            source: The peer `Nsg` whose members are the traffic source.
            port: Destination TCP port.
            description: Optional human-readable description.  Defaults to
                `"TCP {port} from NSG"`.

        Returns:
            The `oci.core.NetworkSecurityGroupSecurityRule` resource.

        Example:
            ```python
            web_nsg.allow_from_nsg("app-in", lb_nsg,  app_port)
            web_nsg.allow_from_nsg("ssh-in", lb_nsg,  SSH)
            db_nsg.allow_from_nsg("db-in",  web_nsg, POSTGRES)
            ```
        """
        return self.add_rule(
            label,
            direction="INGRESS",
            protocol=TCP,
            source=source.id,
            source_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(port),
            description=description or f"TCP {port} from NSG",
        )

    def allow_to_nsg(
        self,
        label: str,
        destination: Nsg,
        port: int,
        description: str = "",
    ) -> oci.core.NetworkSecurityGroupSecurityRule:
        """Add an EGRESS TCP rule allowing traffic to another NSG.

        Uses `destination_type="NETWORK_SECURITY_GROUP"` so only VMs
        carrying `destination` can receive the traffic.

        Args:
            label: Unique label for this rule within the NSG.
            destination: The peer `Nsg` whose members are the target.
            port: Destination TCP port.
            description: Optional human-readable description.  Defaults to
                `"TCP {port} to NSG"`.

        Returns:
            The `oci.core.NetworkSecurityGroupSecurityRule` resource.

        Example:
            ```python
            lb_nsg.allow_to_nsg("app-out",     web_nsg, app_port)
            web_nsg.allow_to_nsg("db-out",     db_nsg,  POSTGRES)
            web_nsg.allow_to_nsg("ssh-db-out", db_nsg,  SSH)
            ```
        """
        return self.add_rule(
            label,
            direction="EGRESS",
            protocol=TCP,
            destination=destination.id,
            destination_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(port),
            description=description or f"TCP {port} to NSG",
        )

    def allow_to_services(
        self,
        label: str,
        description: str = "",
    ) -> oci.core.NetworkSecurityGroupSecurityRule:
        """Add an EGRESS rule allowing all traffic to Oracle Services (Service GW).

        Uses `destination_type="SERVICE_CIDR_BLOCK"` and `protocol=ALL`.
        Required for any instance that must reach OCI Object Storage, the
        container registry, or other Oracle-managed services.

        Args:
            label: Unique label for this rule within the NSG.
            description: Optional human-readable description.  Defaults to
                `"All traffic to Oracle Services"`.

        Returns:
            The `oci.core.NetworkSecurityGroupSecurityRule` resource.

        Example:
            ```python
            web_nsg.allow_to_services("svc-out")
            db_nsg.allow_to_services("svc-out")
            ```
        """
        return self.add_rule(
            label,
            direction="EGRESS",
            protocol=ALL,
            destination=SVC_CIDR,
            destination_type="SERVICE_CIDR_BLOCK",
            description=description or "All traffic to Oracle Services",
        )

    def allow_to_cidr(
        self,
        label: str,
        cidr: str,
        description: str = "",
    ) -> oci.core.NetworkSecurityGroupSecurityRule:
        """Add an EGRESS all-protocol rule allowing traffic to a CIDR block.

        Use `INTERNET` (`"0.0.0.0/0"`) for unrestricted outbound via the NAT
        Gateway, or pass a specific CIDR for targeted egress.

        Args:
            label: Unique label for this rule within the NSG.
            cidr: Destination CIDR block.  Use `INTERNET` for `"0.0.0.0/0"`.
            description: Optional human-readable description.  Defaults to
                `"All traffic to {cidr}"`.

        Returns:
            The `oci.core.NetworkSecurityGroupSecurityRule` resource.

        Example:
            ```python
            web_nsg.allow_to_cidr("inet-out",    INTERNET)
            web_nsg.allow_to_cidr("peered-out",  "10.1.0.0/16")
            ```
        """
        return self.add_rule(
            label,
            direction="EGRESS",
            protocol=ALL,
            destination=cidr,
            destination_type="CIDR_BLOCK",
            description=description or f"All traffic to {cidr}",
        )

    # GAP BRIDGE: allow_icmp_from_cidr — convenience method for ICMP ingress.
    # Previously there was no helper for ICMP rules; callers had to use the
    # verbose add_rule() with a manually constructed icmp_options argument.
    # This method is used internally by _apply_role_ambient_rules for PMTUD
    # and is also available to callers who need custom ICMP ingress rules.

    def allow_icmp_from_cidr(
        self,
        label: str,
        cidr: str,
        icmp_type: int,
        code: int = -1,
        description: str = "",
    ) -> oci.core.NetworkSecurityGroupSecurityRule:
        """Add an INGRESS ICMP rule allowing a specific type (and optional code) from a CIDR.

        The most common use is ICMP Type 3 Code 4 (path-MTU discovery), which
        is required for TCP connections traversing gateways with differing MTUs.

        Args:
            label: Unique label for this rule within the NSG.
            cidr: Source CIDR block.  Use `INTERNET` for `"0.0.0.0/0"`.
            icmp_type: ICMP type number (e.g. `3` for Destination Unreachable).
            code: ICMP code number.  Use `-1` (default) to match all codes.
            description: Optional human-readable description.

        Returns:
            The `oci.core.NetworkSecurityGroupSecurityRule` resource.

        Example:
            ```python
            # Path-MTU discovery from the internet
            lb_nsg.allow_icmp_from_cidr("pmtu-in", INTERNET, icmp_type=3, code=4)
            ```
        """
        return self.add_rule(
            label,
            direction="INGRESS",
            protocol=ICMP,
            source=cidr,
            source_type="CIDR_BLOCK",
            icmp_options=icmp_opts(icmp_type, code),
            description=description or f"ICMP type {icmp_type} code {code} from {cidr}",
        )

__init__(name: str, vcn: Vcn | VcnRef, compartment_id: pulumi.Input[str], stack_name: str | None = None, opts: pulumi.ResourceOptions | None = None, role: Role | None = None, ports: list[int] | None = None, defined_tags: dict[str, Any] | None = None) -> None

Create a single NSG for a service role.

When role is supplied the NSG self-configures: ambient rules are added automatically based on the posture declared in the role, and the corresponding VCN security list rules are registered so that Vcn.finalize_network can materialise them without any manual Vcn.add_security_rules call.

When role is None the NSG is created empty and all rules must be added explicitly via add_rule and the convenience helpers.

Parameters:

Name Type Description Default
name str

Role name for this NSG (e.g. "load-balancer", "web-backend", "database"). Used to derive the Pulumi resource name and OCI display name.

required
vcn Vcn | VcnRef

The Vcn (or VcnRef) that hosts this NSG.

required
compartment_id Input[str]

OCID of the OCI compartment to deploy into.

required
stack_name str | None

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

None
opts ResourceOptions | None

Pulumi resource options forwarded to the component.

None
role Role | None

Optional Role that encodes the security posture of this NSG. When set, ambient rules are generated automatically and subnet security list rules are registered with the VCN.

None
ports list[int] | None

TCP port numbers that INTERNET_EDGE resources accept from the internet (e.g. [HTTP, HTTPS, SSH]). Required when role=INTERNET_EDGE; ignored for other roles.

None
defined_tags dict[str, Any] | None

OCI defined tags applied to the NetworkSecurityGroup resource, in {"namespace": {"key": "value"}} format. Used for enterprise cost tracking and governance. When None no defined tags are applied.

None
Example
from cloudspells.providers.oci import INTERNET_EDGE, APP_SERVER, DATABASE
from cloudspells.providers.oci.nsg import Nsg, HTTP, HTTPS, SSH

lb_nsg  = Nsg("load-balancer", role=INTERNET_EDGE, ports=[HTTP, HTTPS, SSH],
              vcn=vcn, compartment_id=compartment_id)
web_nsg = Nsg("web-backend",   role=APP_SERVER, vcn=vcn, compartment_id=compartment_id)
db_nsg  = Nsg("database",      role=DATABASE,   vcn=vcn, compartment_id=compartment_id)

lb_nsg.serves(web_nsg, port=8080)
web_nsg.serves(db_nsg, port=5432)
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
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
def __init__(
    self,
    name: str,
    vcn: Vcn | VcnRef,
    compartment_id: pulumi.Input[str],
    stack_name: str | None = None,
    opts: pulumi.ResourceOptions | None = None,
    role: Role | None = None,
    ports: list[int] | None = None,
    defined_tags: dict[str, Any] | None = None,
) -> None:
    """Create a single NSG for a service role.

    When `role` is supplied the NSG self-configures: ambient rules are
    added automatically based on the posture declared in the role, and the
    corresponding VCN security list rules are registered so that
    `Vcn.finalize_network` can materialise them without any manual
    `Vcn.add_security_rules` call.

    When `role` is `None` the NSG is created empty and all rules must be
    added explicitly via `add_rule` and the convenience helpers.

    Args:
        name: Role name for this NSG (e.g. `"load-balancer"`,
            `"web-backend"`, `"database"`).  Used to derive the
            Pulumi resource name and OCI display name.
        vcn: The `Vcn` (or `VcnRef`) that hosts this NSG.
        compartment_id: OCID of the OCI compartment to deploy into.
        stack_name: Pulumi stack name.  Defaults to
            `pulumi.get_stack()` when `None`.
        opts: Pulumi resource options forwarded to the component.
        role: Optional `Role` that encodes the security posture of this
            NSG.  When set, ambient rules are generated automatically and
            subnet security list rules are registered with the VCN.
        ports: TCP port numbers that `INTERNET_EDGE` resources accept from
            the internet (e.g. `[HTTP, HTTPS, SSH]`).  Required when
            `role=INTERNET_EDGE`; ignored for other roles.
        defined_tags: OCI defined tags applied to the
            `NetworkSecurityGroup` resource, in
            `{"namespace": {"key": "value"}}` format.  Used for
            enterprise cost tracking and governance.  When `None` no
            defined tags are applied.

    Example:
        ```python
        from cloudspells.providers.oci import INTERNET_EDGE, APP_SERVER, DATABASE
        from cloudspells.providers.oci.nsg import Nsg, HTTP, HTTPS, SSH

        lb_nsg  = Nsg("load-balancer", role=INTERNET_EDGE, ports=[HTTP, HTTPS, SSH],
                      vcn=vcn, compartment_id=compartment_id)
        web_nsg = Nsg("web-backend",   role=APP_SERVER, vcn=vcn, compartment_id=compartment_id)
        db_nsg  = Nsg("database",      role=DATABASE,   vcn=vcn, compartment_id=compartment_id)

        lb_nsg.serves(web_nsg, port=8080)
        web_nsg.serves(db_nsg, port=5432)
        ```
    """
    super().__init__(
        "custom:network:Nsg",
        name,
        compartment_id,
        stack_name,
        opts,
    )

    self._vcn = vcn
    self.role = role

    resource_name = self.create_resource_name("nsg")
    self.nsg = oci.core.NetworkSecurityGroup(
        resource_name,
        compartment_id=self.compartment_id,
        vcn_id=vcn.id,
        display_name=resource_name,
        freeform_tags=self.create_freeform_tags(resource_name, "nsg"),
        # [GAP] G5: wire defined_tags into the NSG resource
        defined_tags=defined_tags,
        opts=pulumi.ResourceOptions(parent=self),
    )
    self.id = self.nsg.id

    if role is not None:
        self._apply_role_ambient_rules(role, ports or [])

serves(target: Nsg, port: int, *, with_ssh: bool = True) -> None

Declare a directed traffic relationship from this NSG to target.

A single call generates the full set of bilateral rules needed for the relationship:

  • Egress from this NSG to target on port.
  • Ingress on target from this NSG on port.
  • (When with_ssh=True and target has role.accept_management_ssh) Egress from this NSG to target on port 22.
  • (Same condition) Ingress on target from this NSG on port 22.

When both NSGs carry Role instances and the backing network is a live Vcn, the corresponding subnet security list cross-subnet rules are also registered automatically. Cross-subnet rules are only emitted when the two roles occupy different tiers (same-tier rules are handled entirely by the NSGs themselves).

Parameters:

Name Type Description Default
target Nsg

The downstream Nsg that receives the traffic.

required
port int

TCP port number for the application-level connection.

required
with_ssh bool

When True (default) an SSH (port 22) management channel is added alongside the application port — egress from this NSG to target, ingress on target from this NSG. Set False to suppress the SSH channel (e.g. for read-only data paths or when SSH access is provided by a separate Bastion service).

True
Example
lb_nsg.serves(web_nsg, port=8080)          # app + SSH management
web_nsg.serves(db_nsg, port=5432)          # app + SSH management
lb_nsg.serves(web_nsg, port=443, with_ssh=False)  # HTTPS only
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
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
def serves(
    self,
    target: Nsg,
    port: int,
    *,
    with_ssh: bool = True,
) -> None:
    """Declare a directed traffic relationship from this NSG to `target`.

    A single call generates the full set of bilateral rules needed for the
    relationship:

    - Egress from this NSG to `target` on `port`.
    - Ingress on `target` from this NSG on `port`.
    - (When `with_ssh=True` and `target` has `role.accept_management_ssh`)
      Egress from this NSG to `target` on port 22.
    - (Same condition) Ingress on `target` from this NSG on port 22.

    When both NSGs carry `Role` instances and the backing network is a
    live `Vcn`, the corresponding subnet security list cross-subnet rules
    are also registered automatically.  Cross-subnet rules are only emitted
    when the two roles occupy different tiers (same-tier rules are handled
    entirely by the NSGs themselves).

    Args:
        target: The downstream `Nsg` that receives the traffic.
        port: TCP port number for the application-level connection.
        with_ssh: When `True` (default) an SSH (port 22) management
            channel is added alongside the application port — egress from
            this NSG to `target`, ingress on `target` from this NSG.  Set
            `False` to suppress the SSH channel (e.g. for read-only data
            paths or when SSH access is provided by a separate Bastion
            service).

    Example:
        ```python
        lb_nsg.serves(web_nsg, port=8080)          # app + SSH management
        web_nsg.serves(db_nsg, port=5432)          # app + SSH management
        lb_nsg.serves(web_nsg, port=443, with_ssh=False)  # HTTPS only
        ```
    """
    src = self.name
    tgt = target.name

    # Application port — both directions
    self.allow_to_nsg(f"out-{tgt}-{port}", target, port)
    target.allow_from_nsg(f"in-{src}-{port}", self, port)

    # SSH management channel
    needs_ssh = with_ssh and (target.role is None or target.role.accept_management_ssh)
    if needs_ssh:
        self.allow_to_nsg(f"out-{tgt}-ssh", target, SSH)
        target.allow_from_nsg(f"in-{src}-ssh", self, SSH)

    # Security list cross-subnet rules (only when both roles are known
    # and the network is a live Vcn — VcnRef manages its own rules)
    if self.role is None or target.role is None:
        return
    if not isinstance(self._vcn, Vcn):
        return
    src_tier = self.role.subnet_tier
    tgt_tier = target.role.subnet_tier
    if src_tier == tgt_tier:
        return  # same subnet — NSG rules are sufficient

    src_cidr = getattr(self._vcn, f"get_{src_tier}_subnet_cidr")()
    tgt_cidr = getattr(self._vcn, f"get_{tgt_tier}_subnet_cidr")()

    self._sl_for_tier(
        f"{src_tier}-egress-tcp-{port}-to-{tgt_tier}",
        src_tier,
        egress=[_sl_egress_tcp(port, tgt_cidr, f"TCP {port} to {tgt_tier} tier")],
    )
    self._sl_for_tier(
        f"{tgt_tier}-ingress-tcp-{port}-from-{src_tier}",
        tgt_tier,
        ingress=[_sl_ingress_tcp(port, src_cidr, f"TCP {port} from {src_tier} tier")],
    )

    if needs_ssh:
        self._sl_for_tier(
            f"{src_tier}-egress-tcp-22-to-{tgt_tier}",
            src_tier,
            egress=[_sl_egress_tcp(SSH, tgt_cidr, f"SSH to {tgt_tier} tier")],
        )
        self._sl_for_tier(
            f"{tgt_tier}-ingress-tcp-22-from-{src_tier}",
            tgt_tier,
            ingress=[_sl_ingress_tcp(SSH, src_cidr, f"SSH from {src_tier} tier")],
        )

add_rule(label: 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, udp_options: oci.core.NetworkSecurityGroupSecurityRuleUdpOptionsArgs | None = None, icmp_options: oci.core.NetworkSecurityGroupSecurityRuleIcmpOptionsArgs | None = None, description: str = '') -> oci.core.NetworkSecurityGroupSecurityRule

Add a single stateful security rule to this NSG.

The Pulumi resource name is {stack}-{nsg-name}-nsg-rule-{label}. label must be unique within this NSG.

Parameters:

Name Type Description Default
label str

Short unique label for this rule within the NSG (e.g. "https-in", "db-out").

required
direction str

"INGRESS" or "EGRESS".

required
protocol str

OCI protocol string — use module constants TCP, UDP, ICMP, or ALL.

required
source Input[str] | None

Source CIDR string or NSG OCID. Required for ingress.

None
source_type str | None

"CIDR_BLOCK", "NETWORK_SECURITY_GROUP", or "SERVICE_CIDR_BLOCK".

None
destination Input[str] | None

Destination CIDR or NSG OCID. Required for egress.

None
destination_type str | None

"CIDR_BLOCK", "NETWORK_SECURITY_GROUP", or "SERVICE_CIDR_BLOCK".

None
tcp_options NetworkSecurityGroupSecurityRuleTcpOptionsArgs | None

TCP port restriction — build with tcp_port or tcp_port_range.

None
udp_options NetworkSecurityGroupSecurityRuleUdpOptionsArgs | None

UDP port restriction — build with udp_port or udp_port_range.

None
icmp_options NetworkSecurityGroupSecurityRuleIcmpOptionsArgs | None

ICMP type/code restriction — build with icmp_opts.

None
description str

Human-readable description shown in the OCI Console.

''

Returns:

Type Description
NetworkSecurityGroupSecurityRule

The oci.core.NetworkSecurityGroupSecurityRule resource.

Example
web_nsg.add_rule(
    "app-in",
    direction="INGRESS", protocol=TCP,
    source=lb_nsg.id,
    source_type="NETWORK_SECURITY_GROUP",
    tcp_options=tcp_port(8080),
    description="HTTP traffic from load-balancer NSG",
)

# DNS over UDP (requires udp_options — previously impossible)
dns_nsg.add_rule(
    "dns-out",
    direction="EGRESS", protocol=UDP,
    destination=resolver_ip, destination_type="CIDR_BLOCK",
    udp_options=udp_port(DNS),
)
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
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
def add_rule(
    self,
    label: 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,
    udp_options: oci.core.NetworkSecurityGroupSecurityRuleUdpOptionsArgs | None = None,
    icmp_options: oci.core.NetworkSecurityGroupSecurityRuleIcmpOptionsArgs | None = None,
    description: str = "",
) -> oci.core.NetworkSecurityGroupSecurityRule:
    """Add a single stateful security rule to this NSG.

    The Pulumi resource name is `{stack}-{nsg-name}-nsg-rule-{label}`.
    `label` must be unique within this NSG.

    Args:
        label: Short unique label for this rule within the NSG
            (e.g. `"https-in"`, `"db-out"`).
        direction: `"INGRESS"` or `"EGRESS"`.
        protocol: OCI protocol string — use module constants `TCP`,
            `UDP`, `ICMP`, or `ALL`.
        source: Source CIDR string or NSG OCID.  Required for ingress.
        source_type: `"CIDR_BLOCK"`, `"NETWORK_SECURITY_GROUP"`,
            or `"SERVICE_CIDR_BLOCK"`.
        destination: Destination CIDR or NSG OCID.  Required for egress.
        destination_type: `"CIDR_BLOCK"`, `"NETWORK_SECURITY_GROUP"`,
            or `"SERVICE_CIDR_BLOCK"`.
        tcp_options: TCP port restriction — build with `tcp_port`
            or `tcp_port_range`.
        udp_options: UDP port restriction — build with `udp_port`
            or `udp_port_range`.
        icmp_options: ICMP type/code restriction — build with `icmp_opts`.
        description: Human-readable description shown in the OCI Console.

    Returns:
        The `oci.core.NetworkSecurityGroupSecurityRule` resource.

    Example:
        ```python
        web_nsg.add_rule(
            "app-in",
            direction="INGRESS", protocol=TCP,
            source=lb_nsg.id,
            source_type="NETWORK_SECURITY_GROUP",
            tcp_options=tcp_port(8080),
            description="HTTP traffic from load-balancer NSG",
        )

        # DNS over UDP (requires udp_options — previously impossible)
        dns_nsg.add_rule(
            "dns-out",
            direction="EGRESS", protocol=UDP,
            destination=resolver_ip, destination_type="CIDR_BLOCK",
            udp_options=udp_port(DNS),
        )
        ```
    """
    resource_name = self.create_resource_name(f"nsg-rule-{label}")
    return oci.core.NetworkSecurityGroupSecurityRule(
        resource_name,
        network_security_group_id=self.nsg.id,
        direction=direction,
        protocol=protocol,
        source=source,
        source_type=source_type,
        destination=destination,
        destination_type=destination_type,
        tcp_options=tcp_options,
        # GAP BRIDGE: udp_options wired in — previously missing from the
        # resource call, making port-restricted UDP rules impossible.
        udp_options=udp_options,
        icmp_options=icmp_options,
        stateless=False,
        description=description or resource_name,
        opts=pulumi.ResourceOptions(parent=self),
    )

allow_from_cidr(label: str, port: int, cidr: str, description: str = '') -> oci.core.NetworkSecurityGroupSecurityRule

Add an INGRESS TCP rule allowing traffic from a CIDR block.

Use INTERNET ("0.0.0.0/0") for unrestricted internet access, or pass a specific CIDR for restricted sources such as an office IP, VPN range, or peered VCN CIDR.

Parameters:

Name Type Description Default
label str

Unique label for this rule within the NSG.

required
port int

Destination TCP port.

required
cidr str

Source CIDR block. Use INTERNET for "0.0.0.0/0".

required
description str

Optional human-readable description. Defaults to "TCP {port} from {cidr}".

''

Returns:

Type Description
NetworkSecurityGroupSecurityRule

The oci.core.NetworkSecurityGroupSecurityRule resource.

Example
lb_nsg.allow_from_cidr("https-in",   HTTPS,    INTERNET)
lb_nsg.allow_from_cidr("ssh-office",  SSH,      "203.0.113.42/32")
db_nsg.allow_from_cidr("db-peered",   POSTGRES, "172.16.0.0/12")
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
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
def allow_from_cidr(
    self,
    label: str,
    port: int,
    cidr: str,
    description: str = "",
) -> oci.core.NetworkSecurityGroupSecurityRule:
    """Add an INGRESS TCP rule allowing traffic from a CIDR block.

    Use `INTERNET` (`"0.0.0.0/0"`) for unrestricted internet access, or
    pass a specific CIDR for restricted sources such as an office IP, VPN
    range, or peered VCN CIDR.

    Args:
        label: Unique label for this rule within the NSG.
        port: Destination TCP port.
        cidr: Source CIDR block.  Use `INTERNET` for `"0.0.0.0/0"`.
        description: Optional human-readable description.  Defaults to
            `"TCP {port} from {cidr}"`.

    Returns:
        The `oci.core.NetworkSecurityGroupSecurityRule` resource.

    Example:
        ```python
        lb_nsg.allow_from_cidr("https-in",   HTTPS,    INTERNET)
        lb_nsg.allow_from_cidr("ssh-office",  SSH,      "203.0.113.42/32")
        db_nsg.allow_from_cidr("db-peered",   POSTGRES, "172.16.0.0/12")
        ```
    """
    return self.add_rule(
        label,
        direction="INGRESS",
        protocol=TCP,
        source=cidr,
        source_type="CIDR_BLOCK",
        tcp_options=tcp_port(port),
        description=description or f"TCP {port} from {cidr}",
    )

allow_from_nsg(label: str, source: Nsg, port: int, description: str = '') -> oci.core.NetworkSecurityGroupSecurityRule

Add an INGRESS TCP rule allowing traffic from another NSG.

Uses source_type="NETWORK_SECURITY_GROUP" so only VMs carrying source can send traffic — no CIDRs required.

Parameters:

Name Type Description Default
label str

Unique label for this rule within the NSG.

required
source Nsg

The peer Nsg whose members are the traffic source.

required
port int

Destination TCP port.

required
description str

Optional human-readable description. Defaults to "TCP {port} from NSG".

''

Returns:

Type Description
NetworkSecurityGroupSecurityRule

The oci.core.NetworkSecurityGroupSecurityRule resource.

Example
web_nsg.allow_from_nsg("app-in", lb_nsg,  app_port)
web_nsg.allow_from_nsg("ssh-in", lb_nsg,  SSH)
db_nsg.allow_from_nsg("db-in",  web_nsg, POSTGRES)
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
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
def allow_from_nsg(
    self,
    label: str,
    source: Nsg,
    port: int,
    description: str = "",
) -> oci.core.NetworkSecurityGroupSecurityRule:
    """Add an INGRESS TCP rule allowing traffic from another NSG.

    Uses `source_type="NETWORK_SECURITY_GROUP"` so only VMs carrying
    `source` can send traffic — no CIDRs required.

    Args:
        label: Unique label for this rule within the NSG.
        source: The peer `Nsg` whose members are the traffic source.
        port: Destination TCP port.
        description: Optional human-readable description.  Defaults to
            `"TCP {port} from NSG"`.

    Returns:
        The `oci.core.NetworkSecurityGroupSecurityRule` resource.

    Example:
        ```python
        web_nsg.allow_from_nsg("app-in", lb_nsg,  app_port)
        web_nsg.allow_from_nsg("ssh-in", lb_nsg,  SSH)
        db_nsg.allow_from_nsg("db-in",  web_nsg, POSTGRES)
        ```
    """
    return self.add_rule(
        label,
        direction="INGRESS",
        protocol=TCP,
        source=source.id,
        source_type="NETWORK_SECURITY_GROUP",
        tcp_options=tcp_port(port),
        description=description or f"TCP {port} from NSG",
    )

allow_to_nsg(label: str, destination: Nsg, port: int, description: str = '') -> oci.core.NetworkSecurityGroupSecurityRule

Add an EGRESS TCP rule allowing traffic to another NSG.

Uses destination_type="NETWORK_SECURITY_GROUP" so only VMs carrying destination can receive the traffic.

Parameters:

Name Type Description Default
label str

Unique label for this rule within the NSG.

required
destination Nsg

The peer Nsg whose members are the target.

required
port int

Destination TCP port.

required
description str

Optional human-readable description. Defaults to "TCP {port} to NSG".

''

Returns:

Type Description
NetworkSecurityGroupSecurityRule

The oci.core.NetworkSecurityGroupSecurityRule resource.

Example
lb_nsg.allow_to_nsg("app-out",     web_nsg, app_port)
web_nsg.allow_to_nsg("db-out",     db_nsg,  POSTGRES)
web_nsg.allow_to_nsg("ssh-db-out", db_nsg,  SSH)
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
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
def allow_to_nsg(
    self,
    label: str,
    destination: Nsg,
    port: int,
    description: str = "",
) -> oci.core.NetworkSecurityGroupSecurityRule:
    """Add an EGRESS TCP rule allowing traffic to another NSG.

    Uses `destination_type="NETWORK_SECURITY_GROUP"` so only VMs
    carrying `destination` can receive the traffic.

    Args:
        label: Unique label for this rule within the NSG.
        destination: The peer `Nsg` whose members are the target.
        port: Destination TCP port.
        description: Optional human-readable description.  Defaults to
            `"TCP {port} to NSG"`.

    Returns:
        The `oci.core.NetworkSecurityGroupSecurityRule` resource.

    Example:
        ```python
        lb_nsg.allow_to_nsg("app-out",     web_nsg, app_port)
        web_nsg.allow_to_nsg("db-out",     db_nsg,  POSTGRES)
        web_nsg.allow_to_nsg("ssh-db-out", db_nsg,  SSH)
        ```
    """
    return self.add_rule(
        label,
        direction="EGRESS",
        protocol=TCP,
        destination=destination.id,
        destination_type="NETWORK_SECURITY_GROUP",
        tcp_options=tcp_port(port),
        description=description or f"TCP {port} to NSG",
    )

allow_to_services(label: str, description: str = '') -> oci.core.NetworkSecurityGroupSecurityRule

Add an EGRESS rule allowing all traffic to Oracle Services (Service GW).

Uses destination_type="SERVICE_CIDR_BLOCK" and protocol=ALL. Required for any instance that must reach OCI Object Storage, the container registry, or other Oracle-managed services.

Parameters:

Name Type Description Default
label str

Unique label for this rule within the NSG.

required
description str

Optional human-readable description. Defaults to "All traffic to Oracle Services".

''

Returns:

Type Description
NetworkSecurityGroupSecurityRule

The oci.core.NetworkSecurityGroupSecurityRule resource.

Example
web_nsg.allow_to_services("svc-out")
db_nsg.allow_to_services("svc-out")
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
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
def allow_to_services(
    self,
    label: str,
    description: str = "",
) -> oci.core.NetworkSecurityGroupSecurityRule:
    """Add an EGRESS rule allowing all traffic to Oracle Services (Service GW).

    Uses `destination_type="SERVICE_CIDR_BLOCK"` and `protocol=ALL`.
    Required for any instance that must reach OCI Object Storage, the
    container registry, or other Oracle-managed services.

    Args:
        label: Unique label for this rule within the NSG.
        description: Optional human-readable description.  Defaults to
            `"All traffic to Oracle Services"`.

    Returns:
        The `oci.core.NetworkSecurityGroupSecurityRule` resource.

    Example:
        ```python
        web_nsg.allow_to_services("svc-out")
        db_nsg.allow_to_services("svc-out")
        ```
    """
    return self.add_rule(
        label,
        direction="EGRESS",
        protocol=ALL,
        destination=SVC_CIDR,
        destination_type="SERVICE_CIDR_BLOCK",
        description=description or "All traffic to Oracle Services",
    )

allow_to_cidr(label: str, cidr: str, description: str = '') -> oci.core.NetworkSecurityGroupSecurityRule

Add an EGRESS all-protocol rule allowing traffic to a CIDR block.

Use INTERNET ("0.0.0.0/0") for unrestricted outbound via the NAT Gateway, or pass a specific CIDR for targeted egress.

Parameters:

Name Type Description Default
label str

Unique label for this rule within the NSG.

required
cidr str

Destination CIDR block. Use INTERNET for "0.0.0.0/0".

required
description str

Optional human-readable description. Defaults to "All traffic to {cidr}".

''

Returns:

Type Description
NetworkSecurityGroupSecurityRule

The oci.core.NetworkSecurityGroupSecurityRule resource.

Example
web_nsg.allow_to_cidr("inet-out",    INTERNET)
web_nsg.allow_to_cidr("peered-out",  "10.1.0.0/16")
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
 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
def allow_to_cidr(
    self,
    label: str,
    cidr: str,
    description: str = "",
) -> oci.core.NetworkSecurityGroupSecurityRule:
    """Add an EGRESS all-protocol rule allowing traffic to a CIDR block.

    Use `INTERNET` (`"0.0.0.0/0"`) for unrestricted outbound via the NAT
    Gateway, or pass a specific CIDR for targeted egress.

    Args:
        label: Unique label for this rule within the NSG.
        cidr: Destination CIDR block.  Use `INTERNET` for `"0.0.0.0/0"`.
        description: Optional human-readable description.  Defaults to
            `"All traffic to {cidr}"`.

    Returns:
        The `oci.core.NetworkSecurityGroupSecurityRule` resource.

    Example:
        ```python
        web_nsg.allow_to_cidr("inet-out",    INTERNET)
        web_nsg.allow_to_cidr("peered-out",  "10.1.0.0/16")
        ```
    """
    return self.add_rule(
        label,
        direction="EGRESS",
        protocol=ALL,
        destination=cidr,
        destination_type="CIDR_BLOCK",
        description=description or f"All traffic to {cidr}",
    )

allow_icmp_from_cidr(label: str, cidr: str, icmp_type: int, code: int = -1, description: str = '') -> oci.core.NetworkSecurityGroupSecurityRule

Add an INGRESS ICMP rule allowing a specific type (and optional code) from a CIDR.

The most common use is ICMP Type 3 Code 4 (path-MTU discovery), which is required for TCP connections traversing gateways with differing MTUs.

Parameters:

Name Type Description Default
label str

Unique label for this rule within the NSG.

required
cidr str

Source CIDR block. Use INTERNET for "0.0.0.0/0".

required
icmp_type int

ICMP type number (e.g. 3 for Destination Unreachable).

required
code int

ICMP code number. Use -1 (default) to match all codes.

-1
description str

Optional human-readable description.

''

Returns:

Type Description
NetworkSecurityGroupSecurityRule

The oci.core.NetworkSecurityGroupSecurityRule resource.

Example
# Path-MTU discovery from the internet
lb_nsg.allow_icmp_from_cidr("pmtu-in", INTERNET, icmp_type=3, code=4)
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
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
def allow_icmp_from_cidr(
    self,
    label: str,
    cidr: str,
    icmp_type: int,
    code: int = -1,
    description: str = "",
) -> oci.core.NetworkSecurityGroupSecurityRule:
    """Add an INGRESS ICMP rule allowing a specific type (and optional code) from a CIDR.

    The most common use is ICMP Type 3 Code 4 (path-MTU discovery), which
    is required for TCP connections traversing gateways with differing MTUs.

    Args:
        label: Unique label for this rule within the NSG.
        cidr: Source CIDR block.  Use `INTERNET` for `"0.0.0.0/0"`.
        icmp_type: ICMP type number (e.g. `3` for Destination Unreachable).
        code: ICMP code number.  Use `-1` (default) to match all codes.
        description: Optional human-readable description.

    Returns:
        The `oci.core.NetworkSecurityGroupSecurityRule` resource.

    Example:
        ```python
        # Path-MTU discovery from the internet
        lb_nsg.allow_icmp_from_cidr("pmtu-in", INTERNET, icmp_type=3, code=4)
        ```
    """
    return self.add_rule(
        label,
        direction="INGRESS",
        protocol=ICMP,
        source=cidr,
        source_type="CIDR_BLOCK",
        icmp_options=icmp_opts(icmp_type, code),
        description=description or f"ICMP type {icmp_type} code {code} from {cidr}",
    )

tcp_port(port: int) -> oci.core.NetworkSecurityGroupSecurityRuleTcpOptionsArgs

Return TCP options restricting traffic to a single destination port.

Parameters:

Name Type Description Default
port int

Destination TCP port number (1–65535).

required

Returns:

Type Description
NetworkSecurityGroupSecurityRuleTcpOptionsArgs

NetworkSecurityGroupSecurityRuleTcpOptionsArgs with a single-port

NetworkSecurityGroupSecurityRuleTcpOptionsArgs

destination range.

Example
nsg.add_rule("https-in", ..., tcp_options=tcp_port(443))
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def tcp_port(port: int) -> oci.core.NetworkSecurityGroupSecurityRuleTcpOptionsArgs:
    """Return TCP options restricting traffic to a single destination port.

    Args:
        port: Destination TCP port number (1–65535).

    Returns:
        `NetworkSecurityGroupSecurityRuleTcpOptionsArgs` with a single-port
        destination range.

    Example:
        ```python
        nsg.add_rule("https-in", ..., tcp_options=tcp_port(443))
        ```
    """
    return oci.core.NetworkSecurityGroupSecurityRuleTcpOptionsArgs(
        destination_port_range=oci.core.NetworkSecurityGroupSecurityRuleTcpOptionsDestinationPortRangeArgs(
            min=port,
            max=port,
        )
    )

tcp_port_range(min_port: int, max_port: int) -> oci.core.NetworkSecurityGroupSecurityRuleTcpOptionsArgs

Return TCP options restricting traffic to a destination port range.

Parameters:

Name Type Description Default
min_port int

Lowest destination port (inclusive).

required
max_port int

Highest destination port (inclusive).

required

Returns:

Type Description
NetworkSecurityGroupSecurityRuleTcpOptionsArgs

NetworkSecurityGroupSecurityRuleTcpOptionsArgs with the specified

NetworkSecurityGroupSecurityRuleTcpOptionsArgs

destination port range.

Example
nsg.add_rule("ephemeral-out", ..., tcp_options=tcp_port_range(1024, 65535))
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def tcp_port_range(min_port: int, max_port: int) -> oci.core.NetworkSecurityGroupSecurityRuleTcpOptionsArgs:
    """Return TCP options restricting traffic to a destination port range.

    Args:
        min_port: Lowest destination port (inclusive).
        max_port: Highest destination port (inclusive).

    Returns:
        `NetworkSecurityGroupSecurityRuleTcpOptionsArgs` with the specified
        destination port range.

    Example:
        ```python
        nsg.add_rule("ephemeral-out", ..., tcp_options=tcp_port_range(1024, 65535))
        ```
    """
    return oci.core.NetworkSecurityGroupSecurityRuleTcpOptionsArgs(
        destination_port_range=oci.core.NetworkSecurityGroupSecurityRuleTcpOptionsDestinationPortRangeArgs(
            min=min_port,
            max=max_port,
        )
    )

udp_port(port: int) -> oci.core.NetworkSecurityGroupSecurityRuleUdpOptionsArgs

Return UDP options restricting traffic to a single destination port.

Parameters:

Name Type Description Default
port int

Destination UDP port number (1–65535).

required

Returns:

Type Description
NetworkSecurityGroupSecurityRuleUdpOptionsArgs

NetworkSecurityGroupSecurityRuleUdpOptionsArgs with a single-port

NetworkSecurityGroupSecurityRuleUdpOptionsArgs

destination range.

Example
# DNS over UDP
nsg.add_rule("dns-out", direction="EGRESS", protocol=UDP,
             destination=resolver_cidr, destination_type="CIDR_BLOCK",
             udp_options=udp_port(DNS))
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def udp_port(port: int) -> oci.core.NetworkSecurityGroupSecurityRuleUdpOptionsArgs:
    """Return UDP options restricting traffic to a single destination port.

    Args:
        port: Destination UDP port number (1–65535).

    Returns:
        `NetworkSecurityGroupSecurityRuleUdpOptionsArgs` with a single-port
        destination range.

    Example:
        ```python
        # DNS over UDP
        nsg.add_rule("dns-out", direction="EGRESS", protocol=UDP,
                     destination=resolver_cidr, destination_type="CIDR_BLOCK",
                     udp_options=udp_port(DNS))
        ```
    """
    return oci.core.NetworkSecurityGroupSecurityRuleUdpOptionsArgs(
        destination_port_range=oci.core.NetworkSecurityGroupSecurityRuleUdpOptionsDestinationPortRangeArgs(
            min=port,
            max=port,
        )
    )

udp_port_range(min_port: int, max_port: int) -> oci.core.NetworkSecurityGroupSecurityRuleUdpOptionsArgs

Return UDP options restricting traffic to a destination port range.

Parameters:

Name Type Description Default
min_port int

Lowest destination port (inclusive).

required
max_port int

Highest destination port (inclusive).

required

Returns:

Type Description
NetworkSecurityGroupSecurityRuleUdpOptionsArgs

NetworkSecurityGroupSecurityRuleUdpOptionsArgs with the specified

NetworkSecurityGroupSecurityRuleUdpOptionsArgs

destination port range.

Example
nsg.add_rule("rtp-out", ..., udp_options=udp_port_range(16384, 32767))
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def udp_port_range(min_port: int, max_port: int) -> oci.core.NetworkSecurityGroupSecurityRuleUdpOptionsArgs:
    """Return UDP options restricting traffic to a destination port range.

    Args:
        min_port: Lowest destination port (inclusive).
        max_port: Highest destination port (inclusive).

    Returns:
        `NetworkSecurityGroupSecurityRuleUdpOptionsArgs` with the specified
        destination port range.

    Example:
        ```python
        nsg.add_rule("rtp-out", ..., udp_options=udp_port_range(16384, 32767))
        ```
    """
    return oci.core.NetworkSecurityGroupSecurityRuleUdpOptionsArgs(
        destination_port_range=oci.core.NetworkSecurityGroupSecurityRuleUdpOptionsDestinationPortRangeArgs(
            min=min_port,
            max=max_port,
        )
    )

icmp_opts(icmp_type: int, code: int = -1) -> oci.core.NetworkSecurityGroupSecurityRuleIcmpOptionsArgs

Return ICMP options for a specific type and optional code.

Parameters:

Name Type Description Default
icmp_type int

ICMP type number (e.g. 3 for Destination Unreachable).

required
code int

ICMP code number. Use -1 (default) to match all codes for the given type.

-1

Returns:

Type Description
NetworkSecurityGroupSecurityRuleIcmpOptionsArgs

NetworkSecurityGroupSecurityRuleIcmpOptionsArgs ready for use in

NetworkSecurityGroupSecurityRuleIcmpOptionsArgs

Nsg.add_rule or Nsg.allow_icmp_from_cidr.

Example
# Path-MTU discovery (Type 3, Code 4)
nsg.add_rule("pmtu-in", direction="INGRESS", protocol=ICMP,
             source="0.0.0.0/0", source_type="CIDR_BLOCK",
             icmp_options=icmp_opts(3, 4))
Source code in packages/cloudspells-oci/src/cloudspells/providers/oci/nsg.py
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
def icmp_opts(
    icmp_type: int,
    code: int = -1,
) -> oci.core.NetworkSecurityGroupSecurityRuleIcmpOptionsArgs:
    """Return ICMP options for a specific type and optional code.

    Args:
        icmp_type: ICMP type number (e.g. `3` for Destination Unreachable).
        code: ICMP code number.  Use `-1` (default) to match all codes for
            the given type.

    Returns:
        `NetworkSecurityGroupSecurityRuleIcmpOptionsArgs` ready for use in
        `Nsg.add_rule` or `Nsg.allow_icmp_from_cidr`.

    Example:
        ```python
        # Path-MTU discovery (Type 3, Code 4)
        nsg.add_rule("pmtu-in", direction="INGRESS", protocol=ICMP,
                     source="0.0.0.0/0", source_type="CIDR_BLOCK",
                     icmp_options=icmp_opts(3, 4))
        ```
    """
    return oci.core.NetworkSecurityGroupSecurityRuleIcmpOptionsArgs(
        type=icmp_type,
        code=code,
    )