Menggunakan aturan firewall VPC

Halaman ini menjelaskan perintah untuk mengelola aturan firewall Virtual Private Cloud (VPC) dan memberikan beberapa contoh cara menggunakannya. Aturan firewall VPC memungkinkan Anda mengizinkan atau menolak traffic ke atau dari instance virtual machine (VM) di jaringan VPC berdasarkan nomor port, tag, atau protokol.

Sebelum memulai

Untuk mempelajari lebih lanjut aturan firewall VPC, seperti aturan implisit dan aturan yang dibuat sistem untuk jaringan default, lihat Aturan firewall VPC.

Sebelum mengonfigurasi aturan firewall, tinjau komponen aturan firewall untuk memahami komponen firewall yang digunakan di Google Cloud.

Membuat aturan firewall VPC

Aturan firewall VPC ditentukan di tingkat jaringan, dan hanya berlaku untuk jaringan tempat aturan tersebut dibuat; namun, nama yang Anda pilih untuk setiap aturan harus unik untuk project.

Aturan firewall dapat berisi rentang IPv4 atau IPv6, tetapi tidak keduanya.

Saat membuat aturan firewall, Anda dapat memilih untuk mengaktifkan Logging Aturan Firewall. Jika mengaktifkan logging, Anda dapat menghilangkan kolom metadata untuk menghemat biaya penyimpanan. Untuk mengetahui informasi selengkapnya, lihat Menggunakan logging aturan firewall VPC.

Jika Anda ingin menentukan beberapa akun layanan untuk kolom akun layanan target atau sumber, gunakan Google Cloud CLI, API, atau library klien.

Jaringan default menyediakan aturan firewall otomatis pada saat pembuatan. Jaringan mode kustom dan otomatis memungkinkan Anda membuat firewall serupa dengan mudah selama pembuatan jaringan jika Anda menggunakan konsol Google Cloud . Jika Anda menggunakan gcloud CLI atau API dan ingin membuat aturan firewall yang serupa dengan aturan yang disediakan oleh jaringan default, lihat Mengonfigurasi aturan firewall untuk kasus penggunaan umum.

