To assign a static IP address to a Compute Engine instance in GCP, follow these steps:
1. Reserve a static IP address:
GCP Console:
a. Go to the GCP Console: https://console.cloud.google.com/
b. Navigate to VPC Network > External IP addresses.
c. Click on the “Reserve Static Address” button at the top of the page.
d. Enter a name for the static IP address, choose a region, and make sure the “IP version” is set to IPv4.
e. Click the “Reserve” button.
gcloud CLI:
a. Run the following command to reserve a static IP address:
gcloud compute addresses create STATIC_IP_NAME --region REGION
Replace STATIC_IP_NAME
and REGION
with appropriate values.
2. Assign the static IP address to the instance:
GCP Console:
a. Navigate to Compute Engine > VM instances.
b. Click on the instance you want to assign the static IP address to.
c. Click on the “Edit” button at the top of the instance details page.
d. Scroll down to the “Network interfaces” section and click on the “Edit” (pencil) button next to the network interface.
e. Under “External IP”, select the static IP address you reserved earlier from the dropdown menu.
f. Click the “Done” button, and then click the “Save” button at the bottom of the page.
gcloud CLI:
a. First, get the static IP address using the following command:
gcloud compute addresses describe STATIC_IP_NAME --region REGION --format="get(address)"
Replace STATIC_IP_NAME
and REGION
with appropriate values.
b. Then, run the following command to assign the static IP address to the instance:
gcloud compute instances add-access-config INSTANCE_NAME --zone ZONE --access-config-name "external-nat" --address STATIC_IP_ADDRESS
Replace INSTANCE_NAME
, ZONE
, and STATIC_IP_ADDRESS
(obtained in the previous step) with appropriate values.
3. Using Terraform:
To assign a static IP address to a Compute Engine instance using Terraform, first create a google_compute_address
resource, and then reference the address in a google_compute_instance
resource.
a. Modify your main.tf
file to include the following resources:
resource "google_compute_address" "static" {
name = "STATIC_IP_NAME"
region = "REGION"
}
resource "google_compute_instance" "example" {
# ... other configuration ...
network_interface {
network = "default"
access_config {
nat_ip = google_compute_address.static.address
}
}
# ... other configuration ...
}
Replace STATIC_IP_NAME
and REGION
with appropriate values.
b. Run the following commands to apply the changes:
terraform init
terraform plan
terraform apply
This will create a new static IP address and assign it to the specified Compute Engine instance.
Leave a Reply