使用虛擬私有雲防火牆規則

本頁說明設定虛擬私有雲 (VPC) 防火牆規則的正確指令,並提供使用範例。虛擬私有雲防火牆規則可根據連接埠號碼、標記或通訊協定,允許或拒絕虛擬私有雲網路中虛擬機器 (VM) 執行個體的往來流量。

事前準備

如要進一步瞭解虛擬私有雲防火牆規則,例如預設網路的隱含規則和系統產生的規則,請參閱「虛擬私有雲防火牆規則」。

設定防火牆規則前,請先查看防火牆規則組成部分,熟悉 Google Cloud中使用的防火牆元件。

建立虛擬私有雲防火牆規則

虛擬私有雲防火牆規則是在網路層級定義,且僅會套用到規則建立時所在的網路。不過,您為各個防火牆規則選擇的名稱在專案內必須為專屬名稱。

防火牆規則可包含 IPv4 或 IPv6 範圍,但不能同時包含兩者。

建立防火牆規則時,您可以選擇啟用防火牆規則記錄。啟用記錄功能後,您可以省略中繼資料欄位,以節省儲存費用。詳情請參閱「使用虛擬私有雲防火牆規則記錄」。

如要為目標或來源服務帳戶欄位指定多個服務帳戶,請使用 Google Cloud CLI、API 或用戶端程式庫。

預設網路會在建立時提供自動防火牆規則。如果您使用 Google Cloud 控制台,在建立自訂和自動模式網路時,可以輕鬆建立類似的防火牆。如果您使用 gcloud CLI 或 API,並想建立與預設網路提供的防火牆規則類似的規則,請參閱「設定常見用途的防火牆規則」。