Konsol

  1. Di konsol Google Cloud , buka halaman Firewall policies.

    Buka Firewall policies

  2. Klik Create firewall rule.

  3. Masukkan Name untuk aturan firewall.

    Nama ini harus unik untuk project.

  4. (Opsional) Anda dapat mengaktifkan logging aturan firewall:

    • Klik Logs > On.
    • Untuk menghilangkan metadata, klik Tampilkan detail log, lalu hapus centang pada kotak Sertakan metadata.
  5. Tentukan Network untuk aturan firewall.

  6. Tentukan Priority aturan.

    Semakin rendah angkanya, semakin tinggi prioritasnya.

  7. Untuk Direction of traffic, pilih ingress atau egress.

  8. Untuk Action on match, pilih izinkan atau tolak.

  9. Tentukan Target aturan.

    • Jika Anda ingin aturan berlaku untuk semua instance di jaringan, pilih All instances in the network.
    • Jika Anda ingin aturan diterapkan ke instance tertentu berdasarkan tag jaringan (target), pilih Specified target tags, lalu di kolom Target tags, ketik tag yang harus diterapkan aturan.
    • Jika Anda ingin aturan diterapkan ke instance tertentu berdasarkan akun layanan terkait, pilih Akun layanan tertentu, tunjukkan apakah akun layanan berada di project saat ini atau di project lain di Cakupan akun layanan, lalu di kolom Akun layanan target, pilih atau ketik nama akun layanan.
  10. Untuk aturan ingress, tentukan Source filter:

    • Untuk memfilter traffic masuk menurut rentang IPv4 sumber, pilih Rentang IPv4, lalu masukkan blok CIDR ke dalam kolom Rentang IPv4 sumber. Gunakan 0.0.0.0/0 untuk sumber IPv4 apa pun.
    • Untuk memfilter traffic masuk menurut rentang IPv6 sumber, pilih IPv6 ranges, lalu masukkan blok CIDR ke kolom Source IPv6 ranges. Gunakan ::/0 untuk sumber IPv6 apa pun.
    • Untuk memfilter traffic masuk menurut tag jaringan, pilih Tag sumber, lalu ketik tag jaringan ke dalam kolom Tag sumber. Untuk mengetahui batas jumlah tag sumber, lihat Batas per jaringan. Pemfilteran menurut tag sumber hanya tersedia jika target tidak ditentukan oleh akun layanan.
    • Untuk memfilter traffic masuk menurut akun layanan, pilih Akun layanan, tunjukkan apakah akun layanan berada di project saat ini atau di project lain dalam Cakupan akun layanan, lalu pilih atau ketik nama akun layanan di kolom Akun layanan sumber. Pemfilteran menurut akun layanan sumber hanya tersedia jika target tidak ditentukan oleh tag jaringan.
    • Tentukan Filter sumber kedua jika diinginkan. Filter sumber sekunder tidak dapat menggunakan kriteria filter yang sama dengan filter utama. Rentang IP sumber dapat digunakan bersama dengan Tag sumber atau Akun layanan sumber. Kumpulan sumber efektif adalah gabungan alamat IP rentang sumber dan instance yang diidentifikasi oleh tag jaringan atau akun layanan. Artinya, jika rentang IP sumber, atau tag sumber (atau akun layanan sumber) cocok dengan kriteria filter, sumber akan disertakan dalam set sumber efektif.
    • Tag sumber dan Akun layanan sumber tidak dapat digunakan bersama-sama.

    Untuk mengetahui informasi selengkapnya tentang penggunaan akun layanan dan tag jaringan, lihat memfilter berdasarkan akun layanan versus tag jaringan.

  11. Untuk aturan ingress, tentukan Filter tujuan:

    • Untuk memfilter traffic masuk menurut rentang IPv4 tujuan, pilih Rentang IPv4 dan masukkan blok CIDR ke dalam kolom Rentang IPv4 tujuan. Gunakan 0.0.0.0/0 untuk tujuan IPv4 apa pun.
    • Untuk memfilter traffic masuk menurut rentang IPv6 tujuan, pilih IPv6 ranges dan masukkan blok CIDR ke dalam kolom Destination IPv6 ranges. Gunakan ::/0 untuk tujuan IPv6 apa pun.

    Untuk mengetahui informasi selengkapnya, lihat Tujuan untuk aturan ingress.

  12. Untuk aturan keluar, tentukan Filter tujuan:

    • Untuk memfilter traffic keluar menurut rentang IPv4 tujuan, pilih Rentang IPv4 dan masukkan blok CIDR ke dalam kolom Rentang IPv4 tujuan. Gunakan 0.0.0.0/0 untuk tujuan IPv4 apa pun.
    • Untuk memfilter traffic keluar menurut rentang IPv6 tujuan, pilih IPv6 ranges dan masukkan blok CIDR ke dalam kolom Destination IPv6 ranges. Gunakan ::/0 untuk tujuan IPv6 apa pun.

    Untuk mengetahui informasi selengkapnya, lihat Tujuan untuk aturan egress.

  13. Untuk aturan keluar, tentukan Source filter:

    • Untuk memfilter traffic keluar menurut rentang IPv4 sumber, pilih Rentang IPv4 dan masukkan blok CIDR ke dalam kolom Rentang IPv4 sumber. Gunakan 0.0.0.0/0 untuk sumber IPv4 apa pun.
    • Untuk memfilter traffic keluar menurut rentang IPv6 sumber, pilih Rentang IPv6 dan masukkan blok CIDR ke dalam kolom Rentang IPv6 sumber. Gunakan ::/0 untuk tujuan IPv6 apa pun.

    Untuk mengetahui informasi selengkapnya, lihat Sumber untuk aturan egress.

  14. Tentukan Protocols and ports yang akan diterapkan aturan:

    • Agar aturan berlaku untuk semua protokol dan port tujuan, pilih Izinkan semua atau Tolak semua, bergantung pada tindakan.
    • Untuk menentukan protokol dan port tujuan tertentu, pilih Specified protocols and ports:
      • Pilih TCP untuk menyertakan protokol TCP dan port tujuan. Masukkan all atau daftar port tujuan yang dipisahkan koma, seperti 20-22, 80, 8080.
      • Pilih UDP untuk menyertakan protokol UDP dan port tujuan. Masukkan all atau daftar port tujuan yang dipisahkan koma, seperti 67-69, 123.
      • Pilih Lainnya untuk menyertakan protokol seperti icmp, sctp, atau nomor protokol. Misalnya, gunakan icmp atau nomor protokol 1 untuk ICMP IPv4. Gunakan nomor protokol 58 untuk ICMP IPv6.

    Untuk mengetahui informasi selengkapnya, lihat protokol dan port tujuan.

  15. (Opsional) Anda dapat membuat aturan firewall, tetapi tidak menerapkannya dengan menyetel status penerapannya ke nonaktif. Klik Nonaktifkan aturan, lalu pilih Dinonaktifkan.

  16. Klik Create.

