Create Resources
Creation is part of the basic Terraform lifecycle for managing resources. During the terraform apply
command, Terraform calls the provider ApplyResourceChange
RPC, in which the framework calls the resource.Resource
interface Create
method. The request contains Terraform configuration and plan data. The response expects the applied Terraform state data, including any computed values. The data is defined by the schema of the resource.
Other resource lifecycle implementations include:
- Read resources by receiving Terraform prior state data, performing read logic, and saving refreshed Terraform state data.
- Update resources in-place by receiving Terraform prior state, configuration, and plan data, performing update logic, and saving updated Terraform state data.
- Delete resources by receiving Terraform prior state data and performing deletion logic.
Define Create Method
Implement the Create
method by:
- Accessing the data from the
resource.CreateRequest
type. Most use cases should access the plan data in theresource.CreateRequest.Plan
field. - Performing logic or external calls to create and/or run the resource.
- Writing state data into the
resource.CreateResponse.State
field.
If the logic needs to return warning or error diagnostics, they can added into the resource.CreateResponse.Diagnostics
field.
In this example, the resource is setup to accept a configuration value that is sent in a service API creation call:
Caveats
Note these caveats when implementing the Create
method:
- An error is returned if the response state contains unknown values. Set all attributes to either null or known values in the response.
- An error is returned if the response state has the
RemoveResource()
method called. This method is not valid during creation. - An error is returned unless every null or known value in the request plan is saved exactly as-is into the response state. Only unknown plan values can be modified.
- Any response errors will cause Terraform to mark the resource as tainted for recreation on the next Terraform plan.
Recommendations
Note these recommendations when implementing the Create
method:
- Get request data from the Terraform plan data over configuration data as the schema or resource may include plan modification logic which sets plan values.
- Return errors that signify there is an existing resource. Terraform practitioners expect to be notified if an existing resource needs to be imported into Terraform rather than created. This prevents situations where multiple Terraform configurations unexpectedly manage the same underlying resource.