控制台

  1. 前往 Google Cloud 控制台的「Firewall policies」(防火牆政策) 頁面。

    前往「Firewall policies」(防火牆政策)

  2. 按一下「Create firewall rule」(建立防火牆規則)

  3. 輸入防火牆規則的「Name」(名稱)

    此名稱在專案中不得重複。

  4. (選用) 您可以啟用防火牆規則記錄

    • 按一下 [Logs] (記錄) > [On] (啟用)
    • 如要省略中繼資料,請按一下「顯示記錄詳細資料」,然後取消勾選「包含中繼資料」核取方塊。
  5. 指定防火牆規則的「Network」(網路)

  6. 指定規則的「優先順序」

    數值越低,優先順序越高。

  7. 針對「Direction of traffic」(流量方向),選擇輸入或輸出。

  8. 針對「Action on match」(相符時執行的動作),選擇允許或拒絕。

  9. 指定規則的「Targets」(目標)

    • 如要將規則套用到網路中的所有執行個體,請選擇 All instances in the network
    • 如要根據網路 (目標) 標記將規則套用到特定執行個體,請選擇「指定的目標標記」,接著在「目標標記」欄位中,輸入要套用規則的標記。
    • 如要讓規則套用至與特定服務帳戶相關聯的執行個體,請選擇「Specified service account」(指定服務帳戶),在「Service account scope」(服務帳戶範圍) 中指出服務帳戶是位於目前專案還是其他專案,然後在「Target service account」(目標服務帳戶) 欄位中選擇或輸入服務帳戶名稱。
  10. 針對輸入規則,指定「Source filter」(來源篩選器)

    • 如要依來源 IPv4 範圍篩選傳入流量,請選取「IPv4 範圍」,然後在「來源 IPv4 範圍」欄位中輸入 CIDR 區塊。針對任何 IPv4 來源使用「0.0.0.0/0」。
    • 如要依來源 IPv6 範圍篩選傳入流量,請選取「IPv6 範圍」,然後在「來源 IPv6 範圍」欄位中輸入 CIDR 區塊。如為任何 IPv6 來源,請使用 ::/0
    • 如要依網路標記篩選傳入流量,請選擇「來源標記」,然後在「來源標記」欄位中輸入網路標記。如需瞭解來源標記數量限制,請參閱「每個網路的限制」。只有在目標「並非」以服務帳戶指定時,才可依據來源標記進行篩選。
    • 如要依服務帳戶篩選傳入流量,請選擇「Service account」(服務帳戶),並在「Service account scope」(服務帳戶範圍) 底下,指示服務帳戶是位於目前專案還是其他專案,接著在「Source service account」(來源服務帳戶) 欄位中選擇或輸入服務帳戶名稱。只有在目標「並非」以網路標記指定時,才可依據來源服務帳戶進行篩選。
    • 必要時,可以指定「Second source filter」(次要來源篩選器)。次要來源篩選器無法使用與主要來源篩選器相同的篩選條件。來源 IP 範圍可與來源標記來源服務帳戶搭配使用。有效的來源集是來源範圍 IP 位址以及使用網路標記或服務帳戶標示的執行個體的聯集。也就是說,如果來源 IP 範圍「或」來源標記 (或來源服務帳戶) 符合篩選條件,來源就會納入有效來源集。
    • 來源標記來源服務帳戶無法同時使用。

    如要進一步瞭解如何使用服務帳戶和網路標記,請參閱依服務帳戶篩選與依網路標記篩選的比較

  11. 針對輸入規則,指定「Destination filter」(目的地篩選器)

    • 如要依目的地 IPv4 範圍篩選傳入流量,請選取「IPv4 範圍」,並在「目的地 IPv4 範圍」欄位中輸入 CIDR 區塊。針對任何 IPv4 目的地使用 0.0.0.0/0
    • 如要依目的地 IPv6 範圍篩選傳入流量,請選取「IPv6 範圍」,並在「目的地 IPv6 範圍」欄位中輸入 CIDR 區塊。針對任何 IPv6 目的地使用 ::/0

    詳情請參閱「輸入規則目的地」。

  12. 針對輸出規則,指定「Destination filter」(目的地篩選器)

    • 如要依目的地 IPv4 範圍篩選傳出流量,請選取「IPv4 範圍」,並在「目的地 IPv4 範圍」欄位中輸入 CIDR 區塊。針對任何 IPv4 目的地使用 0.0.0.0/0
    • 如要依目的地 IPv6 範圍篩選傳出流量,請選取「IPv6 範圍」,並在「目的地 IPv6 範圍」欄位中輸入 CIDR 區塊。針對任何 IPv6 目的地使用 ::/0

    詳情請參閱「輸出規則目的地」。

  13. 針對輸出規則,指定「Source filter」(來源篩選器)

    • 如要依來源 IPv4 範圍篩選傳出流量,請選取「IPv4 ranges」(IPv4 範圍),並在「Source IPv4 ranges」(來源 IPv4 範圍) 欄位中輸入 CIDR 區塊。針對任何 IPv4 來源使用「0.0.0.0/0」。
    • 如要依來源 IPv6 範圍篩選傳出流量,請選取「IPv6 範圍」,並在「來源 IPv6 範圍」欄位中輸入 CIDR 區塊。針對任何 IPv6 目的地使用 ::/0

    詳情請參閱「輸出規則來源」。

  14. 定義要套用規則的「Protocols and ports」(通訊協定和通訊埠)

    • 如要將規則套用到所有通訊協定和目的地通訊埠,請根據要採取的動作選取「Allow all」(允許所有) 或「Deny all」(全部拒絕)
    • 如要定義特定通訊協定和目的地通訊埠,請選取「指定的通訊協定和通訊埠」
      • 選取「TCP」TCP以包含 TCP 通訊協定和目的地通訊埠。輸入 all 或以半形逗號分隔的目的地通訊埠清單,例如 20-22, 80, 8080
      • 選取「UDP」UDP以包含 UDP 通訊協定和目的地通訊埠。輸入 all 或以半形逗號分隔的目的地通訊埠清單,例如 67-69, 123
      • 選取「其他」,即可加入 icmpsctp 等通訊協定或通訊協定編號。舉例來說,使用 icmp 或通訊協定編號 1 代表 IPv4 ICMP。使用通訊協定編號 58,適用於 IPv6 ICMP。

    詳情請參閱「通訊協定和目的地通訊埠」。

  15. (選用) 您可以將防火牆規則的強制執行狀態設為已停用,如此一來,您就能在不強制執行防火牆規則的情況下建立規則。按一下「停用規則」,然後選取「已停用」

  16. 點選「建立」

gcloud

如要建立 VPC 防火牆規則,請使用 gcloud compute firewall-rules create 指令:

gcloud compute firewall-rules create RULE_NAME \
    [--network NETWORK; default="default"] \
    [--priority PRIORITY;default=1000] \
    [--direction (ingress|egress|in|out); default="ingress"] \
    [--action (deny | allow )] \
    [--target-tags TAG[,TAG,...]] \
    [--target-service-accounts=IAM_SERVICE_ACCOUNT[,IAM_SERVICE_ACCOUNT,...]] \
    [--source-ranges CIDR_RANGE[,CIDR_RANGE,...]] \
    [--source-tags TAG[,TAG, ...]] \
    [--source-service-accounts=IAM_SERVICE_ACCOUNT[,IAM_SERVICE_ACCOUNT,...]] \
    [--destination-ranges CIDR_RANGE[,CIDR_RANGE,...]] \
    [--rules (PROTOCOL[:PORT[-PORT]],[PROTOCOL[:PORT[-PORT]],...]] | all ) \
    [--disabled | --no-disabled] \
    [--enable-logging | --no-enable-logging] \
    [--logging-metadata LOGGING_METADATA]

請依照以下說明的方式來使用參數。如要進一步瞭解每個參數,請參閱 SDK 參考資料說明文件

  • --network 規則的網路。如果省略此參數,系統會在 default 網路中建立規則。如果您沒有預設網路,或想在特定網路中建立規則,就必須使用這個欄位。
  • --priority:代表規則優先順序的數值。數值越低,優先順序越高。
  • --direction 流量方向INGRESSEGRESS 擇一。
  • --action相符時執行的動作allowdeny 擇一。必須與 --rules 旗標搭配使用。
  • 指定目標的方式有下列幾種:
    • 如果規則應套用到網路中的所有目標,請省略 --target-tags--target-service-accounts
    • 使用 --target-tags 標記,根據網路標記定義目標
    • 使用 --target-service-accounts 旗標,根據關聯服務帳戶定義目標
  • 如果是輸入規則,如要進一步調整目的地,請使用 --destination-ranges 以 CIDR 格式指定 IPv4 或 IPv6 位址範圍。如果省略 --destination-ranges,則輸入目的地為任何 IPv4 位址 0.0.0.0/0。詳情請參閱「輸入規則的目標」和「輸入規則的目標和 IP 位址」。

  • 針對輸入規則,指定來源

    • --source-ranges 使用這個標記指定 CIDR 格式的來源 IPv4 或 IPv6 位址範圍。
    • 如果省略 --source-rangessource-tags--source-service-accounts,則傳入來源為任何 IPv4 位址 0.0.0.0/0
    • --source-tags 使用這個標記以透過網路標記來指定來源執行個體。只有在目標「並非」以服務帳戶指定時,才可依據來源標記進行篩選。詳情請參閱依服務帳戶篩選與依網路標記篩選的比較
    • --source-ranges--source-tags 可以「一起」使用。如果兩者都有指定,則有效的來源設定會「結合」來源範圍 IP 位址以及使用網路標記標示的執行個體,即使受到標記的執行個體在來源範圍中沒有 IP 也是如此。
    • --source-service-accounts 使用此標記來根據執行個體使用的服務帳戶指定執行個體。只有在目標「並非」以網路標記指定時,才可依據來源服務帳戶進行篩選。詳情請參閱依服務帳戶篩選與依網路標記篩選的比較--source-ranges--source-service-accounts 可以「一起」使用。如果兩者都有指定,則有效的來源集會是來源範圍 IP 位址以及使用來源服務帳戶標示的執行個體的聯集,即使使用來源服務帳戶標示的執行個體在來源範圍中沒有 IP 也是如此。
  • 如果是輸出規則,如要進一步調整來源,請使用 --source-ranges 以 CIDR 格式指定 IPv4 或 IPv6 位址範圍。如果省略 --source-ranges ,則輸出來源為任何 IPv4 位址 0.0.0.0/0。詳情請參閱「輸出規則的來源」和「輸出規則的目標和 IP 位址」。

  • 針對輸出規則,指定目的地

    • --destination-ranges 使用這個標記指定 CIDR 格式的目的地 IPv4 或 IPv6 位址範圍。
    • 如果省略 --destination-ranges,輸出目的地就是任何 IPv4 位址 0.0.0.0/0
  • --rules:要套用規則的通訊協定和目的地通訊埠清單。使用 all 可讓規則適用於所有通訊協定和所有目的地通訊埠。需要 --action 旗標。

  • 根據預設,防火牆規則建立後會自動強制執行,不過您可以變更這項行為。

    • 如果同時省略 --disabled--no-disabled,會建立並強制執行防火牆規則。
    • --disabled:加入此標記可在不強制執行防火牆規則的情況下建立規則。除非您更新防火牆規則,將狀態變更為啟用,否則防火牆規則將維持停用狀態。
    • --no-disabled 加入此標記可確保強制執行防火牆規則。
  • --enable-logging | --no-enable-logging 您可以在建立或更新防火牆規則時啟用防火牆規則記錄。虛擬私有雲防火牆規則記錄可讓您稽核、驗證及分析防火牆規則的效果。詳情請參閱「虛擬私有雲防火牆規則記錄」。

    • --logging-metadata 啟用記錄功能後,防火牆規則記錄功能預設會納入基礎和中繼資料欄位。您可以省略中繼資料欄位,以節省儲存費用。詳情請參閱「使用虛擬私有雲防火牆規則記錄」。