gcloud

Untuk membuat aturan firewall VPC, gunakan perintah 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]

Gunakan parameter sebagai berikut. Detail selengkapnya tentang setiap opsi tersedia dalam dokumentasi referensi SDK.

  • --network Jaringan untuk aturan. Jika tidak ditentukan, aturan akan dibuat di jaringan default. Jika Anda tidak memiliki jaringan default atau ingin membuat aturan di jaringan tertentu, Anda harus menggunakan kolom ini.
  • --priority Nilai numerik yang menunjukkan prioritas untuk aturan. Semakin rendah angkanya, semakin tinggi prioritasnya.
  • --direction Arah traffic, INGRESS atau EGRESS.
  • --action Tindakan jika ada kecocokan, allow atau deny. Harus digunakan dengan flag --rules.
  • Tentukan target dengan salah satu cara berikut:
    • Hapus --target-tags dan --target-service-accounts jika aturan harus berlaku untuk semua target dalam jaringan.
    • Gunakan flag --target-tags untuk menentukan target menurut tag jaringan.
    • Gunakan flag --target-service-accounts untuk menentukan target menurut akun layanan terkait.
  • Untuk aturan ingress, guna lebih menyempurnakan tujuan, gunakan --destination-ranges untuk menentukan rentang alamat IPv4 atau IPv6 dalam format CIDR. Jika --destination-ranges tidak disertakan, tujuan ingress adalah alamat IPv4 apa pun, 0.0.0.0/0. Untuk mengetahui informasi selengkapnya, lihat Tujuan untuk aturan ingress dan Target dan alamat IP untuk aturan ingress.

  • Untuk aturan ingress, tentukan sumber:

    • --source-ranges Gunakan tanda ini untuk menentukan rentang alamat IPv4 atau IPv6 sumber dalam format CIDR.
    • Jika --source-ranges, source-tags, dan --source-service-accounts dihilangkan, sumber ingress adalah alamat IPv4 apa pun, 0.0.0.0/0.
    • --source-tags Gunakan flag ini untuk menentukan instance sumber menurut tag jaringan. Pemfilteran menurut tag sumber hanya tersedia jika target tidak ditentukan oleh akun layanan. Untuk mengetahui informasi selengkapnya, lihat memfilter berdasarkan akun layanan versus tag jaringan.
    • --source-ranges dan --source-tags dapat digunakan bersama-sama. Jika keduanya ditentukan, set sumber yang efektif adalah gabungan alamat IP rentang sumber dan instance yang diidentifikasi oleh tag jaringan, meskipun instance yang diberi tag tidak memiliki IP dalam rentang sumber.
    • --source-service-accounts Gunakan flag ini untuk menentukan instance berdasarkan akun layanan yang mereka gunakan. Pemfilteran menurut akun layanan sumber hanya tersedia jika target tidak ditentukan oleh tag jaringan. Untuk mengetahui informasi selengkapnya, lihat memfilter berdasarkan akun layanan versus tag jaringan. --source-ranges dan --source-service-accounts dapat digunakan bersama-sama. Jika keduanya ditentukan, set sumber yang efektif adalah gabungan alamat IP rentang sumber dan instance yang diidentifikasi oleh akun layanan sumber, meskipun instance yang diidentifikasi oleh akun layanan sumber tidak memiliki IP dalam rentang sumber.
  • Untuk aturan keluar, guna lebih menyaring sumber, gunakan --source-ranges untuk menentukan rentang alamat IPv4 atau IPv6 dalam format CIDR. Jika --source-ranges dihilangkan, sumber keluar adalah alamat IPv4 apa pun, 0.0.0.0/0. Untuk mengetahui informasi selengkapnya, lihat Sumber untuk aturan egress dan Target dan alamat IP untuk aturan egress.

  • Untuk aturan traffic keluar, tentukan tujuan:

    • --destination-ranges Gunakan tanda ini untuk menentukan rentang alamat IPv4 atau IPv6 tujuan dalam format CIDR.
    • Jika --destination-ranges tidak disertakan, tujuan keluar adalah alamat IPv4 apa pun, 0.0.0.0/0.
  • --rules Daftar protokol dan port tujuan yang akan menerapkan aturan tersebut. Gunakan all agar aturan berlaku untuk semua protokol dan semua port tujuan. Memerlukan flag --action.

  • Secara default, aturan firewall dibuat dan diterapkan secara otomatis; namun, Anda dapat mengubah perilaku ini.

    • Jika --disabled dan --no-disabled tidak disertakan, aturan firewall akan dibuat dan diterapkan.
    • --disabled Tambahkan tanda ini untuk membuat aturan firewall, tetapi tidak menerapkannya. Aturan firewall akan tetap dinonaktifkan hingga Anda memperbarui aturan firewall untuk mengaktifkannya.
    • --no-disabled Tambahkan tanda ini untuk memastikan aturan firewall diterapkan.
  • --enable-logging | --no-enable-logging Anda dapat mengaktifkan Logging Aturan Firewall untuk suatu aturan saat Anda membuat atau memperbaruinya. Logging aturan firewall VPC memungkinkan Anda mengaudit, memverifikasi, dan menganalisis efek aturan firewall Anda. Lihat Logging aturan firewall VPC untuk mengetahui detailnya.

    • --logging-metadata Jika Anda mengaktifkan logging, secara default, Logging Aturan Firewall menyertakan kolom dasar dan metadata. Anda dapat menghilangkan kolom metadata untuk menghemat biaya penyimpanan. Untuk mengetahui informasi selengkapnya, lihat Menggunakan logging aturan firewall VPC.

