Custom Providers with Terraform
In Terraform, a Provider is the logical abstraction of an upstream API. In this lab, you will learn how to build a custom provider for Terraform. Terraform supports a plugin model, and all providers are actually plugins. Plugins are distributed as Go binaries. Although technically possible to write a plugin in another language, almost all Terraform plugins are written in Go.
In this lab, you will build a custom provider for Terraform by:
- Building the plugin
- Defining resources
- Invoking the provider
- Learning about error handling and partial state
- Implementing the destroy and read functions
For this lab, you should have experience with the following:
Familarity with Linux editor like
Setup and Requirements
Before you click the Start Lab button
Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.
This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.
To complete this lab, you need:
- Access to a standard internet browser (Chrome browser recommended).
- Time to complete the lab---remember, once you start, you cannot pause a lab.
How to start your lab and sign in to the Google Cloud Console
Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:
- The Open Google Console button
- Time remaining
- The temporary credentials that you must use for this lab
- Other information, if needed, to step through this lab
Click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page.
Tip: Arrange the tabs in separate windows, side-by-side.
Note: If you see the Choose an account dialog, click Use Another Account.
If necessary, copy the Username from the Lab Details panel and paste it into the Sign in dialog. Click Next.
Copy the Password from the Lab Details panel and paste it into the Welcome dialog. Click Next.
Important: You must use the credentials from the left panel. Do not use your Google Cloud Skills Boost credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
Click through the subsequent pages:
- Accept the terms and conditions.
- Do not add recovery options or two-factor authentication (because this is a temporary account).
- Do not sign up for free trials.
After a few moments, the Cloud Console opens in this tab.
Activate Cloud Shell
Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.
Click Activate Cloud Shell at the top of the Google Cloud console.
It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. The output contains a line that declares the PROJECT_ID for this session:
gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.
(Optional) You can list the active account name with this command:
(Optional) You can list the project ID with this command:
gcloud, in Google Cloud, refer to the gcloud CLI overview guide.
Requirement of Custom Providers
Some examples of when to author a custom Terraform provider:
An internal private cloud whose functionality is either proprietary or would not benefit the open source community.
A "work in progress" provider being tested locally before contributing back.
Extensions of an existing provider.
The provider schema
In Cloud shell, create a file named
provider.go. This is the root of the provider.
Click the Open Editor button on the toolbar of Cloud Shell. (You can switch between Cloud Shell and the code editor by using the Open Editor and Open Terminal icons as required, or click the Open in new window button to leave the Editor open in a separate tab).
In the Editor, add the following content to the
The helper/schema library is part of Terraform Core. It abstracts many of the complexities and ensures consistency between providers. The example above defines an empty provider (there are no resources).
*schema.Provider type describes the provider's properties including:
the configuration keys it accepts
the resources it supports
any callbacks to configure
Building the Plugin
Go requires a
main.go file, which is the default executable when the binary is built.
Create a file named
Since Terraform plugins are distributed as Go binaries, it is important to define this entry-point, which you'll do by adding the following code in the editor window to the
This establishes the main function to produce a valid, executable Go binary. The contents of the main function consume Terraform's plugin library. This library deals with all the communication between Terraform core and the plugin.
Create a module for your Terraform Go packages:
Download and install Terraform packages and dependencies.
Next, build the plugin using the Go toolchain:
The output name (-o) is very important. Terraform searches for plugins in the format of:
In the case above, the plugin is of type provider and of name example.
List out the contents of the directory.
To verify things are working correctly, execute the binary you just created:
Your file tree should look like this:
Terraform providers manage resources. A provider is an abstraction of an upstream API, and a resource is a component of that provider. As an example, the Google provider supports
As a general convention, Terraform providers put each resource in their own file, named after the resource, prefixed with
Create an example_server and name it
Add the following code to the
This uses the
schema.Resource type. This structure defines the data schema and CRUD operations for the resource. Defining these properties are the only required thing to create a resource.
The schema above defines one element, address, which is a required string. Terraform's schema automatically enforces validation and type casting.
Next there are four fields defined -
Delete. The Create, Read, and Delete functions are required for a resource to be functional. There are other functions, but these are the only required ones. Terraform itself handles which function to call and with what data. Based on the schema and current state of the resource, Terraform can determine whether it needs to create a new resource, update an existing one, or destroy.
Each of the four struct fields point to a function. While it is technically possible to inline all functions in the resource schema, best practice dictates pulling each function into its own method. This optimizes for both testing and readability. You will fill in those stubs now, paying close attention to method signatures.
resource_server.gofile and add the following contents at the end of the file.
Lastly, update the provider schema in
provider.goto register the new example_server resource.
Build and test the plugin. Everything should compile as-is, although all operations are a no-op.
The layout now looks like this:
Move the Provider to Plugins Directory
With Terraform 0.13+, you must specify all required providers and their respective source in your Terraform configuration. A provider source string is comprised of hostname/namespace/name.
When you run
terraform init, Terraform will attempt to download the provider from the Terraform Registry.
If Terraform can't download the provider from the Terraform Registry (for example if the provider is local, or because of firewall restrictions), you can specify the installation method configuration explicitly. Otherwise, Terraform will implicitly attempt to find the provider locally in the appropriate subdirectory within the user plugins directory,
In order to use the local example provider you built, you'll move it into the proper subdirectory and then, later in the lab, point to that location in a
First, create the directory:
Then, copy the
terraform-provider-example binary into that location:
Invoking the Provider
Previous sections showed running the provider directly via the shell, which outputs a warning message like:
Terraform plugins should be executed by Terraform directly. To test this, create a
main.tfin the working directory (the same place where the plugin exists).
Next, add the following content to the
Take note of the source and version included in the
required_providers block. When the init command is executed, terraform will search for the example provider in the plugins folder with these specifications.
terraform initto discover the newly compiled Provider:
This validates Terraform is correctly delegating work to your plugin and that your validation is working as intended.
Fix the validation error by adding an
addressfield to the
terraform planto verify the validation is passing:
You can optionally run
terraform apply, but it will be a no-op because all of the resource options currently take no action.
Navigate to the
resource_server.gofile. Implement the
Createfunctionality by making the following update:
This uses the schema.ResourceData API to get the value of address provided by the user in the Terraform configuration. Due to the way Go works, we have to typecast it to string. This is a safe operation, however, since our schema guarantees it will be a string type.
Next, it uses SetId, a built-in function, to set the ID of the resource to the address. The existence of a non-blank ID is what tells Terraform that a resource was created. This ID can be any string value, but should be a value that can be used to read the resource again.
Finally, you must recompile the binary and instruct Terraform to reinitialize it by rerunning
terraform init. This is only necessary because you have modified the code and recompiled the binary and it no longer matches an internal hash Terraform uses to ensure the same binaries are used for each operation.
Recompile and reinitialize the Provider:
Move your provider into the plugins subdirectory with a new version:
main.tfto use new 1.0.1 version:
Terraform will ask for confirmation when you run
terraform apply. Enter yes to create your example server and commit it to state:
SetId, Terraform believes the resource created successfully. Verify this by running
Again, because of the call to
SetId, Terraform believes the resource was created. When running
plan, Terraform properly determines there are no changes to apply.
To verify this behavior, first change the value of the address field then run terraform plan again.
You should see output like this:
Terraform detects the change and displays a diff with a ~ prefix, noting the resource will be modified in place, rather than created new.
terraform applyto apply the changes. Terraform will again prompt for confirmation. Type
Since you didn't implement the Update function, you would expect the terraform plan operation to report changes, but it does not! How were your changes persisted without the Update implementation?
Error handling & partial state
Previously your Update operation succeeded and persisted the new state with an empty function definition. Navigate to the
resource_server.go file and recall the current update function:
return nil tells Terraform that the update operation succeeded without error. Terraform assumes this means any changes requested applied without error. Because of this, our state updated and Terraform believes there are no further changes.
To say it another way: if a callback returns no error, Terraform automatically assumes the entire diff successfully applied, merges the diff into the final state, and persists it.
Functions should never intentionally
panic or call
os.Exit - always return an error.
In reality, it is a bit more complicated than this. Imagine the scenario where our update function has to update two separate fields which require two separate API calls. What do we do if the first API call succeeds but the second fails? How do we properly tell Terraform to only persist half the diff? This is known as a partial state scenario, and implementing these properly is critical to a well-behaving provider.
Here are the rules for state updating in Terraform.
- If the Create callback returns with or without an error without an ID set using
SetId, the resource is assumed to not be created, and no state is saved.
- If the Create callback returns with or without an error and an ID has been set, the resource is assumed created and all state is saved with it. Repeating because it is important: if there is an error, but the ID is set, the state is fully saved.
- If the Update callback returns with or without an error, the full state is saved. If the ID becomes blank, the resource is destroyed (even within an update, though this shouldn't happen except in error scenarios).
- If the Destroy callback returns without an error, the resource is assumed to be destroyed, and all state is removed.
- If the Destroy callback returns with an error, the resource is assumed to still exist, and all prior state is preserved.
- If partial mode (covered next) is enabled when a create or update returns, only the explicitly enabled configuration keys are persisted, resulting in a partial state.
Here is an example of a partial mode with an update function:
Note - this code will not compile since there is no
updateAddress function. You can implement a dummy version of this function to play around with partial state. For this example, partial state does not mean much. If
updateAddress were to fail, then the address field would not be updated.
The Destroy callback is exactly what it sounds like - it is called to destroy the resource. This operation should never update any state on the resource. It is not necessary to call
d.SetId(""), since any non-error return value assumes the resource was deleted successfully.
Add the Destroy callback function in
The Destroy function should always handle the case where the resource might already be destroyed (manually, for example). If the resource is already destroyed, this should not return an error. This allows Terraform users to manually delete resources without breaking Terraform.
Recompile the Provider:
Place it in the proper plugins subdirectory with a new version numbers:
main.tfto use new 1.0.2 version:
terraform destroyto destroy the resource. When prompted for confirmation, type
The Read callback is used to sync the local state with the actual state (upstream). This is called at various points by Terraform and should be a read-only operation. This callback should never modify the real resource.
If the ID is updated to blank, this tells Terraform the resource no longer exists (maybe it was destroyed out of band). Just like the destroy callback, the Read function should gracefully handle this case.
Update the Read callback function in
In this lab, you built a custom provider for Terraform. You accomplished this by building a plugin, defining resources, learning about error handling and partial state, and implementing a few Terraform functions.
Finish Your Quest
This self-paced lab is part of the Managing Cloud Infrastructure with Terraform Quest. A Quest is a series of related labs that form a learning path. Completing this Quest earns you the badge above, to recognize your achievement. You can make your badge public and link to them in your online resume or social media account. Enroll in this Quest and get immediate completion credit if you've taken this lab. See other available Qwiklabs Quests.
Take Your Next Lab
Continue your Quest with Cloud SQL with Terraform, or check out these suggestions:
Next Steps / Learn More
- Add Next Steps
Google Cloud training and certification
...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.
Manual Last Updated June 05, 2022
Lab Last Tested June 05, 2022
Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.