Terraform

如要建立防火牆規則,可以使用 google_compute_firewall 資源

resource "google_compute_firewall" "rules" {
  name        = "my-firewall-rule"
  network     = "default"
  description = "Creates firewall rule targeting tagged instances"

  allow {
    protocol = "tcp"
    ports    = ["80", "443"]
  }

  source_ranges = ["0.0.0.0/0"]
  target_tags   = ["web"]
}

如要瞭解如何套用或移除 Terraform 設定,請參閱「基本 Terraform 指令」。

API

建立虛擬私有雲防火牆規則。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls
{
  "name": "RULE_NAME",
  "network": "projects/PROJECT-ID/global/networks/NETWORK",
  ... other fields
}

更改下列內容:

  • PROJECT_ID:虛擬私有雲網路所在的專案 ID。
  • NETWORK:建立防火牆規則的虛擬私有雲網路名稱。
  • RULE_NAME:防火牆規則的名稱。

  • 針對輸入防火牆規則,指定輸入來源和目的地:

    • 使用 sourceRangessourceTagssourceServiceAccounts 欄位指定進入來源。

    • sourceRanges 可以是 IPv4 或 IPv6 範圍,但不得同時包含兩者。如要使用 0.0.0.0/0 範圍,請勿指定任何欄位。

    • 您無法同時使用 sourceTagssourceServiceAccounts 欄位。不過,您可以搭配 sourceTagssourceServiceAccounts 使用 sourceRanges。如果有的話,連線只要符合其中一項,就會套用防火牆規則。

    • 如果是目標欄位,使用 sourceTags 欄位時,就不能使用 targetServiceAccounts 欄位。您必須使用 targetTags 欄位或不使用目標欄位。同樣地,如果您使用 sourceServiceAccounts 欄位,就無法使用 targetTags 欄位。如未指定目標欄位,規則會套用至網路中的所有目標。

    • 使用 destinationRanges 欄位指定連入目的地。destinationRanges 可以是 IPv4 或 IPv6 範圍,但不能同時包含兩者。
      如未指定目的地, Google Cloud 會使用 0.0.0.0/0。詳情請參閱「輸入規則目的地」和「輸入規則的目標和 IP 位址」。

  • 針對輸出防火牆規則,請指定輸出來源和目的地:

    • 使用 sourceRanges 欄位指定輸出來源。sourceRange 可以是 IPv4 或 IPv6 範圍,但不能同時包含兩者。
      如未指定來源, Google Cloud 會使用 0.0.0.0/0。 詳情請參閱「輸出規則的來源」和「輸出規則的目標和 IP 位址」。

    • 使用 destinationRanges 欄位指定目的地。destinationRanges 可以是 IPv4 或 IPv6 範圍,但不能同時包含兩者。
      如未指定目的地, Google Cloud會使用 0.0.0.0/0。使用 targetTagstargetServiceAccounts 欄位,指定規則適用的目標。如未指定目標欄位,規則會套用至網路中的所有目標。

如要進一步瞭解每個欄位,請參閱 firewalls.insert 方法。