Terraform

Untuk membuat aturan firewall, Anda dapat menggunakan resource 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"]
}

Untuk mempelajari cara menerapkan atau menghapus konfigurasi Terraform, lihat Perintah dasar Terraform.

API

Buat aturan firewall VPC.

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

Ganti kode berikut:

  • PROJECT_ID: ID project tempat jaringan VPC berada.
  • NETWORK: nama jaringan VPC tempat aturan firewall dibuat.
  • RULE_NAME: nama aturan firewall.

  • Untuk aturan firewall masuk, tentukan sumber dan tujuan masuk:

    • Gunakan kolom sourceRanges, sourceTags, atau sourceServiceAccounts untuk menentukan sumber masuk.

    • sourceRanges dapat berupa rentang IPv4 atau IPv6, tetapi tidak boleh merupakan kombinasi keduanya. Untuk menggunakan rentang 0.0.0.0/0, jangan tentukan kolom apa pun.

    • Anda tidak dapat menggunakan kolom sourceTags dan sourceServiceAccounts secara bersamaan. Namun, Anda dapat menggunakan sourceRanges dengan sourceTags atau sourceServiceAccounts. Jika Anda melakukannya, koneksi hanya perlu cocok dengan salah satu dari keduanya agar aturan firewall dapat diterapkan.

    • Untuk kolom target, jika Anda menggunakan kolom sourceTags, Anda tidak dapat menggunakan kolom targetServiceAccounts. Anda harus menggunakan kolom targetTags atau tidak ada kolom target. Demikian pula, jika Anda menggunakan kolom sourceServiceAccounts, Anda tidak dapat menggunakan kolom targetTags. Jika Anda tidak menentukan kolom target, aturan akan berlaku untuk semua target dalam jaringan.

    • Gunakan kolom destinationRanges untuk menentukan tujuan ingress. destinationRanges dapat berupa rentang IPv4 atau IPv6, tetapi tidak dapat berupa kombinasi keduanya.
      Jika Anda tidak menentukan tujuan, Google Cloud akan menggunakan 0.0.0.0/0. Untuk mengetahui informasi selengkapnya, lihat Tujuan untuk aturan ingress dan Target dan alamat IP untuk aturan ingress.

  • Untuk aturan firewall keluar, tentukan sumber dan tujuan keluar:

    • Gunakan kolom sourceRanges untuk menentukan sumber traffic keluar. sourceRange dapat berupa rentang IPv4 atau IPv6, tetapi tidak dapat berupa kombinasi keduanya.
      Jika Anda tidak menentukan sumber, Google Cloud akan menggunakan 0.0.0.0/0. Untuk mengetahui informasi selengkapnya, lihat Sumber untuk aturan egress dan Target dan alamat IP untuk aturan egress.

    • Gunakan kolom destinationRanges untuk menentukan tujuan. destinationRanges dapat berupa rentang IPv4 atau IPv6, tetapi tidak boleh berupa kombinasi keduanya.
      Jika Anda tidak menentukan tujuan, Google Cloud akan menggunakan 0.0.0.0/0. Gunakan kolom targetTags atau targetServiceAccounts untuk menentukan target yang menerapkan aturan. Jika Anda tidak menentukan kolom target, aturan akan berlaku untuk semua target dalam jaringan.

