VPC 방화벽 규칙 사용

이 페이지에서는 Virtual Private Cloud(VPC) 방화벽 규칙을 다루기 위한 명령어를 설명하고 몇 가지 사용 예시를 제공합니다. VPC 방화벽 규칙을 사용하면 포트 번호, 태그, 프로토콜을 기반으로 VPC 네트워크에서 가상 머신(VM) 인스턴스에 대한 트래픽을 허용하거나 거부할 수 있습니다.

시작하기 전에

기본 네트워크의 암시적 규칙 및 시스템 생성 규칙과 같은 VPC 방화벽 규칙에 대한 자세한 내용은 VPC 방화벽 규칙을 참조하세요.

방화벽 규칙을 구성하기 전에 Google Cloud에서 사용되는 방화벽 구성요소에 익숙해지도록 방화벽 규칙 구성요소를 검토하세요.

VPC 방화벽 규칙 만들기

VPC 방화벽 규칙은 네트워크 수준에서 정의되며 네트워크가 만들어진 위치에만 적용됩니다. 그러나 각각에 대해 선택한 이름은 프로젝트에 고유해야 합니다.

방화벽 규칙에는 IPv4 또는 IPv6 범위 중 하나가 포함될 수 있지만 둘 다 포함될 수는 없습니다.

방화벽 규칙을 만들 때 방화벽 규칙 로깅을 사용 설정할 수 있습니다. 로깅을 사용 설정한 경우 메타데이터 필드를 생략하여 스토리지 비용을 절약할 수 있습니다. 자세한 내용은 방화벽 규칙 로깅 사용을 참조하세요.

대상 또는 소스 서비스 계정 필드에 여러 서비스 계정을 지정하려면 Google Cloud CLI, API, 클라이언트 라이브러리를 사용합니다.

기본 네트워크 서비스는 생성 시 자동 방화벽 규칙을 제공합니다. 커스텀 및 자동 모드 네트워크를 사용하면 Google Cloud 콘솔을 사용하는 경우 네트워크 생성 중에 간편하게 비슷한 방화벽을 만들 수 있습니다. gcloud CLI 또는 API를 사용 중이고 기본 네트워크에서 제공되는 것과 비슷한 방화벽 규칙을 만들려면 일반적인 사용 사례의 방화벽 규칙 구성을 참조하세요.

콘솔

  1. Google Cloud 콘솔에서 방화벽 정책 페이지로 이동합니다.

    방화벽 정책으로 이동

  2. 방화벽 규칙 만들기를 클릭합니다.

  3. 방화벽 규칙의 이름을 입력합니다.

    이 이름은 프로젝트에서 고유해야 합니다.

  4. (선택사항) 방화벽 규칙 로깅을 사용할 수 있습니다.

    • 로그 > 사용을 클릭합니다.
    • 메타데이터를 생략하려면 로그 세부정보 표시를 클릭한 후 메타데이터 포함 체크박스를 선택 해제합니다.
  5. 방화벽 규칙의 네트워크를 지정합니다.

  6. 규칙의 우선순위를 지정합니다.

    숫자가 작을수록 우선순위가 높아집니다.

  7. 트래픽 방향에서 인그레스 또는 이그레스를 선택합니다.

  8. 일치 시 작업에서 허용 또는 거부를 선택합니다.

  9. 규칙의 대상을 지정합니다.

    • 네트워크의 모든 인스턴스에 규칙을 적용하려면 All instances in the network를 선택합니다.
    • 네트워크(대상) 태그별로 일부 인스턴스에 규칙을 적용하려면 지정된 대상 태그를 선택한 후 대상 태그 필드에서 규칙을 적용해야 하는 태그를 입력합니다.
    • 연결된 서비스 계정별로 일부 인스턴스에 규칙을 적용하려면 지정된 서비스 계정을 선택하고 서비스 계정 범위에서 서비스 계정이 현재 프로젝트 또는 다른 프로젝트에 있는지 여부를 표시한 후 대상 서비스 계정 필드에서 서비스 계정 이름을 선택하거나 입력합니다.
  10. 인그레스 규칙의 경우 소스 필터를 지정합니다.

    • 소스 IPv4 범위를 기준으로 들어오는 트래픽을 필터링하려면 IPv4 범위를 선택한 후 소스 IPv4 범위 필드에 CIDR 블록을 입력합니다. 모든 IPv4 소스에 0.0.0.0/0을 사용합니다.
    • 소스 IPv6 범위를 기준으로 들어오는 트래픽을 필터링하려면 IPv6 범위를 선택한 후 소스 IPv6 범위 필드에 CIDR 블록을 입력합니다. 모든 IPv6 소스에 ::/0을 사용합니다.
    • 네트워크 태그를 기준으로 들어오는 트래픽을 필터링하려면 소스 태그를 선택한 후 소스 태그 필드에 네트워크 태그를 입력합니다. 소스 태그 개수에 대한 제한은 네트워크별 한도를 참조하세요. 소스 태그별 필터링은 대상이 서비스 계정으로 지정되지 않은 경우에만 사용할 수 있습니다. 자세한 내용은 서비스 계정별 필터링 및 네트워크 태그별 필터링을 참조하세요.
    • 서비스 계정을 기준으로 들어오는 트래픽을 필터링하려면 서비스 계정을 선택하고 서비스 계정 범위에서 서비스 계정이 현재 프로젝트 또는 다른 프로젝트에 있는지 여부를 표시한 후 소스 서비스 계정 필드에서 서비스 계정 이름을 선택하거나 입력합니다. 소스 서비스 계정별 필터링은 대상이 네트워크 태그로 지정되지 않은 경우에만 사용 가능합니다. 자세한 내용은 서비스 계정별 필터링 및 네트워크 태그별 필터링을 참조하세요.
    • 원하는 경우 보조 소스 필터를 지정합니다. 보조 소스 필터는 기본 소스 필터와 동일한 필터 기준을 사용할 수 없습니다. 소스 IP 범위소스 태그 또는 소스 서비스 계정과 함께 사용될 수 있습니다. 유효한 소스 세트는 소스 범위 IP 주소와 네트워크 태그 또는 서비스 계정으로 식별된 인스턴스의 통합입니다. 즉, 소스 IP 범위 또는 소스 태그(또는 소스 서비스 계정)가 필터 기준과 일치하면 소스가 유효한 소스 세트에 포함됩니다.
    • 소스 태그소스 서비스 계정은 함께 사용할 수 없습니다.
  11. 인그레스 규칙의 경우 대상 필터를 지정합니다.

    • 대상 IPv4 범위를 기준으로 들어오는 트래픽을 필터링하려면 IPv4 범위를 선택하고 대상 IPv4 범위 필드에 CIDR 블록을 입력합니다. 모든 IPv4 대상에 0.0.0.0/0을 사용합니다.
    • 목적지 IPv6 범위를 기준으로 나가는 트래픽을 필터링하려면 IPv6 범위를 선택하고 목적지 IPv6 범위 필드에 CIDR 블록을 입력합니다. 모든 IPv6 대상에 ::/0을 사용합니다. 자세한 내용은 인그레스 규칙의 목적지를 참조하세요.
  12. 이그레스 규칙의 경우 대상 필터를 지정합니다.

    • 대상 IPv4 범위를 기준으로 나가는 트래픽을 필터링하려면 IPv4 범위를 선택하고 대상 IPv4 범위 필드에 CIDR 블록을 입력합니다. 모든 IPv4 대상에 0.0.0.0/0을 사용합니다.
    • 대상 IPv6 범위를 기준으로 나가는 트래픽을 필터링하려면 IPv6 범위를 선택하고 대상 IPv6 범위 필드에 CIDR 블록을 입력합니다. 모든 IPv6 대상에 ::/0을 사용합니다.
  13. 이그레스 규칙의 경우 소스 필터를 지정합니다.

    • 소스 IPv4 범위를 기준으로 나가는 트래픽을 필터링하려면 IPv4 범위를 선택한 후 소스 IPv4 범위 필드에 CIDR 블록을 입력합니다. 모든 IPv4 소스에 0.0.0.0/0을 사용합니다.
    • 소스 IPv6 범위를 기준으로 나가는 트래픽을 필터링하려면 IPv6 범위를 선택하고 소스 IPv6 범위 필드에 CIDR 블록을 입력합니다. 모든 IPv6 대상에 ::/0을 사용합니다. 자세한 내용은 이그레스 규칙의 소스를 참조하세요.
  14. 규칙을 적용할 프로토콜과 포트를 정의합니다.

    • 모든 프로토콜과 대상 포트에 규칙을 적용하려면 작업에 따라 모두 허용 또는 모두 거부를 선택합니다.
    • 특정 프로토콜과 대상 포트를 정의하려면 지정된 프로토콜 및 포트를 선택합니다.

      • TCP 프로토콜과 대상 포트를 포함하려면 TCP를 선택합니다. all 또는 20-22, 80, 8080 등의 쉼표로 구분된 대상 포트 목록을 입력합니다.
      • UDP 프로토콜과 대상 포트를 포함하려면 UDP를 선택합니다. all 또는 67-69, 123 등의 쉼표로 구분된 대상 포트 목록을 입력합니다.
      • icmp, sctp 또는 프로토콜 번호와 같은 프로토콜을 포함하려면 기타를 선택합니다. 예를 들어 IPv4 ICMP의 경우 icmp 또는 프로토콜 번호 1을 사용합니다. IPv6 ICMP에는 프로토콜 번호 58을 사용합니다.

        자세한 내용은 프로토콜 및 대상 포트를 참조하세요.

  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 트래픽의 방향(ingress 또는 egress)입니다.
  • --action 일치 시 작업(allow 또는 deny)입니다. --rules 플래그와 함께 사용해야 합니다.
  • 다음 방법 중 하나로 대상을 지정합니다.
    • 네트워크의 모든 대상에 규칙이 적용되어야 하는 경우 --target-tags--target-service-accounts를 생략합니다.
    • 네트워크 태그별로 대상을 정의하려면 --target-tags 플래그를 사용합니다.
    • 연결된 서비스 계정별로 대상을 정의하려면 --target-service-accounts 플래그를 사용합니다.
  • 인그레스 규칙의 경우 대상을 더 세분화하려면 --destination-ranges를 사용하여 IPv4 또는 IPv6 주소 범위를 CIDR 형식으로 지정합니다. --destination-ranges를 생략하면 인그레스 대상은 모든 IPv4 주소(0.0.0.0/0)입니다. 자세한 내용은 인그레스 규칙의 대상인그레스 규칙 대상 및 IP 주소를 참조하세요.

  • 인그레스 규칙의 경우 소스를 지정합니다.

    • --source-ranges 소스 IPv4 또는 IPv6 주소의 범위를 CIDR 형식으로 지정하려면 이 플래그를 사용합니다.
    • --source-ranges, source-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를 사용하여
    IPv4 또는 IPv6 주소 범위를 CIDR 형식으로 지정합니다. --source-ranges를 생략하면 이그레스 소스는 모든 IPv4 주소(0.0.0.0/0)입니다. 자세한 내용은 이그레스 규칙의 소스이그레스 규칙의 대상 및 IP 주소를 참조하세요.

  • 이그레스 규칙의 경우 대상을 지정합니다.

    • --destination-ranges 대상 IPv4 또는 IPv6 주소의 범위를 CIDR 형식으로 지정하려면 이 플래그를 사용합니다.
    • --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

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
}

