Applying a firewall rule to a specific Compute Engine instance in GCP can be achieved by using network tags. Network tags are used to identify instances when defining firewall rules. Here’s how to apply a firewall rule to a specific instance using GCP Console, gcloud CLI, and Terraform:
1. Using GCP Console:
a. Go to the GCP Console: https://console.cloud.google.com/
b. Navigate to Compute Engine > VM instances.
c. Click on the instance you want to apply the firewall rule to.
d. Click the “Edit” button at the top of the page.
e. In the “Network tags” section, add a new tag (e.g., “allow-ssh”).
f. Navigate to VPC network > Firewall.
g. Click on the “Create firewall rule” button.
h. Configure the firewall rule settings, and under “Target tags,” enter the tag you added to the instance (e.g., “allow-ssh”).
i. Click the “Create” button to create the firewall rule. The rule will now be applied to the instance with the specified tag.
2. Using gcloud CLI:
a. First, add a network tag to the instance:
gcloud compute instances add-tags INSTANCE_NAME --tags allow-ssh --zone ZONE
Replace INSTANCE_NAME
and ZONE
with appropriate values.
b. Create a firewall rule that targets the tag:
gcloud compute firewall-rules create RULE_NAME --allow PROTOCOL:PORT --target-tags allow-ssh
Replace RULE_NAME
, PROTOCOL
, and PORT
with appropriate values.
3. Using Terraform:
a. Modify your main.tf
file to include the following resources:
resource "google_compute_instance" "example" {
# ... existing configuration ...
tags = ["allow-ssh"]
}
resource "google_compute_firewall" "example" {
name = "example-firewall-rule"
network = "default"
allow {
protocol = "PROTOCOL"
ports = ["PORT"]
}
target_tags = ["allow-ssh"]
}
Replace PROTOCOL
and PORT
with appropriate values.
b. Run the following commands to apply the changes:
terraform init
terraform plan
terraform apply
This will create a firewall rule targeting the instance with the “allow-ssh” tag. The rule will only be applied to instances that have the specified tag.
Leave a Reply