Untuk mengetahui informasi dan deskripsi selengkapnya untuk setiap kolom, lihat metode 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: "Allowing TCP traffic on port 80 and 443 from Internet.",
    target_tags: ["web"]
  }

  # Note that the default value of priority for the firewall API is 1000.
  # If you want to create a rule that has priority == 0, you need to explicitly set it:
  #   rule[:priority] = 0
  # Use `rule.has_key? :priority` to check if the priority has been set.
  # Use `rule.delete :priority` method to unset the priority.

  request = {
    firewall_resource: rule,
    project: project
  }

  client = ::Google::Cloud::Compute::V1::Firewalls::Rest::Client.new
  operation = client.insert request

  wait_until_done operation: operation
end

Memperbarui aturan firewall VPC

Anda dapat mengubah beberapa komponen aturan firewall VPC, seperti protokol dan port tujuan yang ditentukan untuk kondisi kecocokan. Anda tidak dapat mengubah nama, jaringan, tindakan saat kecocokan, dan arah traffic aturan firewall.

Jika Anda perlu mengubah nama, jaringan, atau komponen tindakan atau arah, Anda harus menghapus aturan dan membuat aturan baru.

Jika Anda ingin menambahkan atau menghapus beberapa akun layanan, gunakan gcloud CLI, API, atau library klien. Anda tidak dapat menggunakan konsol Google Cloud untuk menentukan beberapa akun layanan target atau akun layanan sumber.