다음을 바꿉니다.

  • PROJECT_ID: VPC 네트워크가 있는 프로젝트의 ID
  • NETWORK: 방화벽 규칙이 생성된 VPC 네트워크의 이름.
  • RULE_NAME: 방화벽 규칙의 이름입니다.

  • 인그레스 방화벽 규칙의 경우 인그레스 소스 및 대상을 지정합니다.

    • sourceRanges, sourceTags, sourceServiceAccounts 필드를 사용하여 인그레스 소스를 지정합니다.

    • sourceRanges는 IPv4 또는 IPv6 범위일 수 있지만 이 둘의 조합일 수는 없습니다. 0.0.0.0/0 범위를 사용하려면 필드를 지정하지 마세요.

    • sourceTags 필드와 sourceServiceAccounts 필드를 함께 사용할 수 없습니다. 하지만 sourceTags 또는 sourceServiceAccounts와 함께 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을 사용합니다. targetTags 또는 targetServiceAccounts 필드를 사용하여 규칙을 적용할 대상을 지정합니다. 대상 필드를 지정하지 않으면 규칙이 네트워크의 모든 대상에 적용됩니다.

각 필드에 대한 자세한 내용과 설명은 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\Enums\Firewall\Direction;

/**
 * To correctly handle string enums in Cloud Compute library
 * use constants defined in the Enums subfolder.
 */
use Google\Cloud\Compute\V1\Firewall;
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::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

VPC 방화벽 규칙 업데이트

일치 조건에 대해 지정된 프로토콜 및 대상 포트와 같은 VPC 방화벽 규칙의 일부 구성요소를 수정할 수 있습니다. 방화벽 규칙의 이름, 네트워크, 일치 시 작업, 트래픽 방향은 수정할 수 없습니다.

이름, 네트워크, 작업, 방향 구성요소를 변경해야 하는 경우 규칙을 삭제하고 새 규칙을 생성해야 합니다.

여러 서비스 계정을 추가하거나 삭제하려면 gcloud CLI, API 또는 클라이언트 라이브러리를 사용합니다. Google Cloud 콘솔을 사용하여 대상 서비스 계정이나 소스 서비스 계정을 여러 개 지정할 수 없습니다.

콘솔

  1. Google Cloud 콘솔에서 방화벽 정책 페이지로 이동합니다.

    방화벽 정책으로 이동

  2. 수정하려는 방화벽 규칙을 클릭합니다.

  3. 수정을 클릭합니다.

  4. 편집 가능한 구성요소를 필요에 맞게 수정합니다.

  5. 저장을 클릭합니다.

gcloud

VPC 방화벽 규칙을 업데이트하려면 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]

각 플래그에 대한 설명은 방화벽 규칙 만들기와 동일합니다. 각 항목에 대한 세부정보는 SDK 참조 문서에서 볼 수 있습니다.

API

PATCH를 사용하여 allowed, description,sourceRanges, sourceTags, targetTags 필드를 업데이트합니다. 다른 모든 필드에는 PUT 또는 POST를 사용합니다.

(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
}

다음을 바꿉니다.

  • PROJECT_ID: VPC 네트워크가 있는 프로젝트의 ID
  • NETWORK: 방화벽 규칙이 있는 VPC 네트워크의 이름
  • RULE_NAME: 업데이트할 방화벽 규칙의 이름

각 필드에 대한 자세한 내용과 설명은 firewalls.patch 또는 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
  }

  # 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.
  client = ::Google::Cloud::Compute::V1::Firewalls::Rest::Client.new
  operation = client.patch request

  wait_until_done operation: operation
end

VPC 네트워크의 VPC 방화벽 규칙 나열

프로젝트 또는 특정 VPC 네트워크의 모든 VPC 방화벽 규칙을 나열할 수 있습니다. 방화벽 규칙마다 Google Cloud 콘솔에 규칙 유형, 대상, 필터와 같은 세부정보가 표시됩니다.

방화벽 규칙 로깅을 사용 설정하면 방화벽 통계가 방화벽 규칙에 대한 통계를 제공하여 구성을 더 잘 이해하고 안전하게 최적화할 수 있습니다. 예를 들어 지난 6주 동안 사용되지 않은 allow 규칙이 표시됩니다. 자세한 내용은 방화벽 통계 문서의 방화벽 규칙 세부정보 화면 사용을 참조하세요.

콘솔

프로젝트에서 모든 네트워크의 모든 VPC 방화벽 규칙을 표시하려면 다음 안내를 따르세요.

특정 네트워크의 VPC 방화벽 규칙을 표시하려면 다음 안내를 따르세요.

  1. Google Cloud 콘솔에서 VPC 네트워크 페이지로 이동합니다.

    VPC 네트워크로 이동

  2. VPC 네트워크의 이름을 클릭하여 세부정보 페이지로 이동합니다.

  3. 네트워크 세부정보 페이지에서 방화벽 탭을 클릭합니다.

  4. vpc-firewall-rules를 확장합니다.

