Firewall
In this exercise you will create firewall rules to allow SSH and HTTP access to the Compute Engine instance created in your custom VPC.
Exercises
- Create
resourceblock with typegoogle_compute_firewallnamedallow-httpname="${var.name}-fw-allow-http"network=google_compute_network.default.nametarget_tags=["http"]source_ranges=["0.0.0.0/0"]- Remember to set the
projectas well - In the
allowblock, setprotocoltotcpandportto the usual HTTP port80
- Create another
google_compute_firewallresource namedallow-sshname="${var.name}-fw-allow-ssh"network=google_compute_network.default.nametarget_tags=["ssh"]source_ranges=["0.0.0.0/0"]- Remember to set the
projectas well - In the
allowblock, setprotocoltotcpandportto the usual SSH port22
Extra
- Move the
projectconfiguration to the provider's configuration- This way, you don't have to specify it explicitly in each of the resources now that all resources are in the same project
- Create a reusable module called
my-firewallin a subdirectory calledmodules/- Put the two firewall resources there, and define the needed inputs in
variables.tf- Hint: At least the
nameis used. What other parameters need to be referenced?
- Hint: At least the
- Using modules is similar to resources, but have a
moduleblock with a "name"- Hint:
module "firewall" {}
- Hint:
- You will also need to specify a
sourcein thecompute_engine.tffile to reference your module- Hint:
source = "./modules/my-firewall"
- Hint:
- Remember to
terraform initagain, after adding a new module to be used
- Put the two firewall resources there, and define the needed inputs in
Check your configuration
Once again check your configuration first:
terraform plan
Apply your configuration
And to apply, the usual:
terraform apply
Note
If you did the extra exercise above after the initial terraform apply, you will have the resource in the state already.
You can then use terraform state mv to move the resource within the state, so it is not recreated!
The instance is now accessible from everywhere, since we added 0.0.0.0/0 as the source_ranges. How do we access it? Unless an output is added, we don't know the IP address. Or do we?
It is in the Terraform state:
terraform state show google_compute_instance.default
Get the IP address there, from the network_interface access_config block, and try it out with your browser. You should see the default page of Apache2.
Answer
terraform/iam.tf
resource "google_compute_firewall" "allow-http" {
name = "${var.name}-fw-allow-http"
network = google_compute_network.default.name
project = var.project
allow {
protocol = "tcp"
ports = ["80"]
}
target_tags = ["http"]
source_ranges = ["0.0.0.0/0"]
}
resource "google_compute_firewall" "allow-ssh" {
name = "${var.name}-fw-allow-ssh"
network = google_compute_network.default.name
project = var.project
allow {
protocol = "tcp"
ports = ["22"]
}
target_tags = ["ssh"]
source_ranges = ["0.0.0.0/0"]
}
Next
Next, we create a Load Balancer in front of the Compute Engine instance.