terraform-google-modules/terraform-google-network

repository·main·Indexed 19 days ago

https://github.com/terraform-google-modules/terraform-google-network

A Terraform module for simplifying the creation and management of GCP VPC networks. It supports the deployment of auto mode and custom mode VPCs, subnets with secondary IP ranges, firewall policies, VPC network peering, and Shared VPC architectures including host and service project configurations.

Tokens
44.3K
Snippets
116
Records
170
Agent score
64%

What's inside terraform-google-network

  1. Overview of the Terraform Network Module

    main

    The Terraform Network Module simplifies the setup of a Google Cloud Platform (GCP) VPC Network. It allows you to define your network and subnet ranges using a concise syntax.

    Key capabilities include creating:

    • A Google Virtual Private Network (VPC)
    • Subnets within the VPC
    • Secondary ranges for subnets
    • Routes
    • Firewall rules
    • Network firewall policies
    • Hierarchical firewall policies
    • Serverless VPC access connectors
    • Network Connectivity Center

    For granular control, the repository provides individual sub-modules for each of these components.

  2. Configure Google Cloud VPC Firewall rules

    main

    The fabric-net-firewall module creates a minimal VPC firewall setup. It supports several types of rules:

    1. Intra-VPC Rules: Configurable IP range-based rules for internal traffic. By default, it only allows icmp.
    2. Administrator Ingress: Rules allowing complete access from specific admin CIDR ranges.
    3. Tag-based Ingress: Pre-configured rules for common services using network tags:
      • SSH: Uses the ssh tag by default.
      • HTTP: Uses the http-server tag by default.
      • HTTPS: Uses the https-server tag by default.
    4. Custom Rules: User-defined ingress or egress rules using a map of rule objects.

    All IP source ranges for tag-based rules default to 0.0.0.0/0 unless specified otherwise.

    module "net-firewall" {
      source                  = "terraform-google-modules/network/google//modules/fabric-net-firewall"
      project_id              = "my-project"
      network                 = "my-vpc"
      internal_ranges_enabled = true
      internal_ranges         = ["10.0.0.0/0"]
      internal_target_tags    = ["internal"]
      custom_rules = {
        ingress-sample = {
          description          = "Dummy sample ingress rule, tag-based."
          direction            = "INGRESS"
          action               = "allow"
          ranges               = ["192.168.0.0"]
          sources              = ["spam-tag"]
          targets              = ["foo-tag", "egg-tag"]
          use_service_accounts = false
          rules = [
            {
              protocol = "tcp"
              ports    = []
            }
          ]
          extra_attributes = {}
        }
      }
    }
  3. Configure Google Cloud Shared VPC Access

    main

    This module configures service project access to a Shared VPC host project. It automates two primary tasks:

    1. Attaching Service Projects: It uses the google_compute_shared_vpc_service_project resource to attach specified service projects to the host project.
    2. Assigning Subnet IAM Roles: It uses google_compute_subnetwork_iam_binding to grant specific IAM roles for individual subnets within the host project.

    This is useful for managing how service projects interact with the network infrastructure provided by a host project.

    module "net-shared-vpc-access" {
      source              = "terraform-google-modules/network/google//modules/fabric-net-svpc-access"
      version             = "~> 11.0"
    
      host_project_id     = "my-host-project-id"
      service_project_num = 1
      service_project_ids = ["my-service-project-id"]
      host_subnets        = ["my-subnet"]
      host_subnet_regions = ["europe-west1"]
      host_subnet_users   = {
        my-subnet = "group:my-service-owners@example.org,serviceAccount:1234567890@cloudservices.gserviceaccount.com"
      }
      host_service_agent_role = true
      host_service_agent_users = [
        "serviceAccount:service-123456789@container-engine-robot.iam.gserviceaccount.com"
      ]
    }
  4. Create Global or Regional Network Firewall Policies

    main

    This module manages Google Cloud Global and Regional Network Firewall Policies and their associated Rules.

    Key Behaviors:

    • Policy Scope: If policy_region is provided, a Regional policy is created. If policy_region is omitted (null), a Global policy is created.
    • Tier Support: Supports both Cloud Firewall Essentials and Cloud Firewall Standard tier rules.
    • VPC Attachment: You can optionally attach the policy to multiple VPCs using the target_vpcs argument.
    • Rule Attachment: Firewall rules and VPC attachments are optional components.
    module "network_firewall_policy" {
      source       = "terraform-google-modules/network/google//modules/network-firewall-policy"
      version      = "~> 11.0"
      project_id   = var.project_id
      policy_name  = "my-firewall-policy"
      description  = "Test firewall policy"
      target_vpcs  = [var.vpc1_id, var.vpc2_id]
    
      rules = [
        {},
        {},
      ]
    }
  5. Configure VPC Network Subnet Mode

    main

    You can control how subnets are managed within the VPC using the auto_create_subnetworks input:

    • Auto Subnet Mode: Set auto_create_subnetworks = true. The network will automatically create a subnet for each region using the 10.128.0.0/9 address range.
    • Custom Subnet Mode: Set auto_create_subnetworks = false (default). This allows you to explicitly connect or define subnetwork resources manually.
  6. Configure ingress and egress rules

    main

    The module provides two primary ways to define rules. It is recommended to use ingress_rules and egress_rules separately.

    Ingress Rules (ingress_rules)

    Used to control incoming traffic to your VPC.

    Egress Rules (egress_rules)

    Used to control outgoing traffic from your VPC.

    Important Constraint: If the rules variable is non-empty, both ingress_rules and egress_rules will be ignored.

  7. Configure Hierarchical Firewall Policy Rules

    main

    Rules are defined as a list of objects passed to the rules input. Each rule specifies an action (allow or deny) and a direction (INGRESS or EGRESS).

    Key Rule Components:

    • priority: A unique positive integer between 0 and 2147483647.
    • target_resources: A list of network resource URLs. If empty, the rule applies to all VMs in the organization.
    • target_service_accounts: A list of service account URLs. If empty, the rule applies to all VMs in the organization.
    • match: A block defining the traffic criteria:
      • For INGRESS rules: Use src_ip_ranges, src_fqdns, src_region_codes, src_threat_intelligences, and src_address_groups. Note that dest_* fields are ignored for Ingress.
      • For EGRESS rules: Use dest_ip_ranges, dest_fqdns, dest_region_codes, dest_threat_intelligences, and dest_address_groups. Note that src_* fields are ignored for Egress.
      • layer4_configs: A list of maps specifying ip_protocol (e.g., tcp, udp, icmp, esp, ah, ipip, sctp, or a protocol number) and an optional list of ports (integers or ranges like 8081-8085).
    rules = [
      {
        priority                = 1
        direction               = "INGRESS"
        action                  = "allow"
        rule_name               = "my-test-rule"
        description             = "My test firewall policy"
        enable_logging          = true
        target_service_accounts = ["service-account@project.iam.gserviceaccount.com"]
        match = {
          src_ip_ranges = ["10.0.0.0/24"]
          layer4_configs = [
            {
              ip_protocol = "tcp"
              ports       = ["80", "443"]
            },
          ]
        }
      }
    ]
  8. Handle multiple peering connections for a single VPC Network

    main

    When creating multiple peering connections for the same VPC Network (e.g., Network A peering to both Network B and Network C), you must ensure they are created sequentially. It is not possible to create more than one peering connection for a VPC Network simultaneously.

    To enforce this order, use the module_depends_on argument to make subsequent peering modules depend on the complete output of the previous peering module.

    module "peering-a-b" {
      source = "terraform-google-modules/network/google//modules/network-peering"
    
      prefix        = "name-prefix"
      local_network = "<A NETWORK SELF LINK>"
      peer_network  = "<B NETWORK SELF LINK>"
    }
    
    module "peering-a-c" {
      source = "terraform-google-modules/network/google//modules/network-peering"
    
      prefix        = "name-prefix"
      local_network = "<A NETWORK SELF LINK>"
      peer_network  = "<C NETWORK SELF LINK>"
    
      module_depends_on = [module.peering-a-b.complete]
    }
  9. Attach Spokes to an NCC Hub

    main

    You can attach different types of spokes to the hub using the following input maps:

    VPC Spokes (vpc_spokes)

    Used for associating VPC networks with the hub. Supports optional producer VPC network peering via link_producer_vpc_network.

    Hybrid Spokes (hybrid_spokes)

    Used for associating VLAN attachments and VPN Tunnels. The type must be either interconnect or vpn.

    Router Appliance Spokes (router_appliance_spokes)

    Used for associating router appliance instances. Requires a list of instances containing virtual_machine and ip_address.

    Global Spoke Labels

    • spoke_labels: A map of labels applied to all spokes created by the module.
  10. Configure route next hop destinations

    main

    When defining a route in the routes list, you must specify how traffic should be routed. Important: Only one next_hop_* input can be used per route. Providing multiple next_hop_* inputs will result in an error.

    Supported next hop types:

    • next_hop_internet: Set to true to use the default internet gateway.
    • next_hop_ip: The network IP address of an instance to handle packets.
    • next_hop_instance: The URL or name of an instance. If only a name is provided, you must also specify next_hop_instance_zone.
    • next_hop_vpn_tunnel: The URL to a VPN Tunnel.
    • next_hop_ilb: The URL to an Internal Load Balancer forwarding rule (loadBalancingScheme=INTERNAL).
    • next_hop_gateway: The next hop gateway.
  11. Configure PSC Producer NAT subnets

    main

    The nat_subnets input allows you to define the IP stack and ranges for the NAT subnets created by the module.

    Stack Type Options:

    • IPV4_ONLY: Requires ipv4_range.
    • IPV4_IPV6: Requires ipv4_range (dual-stack).
    • IPV6_ONLY: Do not provide ipv4_range; IPv6 ranges are assigned automatically by GCP.

    Subnet Configuration Object:

    • subnet_name (optional): Name of the subnet. Defaults to $var.name-nat-subnet-$index.
    • ipv4_range (optional): Required for IPV4_ONLY and IPV4_IPV6.
    • stack_type (optional): IPV4_ONLY, IPV4_IPV6, or IPV6_ONLY.
    nat_subnets = [
      {
        name       = "producer-nat-subnet-0"
        stack_type = "IPV4_IPV6"
        ipv4_range = "10.10.20.0/24"
      },
      {
        name       = "producer-nat-subnet-1"
        stack_type = "IPV6_ONLY"
      }
    ]
  12. Understand Firewall Policy Rule Configuration

    main

    Rules are defined within the rules list. Each rule object follows a specific schema and logic:

    Core Rule Attributes

    • priority: A unique positive integer between 0 and 2147483647.
    • direction: Either INGRESS or EGRESS.
    • action: Valid actions include allow, deny, goto_next, apply_security_profile_group, mirror, and do_not_mirror.
      • Note: mirror and do_not_mirror require is_mirroring = true.
    • rule_name: Optional name for the rule.
    • disabled: Optional boolean to disable the rule.
    • enable_logging: Optional boolean to enable logging.
    • target_secure_tags vs target_service_accounts: You cannot set both. Providing both will result in an error.

    Match Criteria Logic

    • For INGRESS policies: dest_fqdns, dest_region_codes, dest_threat_intelligences, and dest_address_groups are ignored.
    • For EGRESS policies: src_fqdns, src_region_codes, src_threat_intelligences, and src_address_groups are ignored.

    Layer 4 Configuration

    layer4_configs is a list of objects used to specify protocols and ports:

    • ip_protocol: Required. Can be a well-known string (tcp, udp, icmp, esp, ah, ipip, sctp) or an IP protocol number. Defaults to all.
    • ports: Optional list of strings (integers or ranges like 8081-8085). Only applicable for UDP or TCP protocols.
    {
      priority                = 1
      direction               = "INGRESS"
      action                  = "allow"
      rule_name               = "my-test-policy"
      disabled                = false
      description             = "My test firewall policy"
      enable_logging          = true
      target_secure_tags      = ["tagValues/${google_tags_tag_value.tag_value.name}"]
      target_service_accounts = ["fw-test-svc-acct@$my-project-id.iam.gserviceaccount.com"]
      match = {
        src_ip_ranges             = ["10.100.0.2"]
        src_fqdns                 = []
        src_region_codes          = []
        src_secure_tags           = []
        src_address_groups        = []
        dest_ip_ranges            = ["10.100.100.2"]
        dest_fqdns                = []
        dest_region_codes         = []
        dest_threat_intelligences = []
        dest_address_groups       = []
        layer4_configs = [
          {
            ip_protocol = "tcp"
            ports       = ["80", "8080", "8081-8085"]
          },
        ]
      }
      is_mirroring = false
      tls_inspect = null
      security_profile_group_id = null
    }