gcloud

제공된 네트워크에 대해 정렬된 VPC 방화벽 규칙 목록을 생성하려면 gcloud compute firewall-rules list 명령어를 사용합니다.

gcloud compute firewall-rules list --filter network=NETWORK \
    --sort-by priority \
    --format="table(
        name,
        network,
        direction,
        priority,
        sourceRanges.list():label=SRC_RANGES,
        destinationRanges.list():label=DEST_RANGES,
        allowed[].map().firewall_rule().list():label=ALLOW,
        denied[].map().firewall_rule().list():label=DENY,
        sourceTags.list():label=SRC_TAGS,
        targetTags.list():label=TARGET_TAGS
        )"

NETWORK를 방화벽 규칙을 나열할 네트워크의 이름으로 바꿉니다.

API

제공된 네트워크에 대한 모든 VPC 방화벽 규칙을 나열합니다.

GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls/?filter=network="NETWORK

다음을 바꿉니다.

  • PROJECT_ID: VPC 네트워크가 있는 프로젝트의 ID
  • NETWORK: 나열할 방화벽 규칙이 포함된 VPC 네트워크의 이름

자세한 내용은 firewalls.list 메서드를 참조하세요.

C#


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

public class ListFirewallRulesAsyncSample
{
    public async Task ListFirewallRulesAsync(
        // TODO(developer): Set your own default values for these parameters or pass different values when calling this method.
        string projectId = "your-project-id")
    {
        // 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();

        // Make the request to list all firewall rules.
        await foreach (var firewallRule in client.ListAsync(projectId))
        {
            // The result is a Firewall sequence that you can iterate over.
            Console.WriteLine($"Firewal Rule: {firewallRule.Name}");
        }
    }
}

Go

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
	"google.golang.org/api/iterator"
)

// listFirewallRules prints the list of firewall names and their descriptions in specified project
func listFirewallRules(w io.Writer, projectID string) error {
	// projectID := "your_project_id"

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

	req := &computepb.ListFirewallsRequest{
		Project: projectID,
	}

	it := firewallsClient.List(ctx, req)
	for {
		firewallRule, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "- %s: %s\n", firewallRule.GetName(), firewallRule.GetDescription())
	}

	return nil
}

Java


import com.google.cloud.compute.v1.Firewall;
import com.google.cloud.compute.v1.FirewallsClient;
import com.google.cloud.compute.v1.FirewallsClient.ListPagedResponse;
import java.io.IOException;

public class ListFirewallRules {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample
    // project: project ID or project number of the Cloud project you want to use.
    String project = "your-project-id";
    listFirewallRules(project);
  }

  // Return a list of all the firewall rules in specified project.
  // Also prints the list of firewall names and their descriptions.
  public static ListPagedResponse listFirewallRules(String project)
      throws IOException {
    /* 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()) {
      ListPagedResponse firewallResponse = firewallsClient.list(project);
      for (Firewall firewall : firewallResponse.iterateAll()) {
        System.out.println(firewall.getName());
      }
      return firewallResponse;
    }
  }
}

Node.js

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

const compute = require('@google-cloud/compute');

async function listFirewallRules() {
  const firewallsClient = new compute.FirewallsClient();

  const [firewallRules] = await firewallsClient.list({
    project: projectId,
  });

  for (const rule of firewallRules) {
    console.log(` - ${rule.name}: ${rule.description}`);
  }
}

listFirewallRules();

PHP

use Google\Cloud\Compute\V1\Client\FirewallsClient;
use Google\Cloud\Compute\V1\ListFirewallsRequest;

/**
 * Return a list of all the firewall rules in specified project. Also prints the
 * list of firewall names and their descriptions.
 *
 * @param string $projectId Project ID or project number of the Cloud project you want to list rules from.
 *
 * @throws \Google\ApiCore\ApiException if the remote call fails.
 */
function list_firewall_rules(string $projectId)
{
    // List all firewall rules defined for the project using Firewalls Client.
    $firewallClient = new FirewallsClient();
    $request = (new ListFirewallsRequest())
        ->setProject($projectId);
    $firewallList = $firewallClient->list($request);

    print('--- Firewall Rules ---' . PHP_EOL);
    foreach ($firewallList->iterateAllElements() as $firewall) {
        printf(' -  %s : %s : %s' . PHP_EOL, $firewall->getName(), $firewall->getDescription(), $firewall->getNetwork());
    }
}

Python

from __future__ import annotations

from collections.abc import Iterable

from google.cloud import compute_v1

def list_firewall_rules(project_id: str) -> Iterable[compute_v1.Firewall]:
    """
    Return a list of all the firewall rules in specified project. Also prints the
    list of firewall names and their descriptions.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.

    Returns:
        A flat list of all firewall rules defined for given project.
    """
    firewall_client = compute_v1.FirewallsClient()
    firewalls_list = firewall_client.list(project=project_id)

    for firewall in firewalls_list:
        print(f" - {firewall.name}: {firewall.description}")

    return firewalls_list

Ruby


require "google/cloud/compute/v1"

# Return a list of all the firewall rules in specified project. Also prints the
# list of firewall names and their descriptions.
#
# @param [String] project project ID or project number of the project you want to use.
# @return [Array<::Google::Cloud::Compute::V1::Firewall>]
#     A list of all firewall rules defined for the given project.
def list_firewall_rules project:
  client = ::Google::Cloud::Compute::V1::Firewalls::Rest::Client.new
  firewalls = client.list project: project

  firewall_list = []
  firewalls.each do |firewall|
    puts " - #{firewall.name}: #{firewall.description}"
    firewall_list << firewall
  end

  firewall_list
end

VM 인스턴스의 네트워크 인터페이스에 대한 VPC 방화벽 규칙 나열

각 네트워크 인터페이스에 대해 Google Cloud 콘솔에는 인터페이스에 적용되는 모든 VPC 방화벽 규칙과 인터페이스에서 실제로 사용되는 규칙이 나열됩니다. 방화벽 규칙은 다른 규칙을 마스킹할 수 있으므로 인터페이스에 적용되는 일부 규칙이 실제로 인터페이스에서 사용되지 않을 수 있습니다.

방화벽 규칙은 규칙의 대상 매개변수를 통해 VM 인스턴스에 연결되고 적용됩니다. 적용되는 모든 규칙을 보고 특정 규칙이 인터페이스에 적용되는지 여부를 확인할 수 있습니다.

방화벽 규칙 로깅을 사용 설정하면 방화벽 통계가 방화벽 규칙에 대한 통계를 제공하여 구성을 더 잘 이해하고 안전하게 최적화할 수 있습니다. 예를 들어 지난 6주 동안 적중한 인터페이스의 규칙이 표시됩니다. 자세한 내용은 방화벽 통계 문서의 VM 네트워크 인터페이스 세부정보 화면 사용을 참조하세요.

콘솔

VM 인스턴스의 특정 네트워크 인터페이스에 적용되는 VPC 규칙을 보려면 다음 안내를 따르세요.

  1. Google Cloud 콘솔에서 VM 인스턴스 페이지로 이동합니다.

    VM 인스턴스로 이동

  2. 보려는 인스턴스를 찾습니다.

  3. 인스턴스의 추가 작업 메뉴()에서 네트워크 세부정보 보기를 선택합니다.

  4. 인스턴스에 네트워크 인터페이스가 여러 개 있는 경우 선택된 네트워크 인터페이스 필드에서 보려는 네트워크 인터페이스를 선택합니다.

  5. 방화벽 및 경로 세부정보 섹션에서 방화벽 탭을 선택합니다.

  6. vpc-firewall-rules를 확장합니다.

  7. 표를 보고 특정 IP 주소를 주고받는 트래픽이 허용되는지 확인합니다.

VPC 방화벽 규칙 세부정보 보기

VPC 방화벽 규칙을 검사하여 규칙의 이름, 관련 네트워크, 규칙이 사용 설정 상태인지 사용 중지 상태인지를 포함한 구성요소를 볼 수 있습니다.

콘솔

  1. 방화벽 규칙을 나열합니다. 모든 규칙 목록을 보거나 특정 네트워크의 규칙만 볼 수 있습니다.
  2. 규칙을 클릭하여 확인합니다.

gcloud

다음 명령어는 개별 VPC 방화벽 규칙을 설명합니다. 방화벽 규칙 이름은 프로젝트에서 고유하므로 기존 방화벽 규칙을 설명할 때 네트워크를 지정할 필요는 없습니다.

gcloud compute firewall-rules describe RULE_NAME

RULE_NAME을 방화벽 규칙의 이름으로 바꿉니다.

API

지정된 VPC 방화벽 규칙을 기술합니다.

GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls/RULE_NAME

자리표시자를 유효한 값으로 바꿉니다.

  • PROJECT_ID: 방화벽 규칙이 있는 프로젝트의 ID
  • RULE_NAME: 설명할 방화벽 규칙의 이름

자세한 내용은 firewalls.get 메서드를 참조하세요.

VPC 방화벽 규칙 삭제

콘솔

  1. VPC 방화벽 규칙을 나열합니다. 모든 규칙 목록을 보거나 특정 네트워크의 규칙만 볼 수 있습니다.
  2. 삭제할 규칙을 클릭합니다.
  3. 삭제를 클릭합니다.
  4. 삭제를 다시 클릭하여 확인합니다.

gcloud

VPC 방화벽 규칙을 삭제하려면 gcloud compute firewall-rules delete 명령어를 사용합니다.

gcloud compute firewall-rules delete RULE_NAME

RULE_NAME을 삭제할 규칙의 이름으로 바꿉니다.

API

VPC 방화벽 규칙을 삭제합니다.

DELETE https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls/RULE_NAME

다음을 바꿉니다.

  • PROJECT_ID: 방화벽 규칙이 있는 프로젝트의 ID
  • RULE_NAME: 삭제할 방화벽 규칙의 이름

자세한 내용은 firewalls.delete 메서드를 참조하세요.

C#


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

public class DeleteFirewallRuleAsyncSample
{
    public async Task DeleteFirewallRuleAsync(
        // 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")
    {

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

        // Make the request to delete the firewall rule.
        var firewallRuleDeletion = await client.DeleteAsync(projectId, firewallRuleName);

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

Go

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
)

// deleteFirewallRule deletes a firewall rule from the project.
func deleteFirewallRule(w io.Writer, projectID, firewallRuleName string) error {
	// projectID := "your_project_id"
	// firewallRuleName := "europe-central2-b"

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

	req := &computepb.DeleteFirewallRequest{
		Project:  projectID,
		Firewall: firewallRuleName,
	}

	op, err := firewallsClient.Delete(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to delete 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 deleted\n")

	return nil
}

Java


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

  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 firewall rule you want to delete.
    String project = "your-project-id";
    String firewallRuleName = "firewall-rule-name-" + UUID.randomUUID();
    deleteFirewallRule(project, firewallRuleName);
  }

  // Deletes a firewall rule from the project.
  public static void deleteFirewallRule(String project, String firewallRuleName)
      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()) {

      OperationFuture<Operation, Operation> operation = firewallsClient.deleteAsync(project,
          firewallRuleName);
      operation.get(3, TimeUnit.MINUTES);

      System.out.println("Deleted firewall rule -> " + firewallRuleName);
    }
  }
}