Konsol

  1. Di konsol Google Cloud , buka halaman Firewall policies.

    Buka Firewall policies

  2. Klik aturan firewall yang ingin Anda ubah.

  3. Klik Edit.

  4. Ubah salah satu komponen yang dapat diedit agar sesuai dengan kebutuhan Anda.

  5. Klik Simpan.

gcloud

Untuk memperbarui aturan firewall VPC, gunakan perintah gcloud compute firewall-rules update:

gcloud compute firewall-rules update RULE_NAME \
    [--priority=PRIORITY] \
    [--description=DESCRIPTION] \
    [--target-tags=TAG,...] \
    [--target-service-accounts=IAM_SERVICE_ACCOUNT,_] \
    [--source-ranges=CIDR_RANGE,...] \
    [--source-tags=TAG,...] \
    [--source-service-accounts=IAM_SERVICE_ACCOUNT,_] \
    [--destination-ranges=CIDR_RANGE,...] \
    [--rules=[PROTOCOL[:PORT[-PORT]],…]] \
    [--disabled | --no-disabled] \
    [--enable-logging | --no-enable-logging]

Deskripsi untuk setiap tanda sama seperti untuk membuat aturan firewall, dan detail selengkapnya tentang setiap tanda tersedia dalam dokumentasi referensi SDK.

API

Gunakan PATCH untuk memperbarui kolom berikut: allowed, description, sourceRanges, sourceTags, atau targetTags. Gunakan PUT atau POST untuk semua kolom lainnya.

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

Ganti kode berikut:

  • PROJECT_ID: ID project tempat jaringan VPC berada.
  • NETWORK: nama jaringan VPC tempat aturan firewall berada.
  • RULE_NAME: nama aturan firewall yang akan diupdate.

Untuk mengetahui informasi dan deskripsi selengkapnya tentang setiap kolom, lihat metode firewalls.patch atau firewalls.update.

C#


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