C#


using Google.Cloud.Compute.V1;
using System.Threading.Tasks;

public class CreateFirewallRuleAsyncSample
{
    public async Task CreateFirewallRuleAsync(
        // TODO(developer): Set your own default values for these parameters or pass different values when calling this method.
        string projectId = "your-project-id",
        string firewallRuleName = "my-test-firewall-rule",
        // Name of the network the rule will be applied to. Some available name formats:
        // projects/{project_id}/global/networks/{network}
        // global/networks/{network}
        string networkName = "global/networks/default")
    {
        Firewall firewallRule = new Firewall
        {
            Name = firewallRuleName,
            Network = networkName,
            Direction = ComputeEnumConstants.Firewall.Direction.Ingress,
            Allowed =
            {
                new Allowed
                {
                    Ports = { "80", "443" },
                    IPProtocol = "tcp"
                }
            },
            TargetTags = { "web" },
            Description = "Allows TCP traffic on port 80 and 443 from anywhere."
        };

        // Note that the default value of priority for the firewall API is 1000.
        // If you check the value of firewallRule.Priority at this point it
        // will be equal to 0, however it is not treated as "set" by the library, and thus
        // the default will be applied to the new rule. If you want to create a rule that
        // has priority == 0, you'll need to explicitly set it: firewallRule.Priority = 0.
        // You can use the firewallRule.HasPriority property to check if the priority has been set.
        // You can use the firewallRule.ClearPriority() method to unset the priority.

        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        FirewallsClient client = await FirewallsClient.CreateAsync();

        // Create the firewall rule in the specified project.
        var firewallRuleCreation = await client.InsertAsync(projectId, firewallRule);

        // Wait for the operation to complete using client-side polling.
        await firewallRuleCreation.PollUntilCompletedAsync();
    }
}

Go

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
	"google.golang.org/protobuf/proto"
)

// createFirewallRule creates a firewall rule allowing for incoming HTTP and HTTPS access from the entire Internet.
func createFirewallRule(w io.Writer, projectID, firewallRuleName, networkName string) error {
	// projectID := "your_project_id"
	// firewallRuleName := "europe-central2-b"
	// networkName := "global/networks/default"

	ctx := context.Background()
	firewallsClient, err := compute.NewFirewallsRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer firewallsClient.Close()

	firewallRule := &computepb.Firewall{
		Allowed: []*computepb.Allowed{
			{
				IPProtocol: proto.String("tcp"),
				Ports:      []string{"80", "443"},
			},
		},
		Direction: proto.String(computepb.Firewall_INGRESS.String()),
		Name:      &firewallRuleName,
		TargetTags: []string{
			"web",
		},
		Network:     &networkName,
		Description: proto.String("Allowing TCP traffic on port 80 and 443 from Internet."),
	}

	// Note that the default value of priority for the firewall API is 1000.
	// If you check the value of `firewallRule.GetPriority()` at this point it
	// will be equal to 0, however it is not treated as "set" by the library and thus
	// the default will be applied to the new rule. If you want to create a rule that
	// has priority == 0, you need to explicitly set it so:

	// firewallRule.Priority = proto.Int32(0)

	req := &computepb.InsertFirewallRequest{
		Project:          projectID,
		FirewallResource: firewallRule,
	}

	op, err := firewallsClient.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create firewall rule: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Firewall rule created\n")

	return nil
}

Java