Node.js

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

const compute = require('@google-cloud/compute');

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

  const [response] = await firewallsClient.delete({
    project: projectId,
    firewall: firewallRuleName,
  });
  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 deleted');
}

deleteFirewallRule();

PHP

use Google\Cloud\Compute\V1\Client\FirewallsClient;
use Google\Cloud\Compute\V1\DeleteFirewallRequest;

/**
 * Delete a firewall rule from the specified project.
 *
 * @param string $projectId Project ID or project number of the Cloud project you want to delete a rule for.
 * @param string $firewallRuleName Name of the rule that is deleted.
 *
 * @throws \Google\ApiCore\ApiException if the remote call fails.
 * @throws \Google\ApiCore\ValidationException if local error occurs before remote call.
 */
function delete_firewall_rule(string $projectId, string $firewallRuleName)
{
    $firewallsClient = new FirewallsClient();

    // Delete the firewall rule using Firewalls Client.
    $request = (new DeleteFirewallRequest())
        ->setFirewall($firewallRuleName)
        ->setProject($projectId);
    $operation = $firewallsClient->delete($request);

    // Wait for the operation to complete.
    $operation->pollUntilComplete();
    if ($operation->operationSucceeded()) {
        printf('Rule %s deleted successfully!' . PHP_EOL, $firewallRuleName);
    } else {
        $error = $operation->getError();
        printf('Failed to delete firewall rule: %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 delete_firewall_rule(project_id: str, firewall_rule_name: str) -> None:
    """
    Deletes a firewall rule from the project.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        firewall_rule_name: name of the firewall rule you want to delete.
    """
    firewall_client = compute_v1.FirewallsClient()
    operation = firewall_client.delete(project=project_id, firewall=firewall_rule_name)

    wait_for_extended_operation(operation, "firewall rule deletion")

Ruby


require "google/cloud/compute/v1"

# Deletes a firewall rule from the project.
#
# @param [String] project project ID or project number of the Cloud project you want to use.
# @param [String] name name of the firewall rule you want to delete.
def delete_firewall_rule project:, name:
  client = ::Google::Cloud::Compute::V1::Firewalls::Rest::Client.new
  operation = client.delete project: project, firewall: name

  wait_until_done operation: operation
end

VPC 방화벽 규칙 모니터링

VPC 방화벽 규칙에 로깅을 사용 설정하여 어떤 규칙이 어떤 트래픽을 허용 또는 차단하는지 확인할 수 있습니다. 자세한 내용은 방화벽 규칙 로깅 사용을 참조하세요.

일반적인 사용 사례의 VPC 방화벽 규칙 구성

다음 섹션에서는 gcloud CLI와 API를 사용하여 기본 네트워크에 대해 생성된 사전 정의된 VPC 방화벽 규칙을 다시 만드는 방법의 예시를 보여줍니다. 이 예시를 사용해서 커스텀 및 자동 모드 네트워크에 사용되는 비슷한 규칙을 만들 수 있습니다. 각 방화벽 규칙은 IPv4 또는 IPv6 주소 범위 중 하나를 포함할 수 있지만 둘 다 포함할 수는 없습니다.

VM 사이에 내부 인그레스 연결 허용

다음 예시에서는 기본 네트워크의 allow-internal 규칙과 비슷하게 VM 인스턴스에 대해 내부 TCP, UDP, ICMP 연결을 허용하도록 방화벽 규칙을 만듭니다.

gcloud

gcloud compute firewall-rules create 명령어를 사용합니다.

gcloud compute firewall-rules create RULE_NAME \
    --action=ALLOW \
    --direction=INGRESS \
    --network=NETWORK \
    --priority=1000 \
    --rules=tcp:0-65535,udp:0-65535,ICMP_PROTOCOL \
    --source-ranges=SUBNET_RANGES

다음을 바꿉니다.

  • RULE_NAME: 이 방화벽 규칙의 이름입니다.
  • NETWORK: 이 방화벽 규칙이 적용되는 네트워크의 이름입니다. 기본값은 default입니다.
  • ICMP_PROTOCOL: ICMP 프로토콜 유형. 프로토콜 이름 icmp 또는 프로토콜 번호 1을 사용하여 ICMPv4를 지정합니다. 프로토콜 번호 58을 사용하여 ICMPv6을 지정합니다.
  • SUBNET_RANGES: 하나 이상의 IP 주소 범위입니다. IP 주소 범위를 포함하면 해당 범위의 트래픽이 VPC 네트워크의 모든 VM 대상에 도달할 수 있습니다. 특정 방화벽 규칙에 IPv4 또는 IPv6 범위를 지정할 수 있습니다.

    IPv4 서브넷 범위:

    • 자동 모드 VPC 네트워크에는 10.128.0.0/9 내의 IP 주소 범위가 사용됩니다.
    • 커스텀 모드 네트워크는 모든 유효한 IPv4 범위를 사용할 수 있습니다. VPC 네트워크의 서브넷에 대해 연속된 범위를 사용하지 않는 경우에는 여러 범위를 지정해야 할 수 있습니다.
    • 10.0.0.0/8,172.16.0.0/12,192.168.0.0/16을 사용하여 모든 비공개 IPv4 주소 범위의 트래픽을 허용할 수 있습니다(RFC 1918 범위).

    IPv6 서브넷 범위:

    • VPC 네트워크에 내부 IPv6 주소 범위를 할당한 경우 이 범위를 소스 범위로 사용할 수 있습니다. VPC 네트워크의 내부 IPv6 범위를 사용하면 방화벽 규칙에 현재 및 향후의 모든 내부 IPv6 서브넷 범위가 포함됩니다. 다음 명령어를 사용하여 VPC 네트워크의 내부 IPv6 범위를 찾을 수 있습니다.

      gcloud compute networks describe NETWORK \
        --format="flattened(internalIpv6Range)"
      

      특정 내부 IPv6 서브넷 범위를 지정할 수도 있습니다.

    • 이중 스택 서브넷의 외부 IPv6 서브넷 범위에서 들어오는 트래픽을 허용하려면 포함하려는 각 서브넷의 IPv6 주소 범위를 지정해야 합니다.

API

POST https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls
{
  "kind": "compute#firewall",
  "name": "RULE_NAME",
  "network": "projects/PROJECT_ID/global/networks/NETWORK",
  "direction": "INGRESS",
  "priority": 1000,
  "targetTags": [],
  "allowed": [
    {
      "IPProtocol": "tcp",
      "ports": [
        "0-65535"
      ]
    },
    {
      "IPProtocol": "udp",
      "ports": [
        "0-65535"
      ]
    },
    {
      "IPProtocol": "ICMP_PROTOCOL"
    }
  ],
  "sourceRanges": [
    "SUBNET_RANGES"
  ]
}

다음을 바꿉니다.

  • PROJECT_ID: VPC 네트워크가 있는 프로젝트의 ID
  • RULE_NAME: 방화벽 규칙의 이름입니다.
  • NETWORK: 방화벽 규칙이 생성된 VPC 네트워크의 이름. 기본값은 default입니다.
  • ICMP_PROTOCOL: ICMP 프로토콜 유형. 프로토콜 이름 icmp 또는 프로토콜 번호 1을 사용하여 ICMPv4를 지정합니다. 프로토콜 번호 58을 사용하여 ICMPv6을 지정합니다.
  • INTERNAL_SOURCE_RANGES: 하나 이상의 IP 범위입니다. VPC 네트워크의 모든 서브넷 내에서 내부 트래픽을 허용하려면 VPC 네트워크에 사용된 IP 주소 범위를 지정합니다. 특정 방화벽 규칙에 IPv4 또는 IPv6 범위를 지정할 수 있습니다.

    IPv4 서브넷 범위:

    • 자동 모드 VPC 네트워크에는 10.128.0.0/9 내의 IP 주소 범위가 사용됩니다.
    • 커스텀 모드 네트워크는 모든 유효한 IPv4 범위를 사용할 수 있습니다. VPC 네트워크의 서브넷에 대해 연속된 범위를 사용하지 않는 경우에는 여러 범위를 지정해야 할 수 있습니다.
    • 10.0.0.0/8,172.16.0.0/12,192.168.0.0/16을 사용하여 모든 비공개 IPv4 주소 범위의 트래픽을 허용할 수 있습니다(RFC 1918 범위).

    IPv6 서브넷 범위:

    • VPC 네트워크에 내부 IPv6 주소 범위를 할당한 경우 이 범위를 소스 범위로 사용할 수 있습니다. VPC 네트워크의 내부 IPv6 범위를 사용하면 방화벽 규칙에 현재 및 향후의 모든 내부 IPv6 서브넷 범위가 포함됩니다. 다음 명령어를 사용하여 VPC 네트워크의 내부 IPv6 범위를 찾을 수 있습니다.

      gcloud compute networks describe NETWORK \
        --format="flattened(internalIpv6Range)"
      

      특정 내부 IPv6 서브넷 범위를 지정할 수도 있습니다.

    • 이중 스택 서브넷의 외부 IPv6 서브넷 범위에서 들어오는 트래픽을 허용하려면 포함하려는 각 서브넷의 IPv6 주소 범위를 지정해야 합니다.

VM에 대한 인그레스 SSH 연결 허용

다음 예시에서는 기본 네트워크의 allow-ssh 규칙과 비슷하게 VM 인스턴스에 대해 SSH 연결을 허용하는 방화벽 규칙을 만듭니다.

gcloud

gcloud compute firewall-rules create 명령어를 사용합니다.

gcloud compute firewall-rules create RULE_NAME \
    --action=ALLOW \
    --direction=INGRESS \
    --network=NETWORK \
    --priority=1000 \
    --rules=tcp:22 \
    --source-ranges=RANGES_OUTSIDE_VPC_NETWORK

다음을 바꿉니다.

  • RULE_NAME: 이 방화벽 규칙의 이름입니다.
  • NETWORK: 이 방화벽 규칙이 적용되는 네트워크의 이름입니다. 기본값은 default입니다.
  • RANGES_OUTSIDE_VPC_NETWORK: 하나 이상의 IP 주소 범위입니다. 특정 방화벽 규칙에 IPv4 또는 IPv6 범위를 지정할 수 있습니다. 모든 IPv4 또는 IPv6 소스 대신 액세스를 허용해야 하는 특정 IP 주소 범위를 지정하는 것이 좋습니다.

    • 소스 범위에 35.235.240.0/20을 포함하면 다른 모든 기본 요건이 충족되었을 때 IAP(Identity-Aware Proxy) TCP 전달을 사용하는 SSH 연결이 허용됩니다. 자세한 내용은 TCP 전달에 IAP 사용을 참조하세요.
    • 0.0.0.0/0을 소스 범위로 사용하면 Google Cloud 외부의 소스를 포함한 모든 IPv4 소스의 트래픽이 허용됩니다.
    • ::/0을 소스 범위로 사용하면 Google Cloud 외부의 소스를 포함한 모든 IPv6 소스의 트래픽이 허용됩니다.

API

POST https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls
{
  "kind": "compute#firewall",
  "name": "RULE_NAME",
  "network": "projects/PROJECT_ID/global/networks/NETWORK",
  "direction": "INGRESS",
  "priority": 1000,
  "targetTags": [],
  "allowed": [
    {
      "IPProtocol": "tcp",
      "ports": [
        "22"
      ]
    }
  ],
  "sourceRanges": [
    "RANGES_OUTSIDE_VPC_NETWORK"
  ]
}

다음을 바꿉니다.

  • PROJECT_ID: VPC 네트워크가 있는 프로젝트의 ID
  • RULE_NAME: 방화벽 규칙의 이름입니다.
  • NETWORK: 방화벽 규칙이 생성된 VPC 네트워크의 이름.
  • RANGES_OUTSIDE_VPC_NETWORK: 하나 이상의 IP 주소 범위입니다. 특정 방화벽 규칙에 IPv4 또는 IPv6 범위를 지정할 수 있습니다. 모든 IPv4 또는 IPv6 소스 대신 액세스를 허용해야 하는 특정 IP 주소 범위를 지정하는 것이 좋습니다.

    • 소스 범위에 35.235.240.0/20을 포함하면 다른 모든 기본 요건이 충족되었을 때 IAP(Identity-Aware Proxy) TCP 전달을 사용하는 SSH 연결이 허용됩니다. 자세한 내용은 TCP 전달에 IAP 사용을 참조하세요.
    • 0.0.0.0/0을 소스 범위로 사용하면 Google Cloud 외부의 소스를 포함한 모든 IPv4 소스의 트래픽이 허용됩니다.
    • ::/0을 소스 범위로 사용하면 Google Cloud 외부의 소스를 포함한 모든 IPv6 소스의 트래픽이 허용됩니다.

VM에 대한 인그레스 RDP 연결 허용

다음 예시에서는 기본 네트워크의 allow-rdp 규칙과 비슷하게 VM 인스턴스에 대한 Microsoft 원격 데스크톱 프로토콜(RDP) 연결을 허용하도록 방화벽 규칙을 만듭니다.

gcloud

gcloud compute firewall-rules create 명령어를 사용합니다.

gcloud compute firewall-rules create RULE_NAME \
    --action=ALLOW \
    --direction=INGRESS \
    --network=NETWORK \
    --priority=1000 \
    --rules=tcp:3389 \
    --source-ranges=RANGES_OUTSIDE_VPC_NETWORK

다음을 바꿉니다.

  • RULE_NAME: 이 방화벽 규칙의 이름입니다.
  • NETWORK: 이 방화벽 규칙이 적용되는 네트워크의 이름입니다. 기본값은 default입니다.
  • RANGES_OUTSIDE_VPC_NETWORK: 하나 이상의 IP 주소 범위입니다. 특정 방화벽 규칙에 IPv4 또는 IPv6 범위를 지정할 수 있습니다. 모든 IPv4 또는 IPv6 소스 대신 액세스를 허용해야 하는 특정 IP 주소 범위를 지정하는 것이 좋습니다.

    • 소스 범위에 35.235.240.0/20을 포함하면 다른 모든 기본 요건이 충족될 때 IAP(Identity-Aware Proxy) TCP 전달을 사용하는 RDP 연결이 허용됩니다. 자세한 내용은 TCP 전달에 IAP 사용을 참조하세요.
    • 0.0.0.0/0을 소스 범위로 사용하면 Google Cloud 외부의 소스를 포함한 모든 IPv4 소스의 트래픽이 허용됩니다.
    • ::/0을 소스 범위로 사용하면 Google Cloud 외부의 소스를 포함한 모든 IPv6 소스의 트래픽이 허용됩니다.

API

POST https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls
{
  "kind": "compute#firewall",
  "name": "RULE_NAME",
  "network": "projects/PROJECT_ID/global/networks/NETWORK",
  "direction": "INGRESS",
  "priority": 1000,
  "allowed": [
    {
      "IPProtocol": "tcp",
      "ports": [
        "3389"
      ]
    }
  ],
  "sourceRanges": [
    "EXTERNAL_SOURCE_RANGES"
  ]
}

다음을 바꿉니다.

  • PROJECT_ID: VPC 네트워크가 있는 프로젝트의 ID
  • RULE_NAME: 방화벽 규칙의 이름입니다.
  • NETWORK: 방화벽 규칙이 생성된 VPC 네트워크의 이름.
  • RANGES_OUTSIDE_VPC_NETWORK: 하나 이상의 IP 주소 범위입니다. 특정 방화벽 규칙에 IPv4 또는 IPv6 범위를 지정할 수 있습니다. 모든 IPv4 또는 IPv6 소스 대신 액세스를 허용해야 하는 특정 IP 주소 범위를 지정하는 것이 좋습니다.

    • 소스 범위에 35.235.240.0/20을 포함하면 다른 모든 기본 요건이 충족될 때 IAP(Identity-Aware Proxy) TCP 전달을 사용하는 RDP 연결이 허용됩니다. 자세한 내용은 TCP 전달에 IAP 사용을 참조하세요.
    • 0.0.0.0/0을 소스 범위로 사용하면 Google Cloud 외부의 소스를 포함한 모든 IPv4 소스의 트래픽이 허용됩니다.
    • ::/0을 소스 범위로 사용하면 Google Cloud 외부의 소스를 포함한 모든 IPv6 소스의 트래픽이 허용됩니다.

VM에 대한 인그레스 ICMP 연결 허용

다음 예시에서는 기본 네트워크의 allow-icmp 규칙과 비슷하게 VM 인스턴스에 대해 ICMP 연결을 허용하는 방화벽 규칙을 만듭니다.

gcloud

gcloud compute firewall-rules create 명령어를 사용합니다.

gcloud compute firewall-rules create RULE_NAME \
    --action=ALLOW \
    --direction=INGRESS \
    --network=NETWORK \
    --priority=1000 \
    --rules=ICMP_PROTOCOL \
    --source-ranges=RANGES_OUTSIDE_VPC_NETWORK

다음을 바꿉니다.

  • RULE_NAME: 방화벽 규칙의 이름입니다.
  • NETWORK: 이 방화벽 규칙이 적용되는 네트워크의 이름입니다. 기본값은 default입니다.
  • ICMP_PROTOCOL: ICMP 프로토콜 유형. 프로토콜 이름 icmp 또는 프로토콜 번호 1을 사용하여 ICMPv4를 지정합니다. 프로토콜 번호 58을 사용하여 ICMPv6을 지정합니다.
  • RANGES_OUTSIDE_VPC_NETWORK: 하나 이상의 IP 주소 범위입니다. 특정 방화벽 규칙에 IPv4 또는 IPv6 범위를 지정할 수 있습니다. 모든 IPv4 또는 IPv6 소스 대신 액세스를 허용해야 하는 특정 IP 주소 범위를 지정하는 것이 좋습니다.

    • 0.0.0.0/0을 소스 범위로 사용하면 Google Cloud 외부의 소스를 포함한 모든 IPv4 소스의 트래픽이 허용됩니다.
    • ::/0을 소스 범위로 사용하면 Google Cloud 외부의 소스를 포함한 모든 IPv6 소스의 트래픽이 허용됩니다.

API

POST https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls
{
  "kind": "compute#firewall",
  "name": "RULE_NAME",
  "network": "projects/PROJECT_ID/global/networks/NETWORK",
  "direction": "INGRESS",
  "priority": 1000,
  "targetTags": [],
  "allowed": [
    {
      "IPProtocol": "ICMP_PROTOCOL"
    }
  ],
  "sourceRanges": [
    "RANGES_OUTSIDE_VPC_NETWORK"
  ]
}

다음을 바꿉니다.

  • PROJECT_ID: VPC 네트워크가 있는 프로젝트의 ID
  • RULE_NAME: 방화벽 규칙의 이름입니다.
  • NETWORK: 방화벽 규칙이 생성된 VPC 네트워크의 이름.
  • ICMP_PROTOCOL: 사용할 ICMP 프로토콜 유형. 프로토콜 이름 icmp 또는 프로토콜 번호 1을 사용하여 ICMPv4를 지정합니다. 프로토콜 번호 58을 사용하여 ICMPv6을 지정합니다.
  • RANGES_OUTSIDE_VPC_NETWORK: 하나 이상의 IP 주소 범위입니다. 특정 방화벽 규칙에 IPv4 또는 IPv6 범위를 지정할 수 있습니다. 모든 IPv4 또는 IPv6 소스 대신 액세스를 허용해야 하는 특정 IP 주소 범위를 지정하는 것이 좋습니다.

    • 0.0.0.0/0을 소스 범위로 사용하면 Google Cloud 외부의 소스를 포함한 모든 IPv4 소스의 트래픽이 허용됩니다.
    • ::/0을 소스 범위로 사용하면 Google Cloud 외부의 소스를 포함한 모든 IPv6 소스의 트래픽이 허용됩니다.

기타 구성 예시

그림 1은 my-network라는 VPC 네트워크의 구성 예시를 설명합니다. 네트워크에는 다음이 포함됩니다.

  • IP 범위가 10.240.10.0/24이고 단일 인스턴스인 subnet1이라는 서브넷
  • IP 범위가 192.168.1.0/24subnet2라는 서브넷
  • webserver 태그가 있고 내부 IP 주소가 192.168.1.2subnet2에 있는 vm1이라는 인스턴스
  • database 태그가 있고 내부 IP 주소가 192.168.1.3subnet2에 있는 vm2라는 인스턴스
이 VPC 네트워크에는 각각 VM이 포함된 2개의 서브넷이 있습니다. subnet2에는 네트워크 태그가 할당된 VM이 포함되어 있습니다.
그림 1. 이 VPC 네트워크에는 각각 VM이 포함된 2개의 서브넷이 있습니다. subnet2에는 네트워크 태그가 할당된 VM이 포함되어 있습니다(확대하려면 클릭).

예시 1: subnet1의 포트 80에 대한 연결을 제외한 모든 인그레스 TCP 연결 거부

이 예시에서는 subnet1의 포트 80을 대상으로 하는 연결을 제외한 모든 인그레스 TCP 연결을 거부하는 방화벽 VPC 규칙 집합을 만듭니다.

gcloud

  1. webserver 태그가 지정된 인스턴스에 대한 모든 인그레스 TCP 트래픽을 거부하는 방화벽 규칙을 만듭니다.

    gcloud compute firewall-rules create deny-subnet1-webserver-access \
        --network NETWORK_NAME \
        --action deny \
        --direction ingress \
        --rules tcp \
        --source-ranges 0.0.0.0/0 \
        --priority 1000 \
        --target-tags webserver
    

    NETWORK_NAME을 네트워크 이름으로 바꿉니다.

  2. webserver로 태그 지정된 인스턴스에서 TCP 포트 80에 액세스하도록 subnet1(10.240.10.0/24)의 모든 IP 주소를 허용하는 방화벽 규칙을 만듭니다.

    gcloud compute firewall-rules create vm1-allow-ingress-tcp-port80-from-subnet1 \
        --network NETWORK_NAME \
        --action allow \
        --direction ingress \
        --rules tcp:80 \
        --source-ranges 10.240.10.0/24 \
        --priority 50 \
        --target-tags webserver
    

    NETWORK_NAME을 네트워크 이름으로 바꿉니다.

예시 2: vm1의 포트 80에 대한 연결을 제외한 모든 이그레스 TCP 연결 거부

gcloud

  1. 모든 이그레스 TCP 트래픽을 거부하는 방화벽 규칙을 만듭니다.

    gcloud compute firewall-rules create deny-all-access \
        --network NETWORK_NAME \
        --action deny \
        --direction egress \
        --rules tcp \
        --destination-ranges 0.0.0.0/0 \
        --priority 1000
    

    NETWORK_NAME을 네트워크 이름으로 바꿉니다.

  2. vm1 포트 80을 대상으로 하는 TCP 트래픽을 허용하는 방화벽 규칙을 만듭니다.

    gcloud compute firewall-rules create vm1-allow-egress-tcp-port80-to-vm1 \
        --network NETWORK_NAME \
        --action allow \
        --direction egress \
        --rules tcp:80 \
        --destination-ranges 192.168.1.2/32 \
        --priority 60
    

    NETWORK_NAME을 네트워크 이름으로 바꿉니다.

예시 3: 외부 호스트의 포트 443에 대한 이그레스 TCP 연결 허용

샘플 외부 IP 주소 192.0.2.5의 포트 443으로 이그레스 TCP 트래픽을 보내도록 webserver 태그가 지정된 인스턴스를 허용하는 방화벽 규칙을 만듭니다.

gcloud

gcloud compute firewall-rules create vm1-allow-egress-tcp-port443-to-192-0-2-5 \
    --network NETWORK_NAME \
    --action allow \
    --direction egress \
    --rules tcp:443 \
    --destination-ranges 192.0.2.5/32 \
    --priority 70 \
    --target-tags webserver

NETWORK_NAME을 네트워크 이름으로 바꿉니다.

예시 4: vm2에서 vm1로의 SSH 연결 허용

webserver(vm1) 태그가 있는 인스턴스에 도달하도록 database(vm2) 태그가 있는 인스턴스에서 SSH 트래픽을 허용하는 방화벽 규칙을 만듭니다.

gcloud

gcloud compute firewall-rules create vm1-allow-ingress-tcp-ssh-from-vm2 \
    --network NETWORK_NAME \
    --action allow \
    --direction ingress \
    --rules tcp:22 \
    --source-tags database \
    --priority 80 \
    --target-tags webserver

NETWORK_NAME을 네트워크 이름으로 바꿉니다.

예 5: 서비스 계정을 사용하여 웹 서버에서 데이터베이스로 TCP:1443 허용

서비스 계정과 역할에 대한 자세한 내용은 서비스 계정에 역할 부여를 참조하세요.

그림 2의 시나리오에서는 템플릿을 통해 자동 확장되는 애플리케이션이 2개 있습니다. 웹 서버 애플리케이션은 my-sa-webserver 서비스 계정과 연결되어 있고, 데이터베이스 애플리케이션은 my-sa-database 서비스 계정과 연결되어 있습니다. 보안 관리자가 my-sa-database 서비스 계정을 사용하는 VM의 대상 포트 1443에 대해 my-sa-webserver 서비스 계정을 사용하는 VM의 TCP 트래픽을 허용하려고 합니다.

방화벽 규칙은 my-sa-database 서비스 계정을 사용하는 VM의 포트 1443에 대해 my-sa-webserver 서비스 계정을 사용하는 VM의 트래픽을 허용합니다.
그림 2. 방화벽 규칙은 my-sa-database 서비스 계정을 사용하는 VM의 포트 1443에 대해 my-sa-webserver 서비스 계정을 사용하는 VM의 트래픽을 허용합니다.

서비스 계정 만들기를 포함한 구성 단계는 다음과 같습니다.

gcloud

  1. 프로젝트 편집자 또는 프로젝트 소유자가 my-sa-webservermy-sa-database라는 서비스 계정을 만듭니다.

    gcloud iam service-accounts create my-sa-webserver \
        --display-name "webserver service account"
    
    gcloud iam service-accounts create my-sa-database \
        --display-name "database service account"
    
  2. 프로젝트 소유자가 Identity and Access Management(IAM) 정책을 설정하여 my-sa-webserver 서비스 계정에 대해 웹 서버 개발자 web-dev@example.comserviceAccountUser 역할을 할당합니다.

    gcloud iam service-accounts add-iam-policy-binding \
    my-sa-webserver@my-project.iam.gserviceaccount.com \
        --member='user:web-dev@example.com' \
        --role='roles/iam.serviceAccountUser'
    
  3. 프로젝트 소유자가 IAM 정책을 설정하여 데이터베이스 개발자 db-dev@example.com에게 서비스 계정 my-sa-databaseserviceAccountUser 역할을 할당합니다.

    gcloud iam service-accounts add-iam-policy-binding \
    my-sa-database@my-project.iam.gserviceaccount.com \
        --member='user:db-dev@example.com' \
        --role='roles/iam.serviceAccountUser'
    
  4. 인스턴스 관리자 역할을 부여받은 개발자 web-dev@example.com은 웹서버 인스턴스 템플릿을 만들고 인스턴스가 서비스 계정 my-sa-webserver으로 실행되도록 승인합니다.

    gcloud compute instance-templates create INSTANCE_TEMPLATE_NAME \
        --service-account my-sa-webserver@my-project-123.iam.gserviceaccount.com
    
  5. 인스턴스 관리자 역할을 부여받은 개발자 db-dev@example.com은 데이터베이스 인스턴스 템플릿을 만들고 인스턴스가 서비스 계정 my-sa-database으로 실행되도록 승인합니다.

    gcloud compute instance-templates create INSTANCE_TEMPLATE_NAME \
        --service-account my-sa-database@my-project-123.iam.gserviceaccount.com
    
  6. 보안 관리자가 my-sa-database 서비스 계정을 사용하는 VM의 포트 1443에 my-sa-webserver 서비스 계정을 사용하는 VM의 TCP 트래픽이 도달하도록 허용하는 방화벽 규칙을 만듭니다.

    gcloud compute firewall-rules create RULE_NAME \
        --network network_a \
        --allow TCP:1443 \
        --source-service-accounts my-sa-webserver@my-project.iam.gserviceaccount.com \
        --target-service-accounts my-sa-database@my-project.iam.gserviceaccount.com
    

문제 해결

VPC 방화벽 규칙을 만들거나 업데이트할 때의 오류 메시지

다음 오류 메시지 중 하나가 표시될 수 있습니다.

  • Should not specify destination range for ingress direction.

    목적지 범위는 인그레스 방화벽 규칙의 유효한 매개변수가 아닙니다. egress의 방향이 구체적으로 지정되지 않는 한 방화벽 규칙은 인그레스 규칙으로 간주됩니다. 방향을 지정하지 않는 규칙을 만드는 경우 목적지 범위를 허용하지 않는 인그레스 규칙으로 만들어집니다. 또한, 소스 범위는 이그레스 규칙의 유효한 매개변수가 아닙니다.

  • Firewall direction cannot be changed once created.

    기존 방화벽 규칙의 방향을 변경할 수 없습니다. 올바른 매개변수로 새 규칙을 만든 다음 기존 규칙을 삭제해야 합니다.

  • Firewall traffic control action cannot be changed once created.

    기존 방화벽 규칙의 작업을 변경할 수 없습니다. 올바른 매개변수로 새 규칙을 만든 다음 기존 규칙을 삭제해야 합니다.

  • Service accounts must be valid RFC 822 email addresses. 방화벽 규칙에 지정된 서비스 계정은 RFC 822에 따라 형식이 지정된 이메일 주소여야 합니다.

    gcloud compute firewall-rules create bad --allow tcp --source-service-accounts invalid-email
    
    Creating firewall...failed.
    ERROR: (gcloud.compute.firewall-rules.create) Could not fetch resource:
    – Invalid value for field 'resource.sourceServiceAccounts[0]': 'invalid-email'. Service accounts must be valid RFC 822 email addresses.
    
  • ServiceAccounts and Tags are mutually exclusive and can't be combined in the same firewall rule. 같은 규칙에서 서비스 계정과 태그를 모두 지정할 수는 없습니다.

    gcloud compute firewall-rules create bad --allow tcp --source-service-accounts test@google.com --target-tags target
    
    Creating firewall...failed.
     ERROR: (gcloud.compute.firewall-rules.create) Could not fetch resource:
    – ServiceAccounts and Tags are mutually exclusive and can't be combined in the same firewall rule.
    

리소스를 찾을 수 없음 오류

VPC 네트워크 또는 방화벽 규칙을 삭제할 때 다음과 비슷한 메시지가 표시될 수 있습니다. The resource "aet-uscentral1-subnet--1-egrfw" was not found.

이 오류가 발생하면 묵시적인 방화벽 규칙을 삭제하거나 세부정보를 보지 못하도록 차단할 수 있습니다. 이 상태의 방화벽 규칙은 VPC 네트워크 삭제를 차단할 수도 있습니다.

이러한 방식으로 차단된 방화벽 규칙 또는 네트워크를 삭제하려면 먼저 연결된 서버리스 VPC 액세스 커넥터를 삭제한 후 다시 시도합니다. 서버리스 VPC 액세스 커넥터를 삭제하는 방법에 대한 자세한 내용은 커넥터 삭제를 참조하세요.

너무 많은 큰 방화벽 오류

Google Compute Engine: The network contains too many large firewalls. 오류 메시지가 표시될 수 있습니다.

안전성 및 성능을 유지하기 위해 VPC 네트워크에서 구현할 수 있는 방화벽 규칙의 복잡성 및 개수가 제한됩니다. 이 오류가 표시되면 계정 관리팀에 문의해서 방화벽 규칙을 단순화하거나 통합하도록 요청합니다.

VM 인스턴스에 연결할 수 없음

VM 인스턴스에 연결할 수 없는 경우 방화벽 규칙을 확인하세요.

gcloud

  1. 다른 VM 인스턴스에서 연결을 시작하는 경우 그 인스턴스의 이그레스 방화벽 규칙을 나열합니다.

    gcloud compute firewall-rules list --filter network=NETWORK_NAME \
      --filter EGRESS \
      --sort-by priority \
      --format="table(
          name,
          network,
          direction,
          priority,
          sourceRanges.list():label=SRC_RANGES,
          destinationRanges.list():label=DEST_RANGES,
          allowed[].map().firewall_rule().list():label=ALLOW,
          denied[].map().firewall_rule().list():label=DENY,
          sourceTags.list():label=SRC_TAGS,
          sourceServiceAccounts.list():label=SRC_SVC_ACCT,
          targetTags.list():label=TARGET_TAGS,
          targetServiceAccounts.list():label=TARGET_SVC_ACCT
          )"
    

    NETWORK_NAME을 네트워크 이름으로 바꿉니다.

  2. 목적지 IP가 이그레스 규칙에서 거부되는지 확인합니다. 우선순위가 가장 높은 규칙(우선순위 번호가 가장 작음)이 우선순위가 낮은 규칙보다 우선합니다. 두 규칙의 우선순위가 같은 경우 거부 규칙이 우선합니다.

  3. 인그레스 방화벽 규칙에서 대상 VM 인스턴스가 포함된 네트워크를 확인합니다.

    gcloud compute firewall-rules list --filter network=NETWORK_NAME \
      --filter INGRESS \
      --sort-by priority \
      --format="table(
          name,
          network,
          direction,
          priority,
          sourceRanges.list():label=SRC_RANGES,
          destinationRanges.list():label=DEST_RANGES,
          allowed[].map().firewall_rule().list():label=ALLOW,
          denied[].map().firewall_rule().list():label=DENY,
          sourceTags.list():label=SRC_TAGS,
          sourceServiceAccounts.list():label=SRC_SVC_ACCT,
          targetTags.list():label=TARGET_TAGS,
          targetServiceAccounts.list():label=TARGET_SVC_ACCT
          )"
    

    NETWORK_NAME을 네트워크 이름으로 바꿉니다.

    샘플 출력입니다. 출력은 방화벽 규칙 목록에 따라 달라집니다.

    NAME                    NETWORK  DIRECTION  PRIORITY  SRC_RANGES    DEST_RANGES  ALLOW                         DENY  SRC_TAGS  SRC_SVC_ACCT      TARGET_TAGS  TARGET_SVC_ACCT
    default-allow-icmp      default  INGRESS    65534     0.0.0.0/0                  icmp
    default-allow-internal  default  INGRESS    65534     10.128.0.0/9               tcp:0-65535,udp:0-65535,icmp
    default-allow-rdp       default  INGRESS    65534     0.0.0.0/0                  tcp:3389
    default-allow-ssh       default  INGRESS    65534     0.0.0.0/0                  tcp:22
    firewall-with-sa        default  INGRESS    1000                                 tcp:10000                                     test1@google.com               target@google.com
    
  4. 또한 트래픽이 인그레스 또는 이그레스 방화벽 규칙에 의해 중단되는 경우 VPC 네트워크의 VM 인스턴스에서 다른 VPC 네트워크 또는 Google Cloud 외부 네트워크에 대한 연결 테스트를 실행하여 문제를 해결할 수 있습니다. 연결 테스트를 실행하여 다양한 시나리오에서 문제를 해결하는 방법에 대한 자세한 내용은 연결 테스트 실행을 참조하세요.

내 VPC 방화벽 규칙의 사용 설정 여부는 어떻게 알 수 있나요?

방화벽이 사용 설정되었는지, 아니면 사용 중지되었는지 보려면 방화벽 규칙 세부정보를 참조하세요.

Google Cloud 콘솔시행 섹션에서 사용 설정됨 또는 사용 중지됨을 찾습니다.

gcloud CLI 출력에서 disabled 필드를 찾습니다. disabled:false인 경우 규칙이 사용 설정되어 시행되고 있는 것입니다. disabled: true인 경우 규칙이 사용 중지된 것입니다.

VM 인스턴스에 적용되는 규칙

이 규칙을 만든 후 특정 인스턴스에서 규칙이 올바르게 적용되고 있는지 확인할 수 있습니다. 자세한 내용은 VM 인스턴스의 네트워크 인터페이스에 대한 방화벽 규칙 나열을 참조하세요.

소스 태그가 있는 VPC 방화벽 규칙은 즉시 적용되지 않음

소스 태그를 사용하는 인그레스 방화벽 규칙은 적용하는 데 시간이 걸릴 수 있습니다. 세부정보는 인그레스 방화벽 규칙의 소스 태그와 관련된 고려사항을 참조하세요.

다음 단계