public class PatchFirewallRuleAsyncSample
{
    public async Task PatchFirewallRuleAsync(
        // 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",
        int newPriority = 10)
    {
        // The patch operation doesn't require the full definition of a Firewall object.
        // It will only update the values that were set in it,
        // in this case it will only change the priority.
        Firewall firewallRule = new Firewall
        {
            Priority = newPriority
        };

        // 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();

        // Patch the firewall rule in the specified project.
        var firewallRulePatching = await client.PatchAsync(projectId, firewallRuleName, firewallRule);

        // Wait for the operation to complete using client-side polling.
        await firewallRulePatching.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"
)

// patchFirewallPriority modifies the priority of a given firewall rule.
func patchFirewallPriority(w io.Writer, projectID, firewallRuleName string, priority int32) error {
	// projectID := "your_project_id"
	// firewallRuleName := "europe-central2-b"
	// priority := 10

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

	firewallRule := &computepb.Firewall{
		Priority: proto.Int32(priority),
	}

	req := &computepb.PatchFirewallRequest{
		Project:          projectID,
		Firewall:         firewallRuleName,
		FirewallResource: firewallRule,
	}

	// The patch operation doesn't require the full definition of a Firewall interface. It will only update
	// the values that were set in it, in this case it will only change the priority.
	op, err := firewallsClient.Patch(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to patch 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 updated\n")

	return nil
}

Java


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.compute.v1.Firewall;
import com.google.cloud.compute.v1.FirewallsClient;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.PatchFirewallRequest;
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 PatchFirewallRule {

  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 you want to modify.
    // priority: the new priority to be set for the rule.
    String project = "your-project-id";
    String firewallRuleName = "firewall-rule-name-" + UUID.randomUUID();
    int priority = 10;

    patchFirewallPriority(project, firewallRuleName, priority);
  }

  // Modifies the priority of a given firewall rule.
  public static void patchFirewallPriority(String project, String firewallRuleName, int priority)
      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 patch operation doesn't require the full definition of a Firewall object. It will only 
         update the values that were set in it, in this case it will only change the priority. */
      Firewall firewall = Firewall.newBuilder()
          .setPriority(priority).build();

      PatchFirewallRequest patchFirewallRequest = PatchFirewallRequest.newBuilder()
          .setProject(project)
          .setFirewall(firewallRuleName)
          .setFirewallResource(firewall).build();

      OperationFuture<Operation, Operation> operation = firewallsClient.patchAsync(
          patchFirewallRequest);
      operation.get(3, TimeUnit.MINUTES);
      System.out.println("Firewall Patch applied successfully ! ");
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const firewallRuleName = 'FIREWALL_RULE_NAME';
// const priority = 10;

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

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

  const firewallRule = new computeProtos.Firewall();
  firewallRule.priority = priority;

  // The patch operation doesn't require the full definition of a Firewall object. It will only update
  // the values that were set in it, in this case it will only change the priority.
  const [response] = await firewallsClient.patch({
    project: projectId,
    firewall: firewallRuleName,
    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 updated');
}

patchFirewallPriority();

PHP

use Google\Cloud\Compute\V1\Client\FirewallsClient;
use Google\Cloud\Compute\V1\Firewall;
use Google\Cloud\Compute\V1\PatchFirewallRequest;

/**
 * Modifies the priority of a given firewall rule.
 *
 * @param string $projectId Project ID or project number of the Cloud project you want to patch a rule from.
 * @param string $firewallRuleName Name of the rule that you want to modify.
 * @param int $priority The new priority to be set for the rule.
 *
 * @throws \Google\ApiCore\ApiException if the remote call fails.
 * @throws \Google\ApiCore\ValidationException if local error occurs before remote call.
 */
function patch_firewall_priority(string $projectId, string $firewallRuleName, int $priority)
{
    $firewallsClient = new FirewallsClient();
    $firewallResource = (new Firewall())->setPriority($priority);

    // The patch operation doesn't require the full definition of a Firewall object. It will only update
    // the values that were set in it, in this case it will only change the priority.
    $request = (new PatchFirewallRequest())
        ->setFirewall($firewallRuleName)
        ->setFirewallResource($firewallResource)
        ->setProject($projectId);
    $operation = $firewallsClient->patch($request);

    // Wait for the operation to complete.
    $operation->pollUntilComplete();
    if ($operation->operationSucceeded()) {
        printf('Patched %s priority to %d.' . PHP_EOL, $firewallRuleName, $priority);
    } else {
        $error = $operation->getError();
        printf('Patching 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 patch_firewall_priority(
    project_id: str, firewall_rule_name: str, priority: int
) -> None:
    """
    Modifies the priority of a given firewall rule.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        firewall_rule_name: name of the rule you want to modify.
        priority: the new priority to be set for the rule.
    """
    firewall_rule = compute_v1.Firewall()
    firewall_rule.priority = priority

    # The patch operation doesn't require the full definition of a Firewall object. It will only update
    # the values that were set in it, in this case it will only change the priority.
    firewall_client = compute_v1.FirewallsClient()
    operation = firewall_client.patch(
        project=project_id, firewall=firewall_rule_name, firewall_resource=firewall_rule
    )

    wait_for_extended_operation(operation, "firewall rule patching")

Ruby


require "google/cloud/compute/v1"

# Modifies the priority of a given firewall rule.
#
# @param [String] project project ID or project number of the Cloud project you want to use.
# @param [String] name name of the rule you want to modify.
# @param [Google::Protobuf::RepeatedField] allowed the repeated instances of the Allowed field in the rule.
#         Compute errors out if allowed is empty.
# @param [Integer] priority the new priority to be set for the rule.
def patch_firewall_priority project:, name:, allowed:, priority:
  allowed_arr = allowed.map do |instance|
    {
      I_p_protocol: instance.I_p_protocol,
      ports: instance.ports.to_a
    }
  end.to_a

  rule = {
    priority: priority,
    allowed: allowed_arr
  }

  request = {
    project: project,
    firewall: name,
    firewall_resource: rule