import com.google.cloud.compute.v1.Allowed;
import com.google.cloud.compute.v1.Firewall;
import com.google.cloud.compute.v1.Firewall.Direction;
import com.google.cloud.compute.v1.FirewallsClient;
import com.google.cloud.compute.v1.InsertFirewallRequest;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateFirewallRule {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample
    /* project: project ID or project number of the Cloud project you want to use.
       firewallRuleName: name of the rule that is created.
       network: name of the network the rule will be applied to. Available name formats:
        * https://www.googleapis.com/compute/v1/projects/{project_id}/global/networks/{network}
        * projects/{project_id}/global/networks/{network}
        * global/networks/{network} */
    String project = "your-project-id";
    String firewallRuleName = "firewall-rule-name-" + UUID.randomUUID();
    String network = "global/networks/default";

    // The rule will be created with default priority of 1000.
    createFirewall(project, firewallRuleName, network);
  }

  // Creates a simple firewall rule allowing for incoming HTTP and 
  // HTTPS access from the entire Internet.
  public static void createFirewall(String project, String firewallRuleName, String network)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    /* Initialize client that will be used to send requests. This client only needs to be created
       once, and can be reused for multiple requests. After completing all of your requests, call
       the `firewallsClient.close()` method on the client to safely
       clean up any remaining background resources. */
    try (FirewallsClient firewallsClient = FirewallsClient.create()) {

      // The below firewall rule is created in the default network.
      Firewall firewallRule = Firewall.newBuilder()
          .setName(firewallRuleName)
          .setDirection(Direction.INGRESS.toString())
          .addAllowed(
              Allowed.newBuilder().addPorts("80").addPorts("443").setIPProtocol("tcp").build())
          .addSourceRanges("0.0.0.0/0")
          .setNetwork(network)
          .addTargetTags("web")
          .setDescription("Allowing TCP traffic on port 80 and 443 from Internet.")
          .build();

      /* Note that the default value of priority for the firewall API is 1000.
         If you check the value of `firewallRule.getPriority()` at this point it
         will be equal to 0, however it is not treated as "set" by the library and thus
         the default will be applied to the new rule. If you want to create a rule that
         has priority == 0, you'll need to explicitly set it so: setPriority(0) */

      InsertFirewallRequest insertFirewallRequest = InsertFirewallRequest.newBuilder()
          .setFirewallResource(firewallRule)
          .setProject(project).build();

      firewallsClient.insertAsync(insertFirewallRequest).get(3, TimeUnit.MINUTES);

      System.out.println("Firewall rule created successfully -> " + firewallRuleName);
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const firewallRuleName = 'YOUR_FIREWALL_RULE_NAME'
// const networkName = 'global/networks/default'

const compute = require('@google-cloud/compute');
const computeProtos = compute.protos.google.cloud.compute.v1;

async function createFirewallRule() {
  const firewallsClient = new compute.FirewallsClient();
  const operationsClient = new compute.GlobalOperationsClient();

  const firewallRule = new computeProtos.Firewall();
  firewallRule.name = firewallRuleName;
  firewallRule.direction = 'INGRESS';
  firewallRule.allowed = [
    {
      IPProtocol: 'tcp',
      ports: ['80', '443'],
    },
  ];
  firewallRule.targetTags = ['web'];
  firewallRule.network = networkName;
  firewallRule.description =
    'Allowing TCP traffic on port 80 and 443 from Internet.';

  // Note that the default value of priority for the firewall API is 1000.
  // If you check the value of `firewallRule.priority` at this point it
  // will be equal to null, however it is not treated as "set" by the library and thus
  // the default will be applied to the new rule. If you want to create a rule that
  // has priority == 0, you need to explicitly set it so:

  // firewallRule.priority = 0

  const [response] = await firewallsClient.insert({
    project: projectId,
    firewallResource: firewallRule,
  });
  let operation = response.latestResponse;

  // Wait for the create operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
    });
  }

  console.log('Firewall rule created');
}

createFirewallRule();

PHP

use Google\Cloud\Compute\V1\Allowed;
use Google\Cloud\Compute\V1\Client\FirewallsClient;
use Google\Cloud\Compute\V1\Firewall;
use Google\Cloud\Compute\V1\Firewall\Direction;
use Google\Cloud\Compute\V1\InsertFirewallRequest;

/**
 * Creates a simple firewall rule allowing incoming HTTP and HTTPS access from the entire internet.
 *
 * @param string $projectId Project ID or project number of the Cloud project you want to create a rule for.
 * @param string $firewallRuleName Name of the rule that is created.
 * @param string $network Name of the network the rule will be applied to. Available name formats:
 *                        https://www.googleapis.com/compute/v1/projects/{project_id}/global/networks/{network}
 *                        projects/{project_id}/global/networks/{network}
 *                        global/networks/{network}
 *
 * @throws \Google\ApiCore\ApiException if the remote call fails.
 * @throws \Google\ApiCore\ValidationException if local error occurs before remote call.
 */

