0
0
Terraformcloud~30 mins

Mock providers in tests in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Mock Providers in Terraform Tests
📖 Scenario: You are working on a Terraform module that manages cloud resources. To ensure your module works correctly, you want to write tests that simulate cloud provider behavior without actually creating real resources.This helps you catch mistakes early and saves cloud costs.
🎯 Goal: Create a Terraform test configuration that uses a mock provider to simulate cloud resources.You will define a mock provider, configure it, and write a simple resource using the mock provider in your test.
📋 What You'll Learn
Create a mock provider block named mock
Configure the mock provider with a version constraint ~> 1.0
Define a resource mock_resource using the mock provider
Add a test configuration block that uses the mock provider
💡 Why This Matters
🌍 Real World
Mock providers let you test Terraform modules safely without creating real cloud resources, saving cost and time.
💼 Career
Cloud engineers and DevOps professionals use mock providers to write reliable infrastructure tests and ensure code quality.
Progress0 / 4 steps
1
Create a mock provider block
Create a Terraform provider block named mock with the source set to hashicorp/mock and version set to ~> 1.0.
Terraform
Need a hint?

Use the terraform block to specify required providers.

Then add a provider "mock" {} block.

2
Add a mock resource using the mock provider
Add a resource block named mock_resource of type mock_resource using the mock provider. Set the resource name to example and add an attribute name with value test-resource.
Terraform
Need a hint?

Use resource "mock_resource" "example" {} and inside set provider = mock and name = "test-resource".

3
Add a test configuration block
Add a terraform block with a required_version set to >= 1.0 and a required_providers block specifying the mock provider with source hashicorp/mock and version ~> 1.0. This simulates the test environment.
Terraform
Need a hint?

Set required_version inside the terraform block to >= 1.0.

4
Complete the mock provider test setup
Add a provider block for mock with no arguments to complete the test setup.
Terraform
Need a hint?

Just add provider "mock" {} block.