Hello community,
I need some help to understand Terraform Test Mocks.
Use case:
I want to write a test for my uptime check in Google-Cloud-Platform (GCP). This resource require a compute instance (virtual machines in GCP), so it can checks the uptime of this compute instance. I don’t want to create a compute instance for this test, I only want to create a “uptime check”, a “alert”, and some other related resources in my Terraform module.
So the idea is to mock this compute instance, instead of creating a separate instance for testing.
My problem:
At one point in my test I want to tell my “uptime check” use the mock_compute_instance and don’t try to find a real instance in the infrastructure. In my Terraform code I have two Parameter instance_id and instance_name which I normally use to connect my “uptime check” to a real “compute instance”. I guess I can reference here the mock object. I am right? But if I execute Terrafrom test it returns:
tests/uptime_check_mock.tftest.hcl... in progress
run "deployment_test"... fail
╷
│ Error: Invalid reference
│
│ on tests/uptime_check_mock.tftest.hcl line 38, in run "deployment_test":
│ 38: instance_id = data.google.google_mock.google_compute_instance
│
│ You can only reference earlier run blocks, file level, and global variables while defining variables from inside a run block.
The code:
mock_provider "google" {
alias = "google_mock"
mock_data "google_compute_instance" {
defaults = {
name = "tf-test-mock-vm"
instance_id = "654321"
instance_name = "HuggaBugga"
}
}
}
variables {
project_id = "test-project"
region = "europe-west3"
# HERE I WANT TO REFERENCE THE MOCKED COMPUTE INSTANCE which is not working
#instance_id = google.google_mock.mock_data.google_compute_instance
#instance_name = data.google_compute_instance
}
run "deployment_test" {
command = apply
providers = {
google = google.google_mock
}
variables {
display_name = "Terraform-Test uptime check for vm instance"
tcp_port = "80"
period = "60s"
}
module {
# Here I create the uptime check which should be tested
source = "./"
}
}
As you can see in my example code above I create a a mock_provider and inside of it I create a mock_data object which I fill with parameters. Now I want to use this data_mock object and let the “uptime check” use it. I not know how to reference to the mocked data or resource object.
I followed mainly this documentation and search in the forum without any clear answer for me.
Can somebody provide my an example?
Thank you in advance.