function create_firewall_rule(string $projectId, string $firewallRuleName, string $network = 'global/networks/default')
{
    $firewallsClient = new FirewallsClient();
    $allowedPorts = (new Allowed())
      ->setIPProtocol('tcp')
      ->setPorts(['80', '443']);
    $firewallResource = (new Firewall())
      ->setName($firewallRuleName)
      ->setDirection(Direction::name(Direction::INGRESS))
      ->setAllowed([$allowedPorts])
      ->setSourceRanges(['0.0.0.0/0'])
      ->setTargetTags(['web'])
      ->setNetwork($network)
      ->setDescription('Allowing TCP traffic on ports 80 and 443 from Internet.');

    /**
    * Note that the default value of priority for the firewall API is 1000.
    * If you check the value of its priority at this point it will be
    * equal to 0, however it is not treated as "set" by the library and thus
    * the default will be applied to the new rule. If you want to create a rule
    * that has priority == 0, you need to explicitly set it so:
    *
    *   $firewallResource->setPriority(0);
    */

    //Create the firewall rule using Firewalls Client.
    $request = (new InsertFirewallRequest())
        ->setFirewallResource($firewallResource)
        ->setProject($projectId);
    $operation = $firewallsClient->insert($request);

    // Wait for the operation to complete.
    $operation->pollUntilComplete();
    if ($operation->operationSucceeded()) {
        printf('Created rule %s.' . PHP_EOL, $firewallRuleName);
    } else {
        $error = $operation->getError();
        printf('Firewall rule creation failed: %s' . PHP_EOL, $error?->getMessage());
    }
}

Python

from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    if operation.error_code:
        print(
            f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
            file=sys.stderr,
            flush=True,
        )
        print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def create_firewall_rule(
    project_id: str, firewall_rule_name: str, network: str = "global/networks/default"
) -> compute_v1.Firewall:
    """
    Creates a simple firewall rule allowing for incoming HTTP and HTTPS access from the entire Internet.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        firewall_rule_name: name of the rule that is created.
        network: name of the network the rule will be applied to. Available name formats:
            * https://www.googleapis.com/compute/v1/projects/{project_id}/global/networks/{network}
            * projects/{project_id}/global/networks/{network}
            * global/networks/{network}

    Returns:
        A Firewall object.
    """
    firewall_rule = compute_v1.Firewall()
    firewall_rule.name = firewall_rule_name
    firewall_rule.direction = "INGRESS"

    allowed_ports = compute_v1.Allowed()
    allowed_ports.I_p_protocol = "tcp"
    allowed_ports.ports = ["80", "443"]

    firewall_rule.allowed = [allowed_ports]
    firewall_rule.source_ranges = ["0.0.0.0/0"]
    firewall_rule.network = network
    firewall_rule.description = "Allowing TCP traffic on port 80 and 443 from Internet."

    firewall_rule.target_tags = ["web"]

    # Note that the default value of priority for the firewall API is 1000.
    # If you check the value of `firewall_rule.priority` at this point it
    # will be equal to 0, however it is not treated as "set" by the library and thus
    # the default will be applied to the new rule. If you want to create a rule that
    # has priority == 0, you need to explicitly set it so:
    # TODO: Uncomment to set the priority to 0
    # firewall_rule.priority = 0

    firewall_client = compute_v1.FirewallsClient()
    operation = firewall_client.insert(
        project=project_id, firewall_resource=firewall_rule
    )

    wait_for_extended_operation(operation, "firewall rule creation")

    return firewall_client.get(project=project_id, firewall=firewall_rule_name)

Ruby


require "google/cloud/compute/v1"

# Creates a simple firewall rule allowing for incoming HTTP and HTTPS access from the entire Internet.
#
# @param [String] project project ID or project number of the Cloud project you want to use.
# @param [String] name: name of the rule that is created.
# @param network: name of the network the rule will be applied to. Available name formats:
#         * https://www.googleapis.com/compute/v1/projects/{project_id}/global/networks/{network}
#         * projects/{project_id}/global/networks/{network}
#         * global/networks/{network}
def create_firewall_rule project:, name:, network: "global/networks/default"
  rule = {
    name: name,
    direction: "INGRESS",
    allowed: [{
      I_p_protocol: "tcp",
      ports: ["80", "443"]
    }],
    source_ranges: ["0.0.0.0/0"],
    network: network,
    description: