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:
// ThingResource defines the resource implementation.// Some resource.Resource interface methods are omitted for brevity.type ThingResource struct { // client is configured via a Configure method, which is not shown in this // example for brevity. Refer to the Configure Resources documentation for // additional details for setting up resources with external clients. client *http.Client} // ThingResourceModel describes the Terraform resource data model to match the// resource schema.type ThingResourceModel struct { Name types.String `tfsdk:"name"` Id types.String `tfsdk:"id"`} // ThingResourceAPIModel describes the API data model.type ThingResourceAPIModel struct { Name string `json:"name"` Id string `json:"id"`} func (r ThingResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { resp.Schema = schema.Schema{ Attributes: map[string]schema.Attribute{ "name": schema.StringAttribute{ MarkdownDescription: "Name of the thing to be saved in the service.", Required: true, }, "id": schema.StringAttribute{ Computed: true, MarkdownDescription: "Service generated identifier for the thing.", PlanModifiers: []planmodifier.String{ stringplanmodifier.UseStateForUnknown(), }, }, }, MarkdownDescription: "Manages a thing.", }} func (r ThingResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { var data ThingResourceModel // Read Terraform plan data into the model resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } // Convert from Terraform data model into API data model createReq := ThingResourceAPIModel{ Name: data.Name.ValueString(), } httpReqBody, err := json.Marshal(createReq) if err != nil { resp.Diagnostics.AddError( "Unable to Create Resource", "An unexpected error occurred while creating the resource create request. "+ "Please report this issue to the provider developers.\n\n"+ "JSON Error: "+err.Error(), ) return } // Create HTTP request httpReq := http.NewRequestWithContext( ctx, http.MethodPost, "http://example.com/things", bytes.NewBuffer(httpReqBody), ) // Send HTTP request httpResp, err := d.client.Do(httpReq) defer httpResp.Body.Close() if err != nil { resp.Diagnostics.AddError( "Unable to Create Resource", "An unexpected error occurred while attempting to create the resource. "+ "Please retry the operation or report this issue to the provider developers.\n\n"+ "HTTP Error: "+err.Error(), ) return } // Return error if the HTTP status code is not 200 OK if httpResp.StatusCode != http.StatusOK { resp.Diagnostics.AddError( "Unable to Create Resource", "An unexpected error occurred while attempting to create the resource. "+ "Please retry the operation or report this issue to the provider developers.\n\n"+ "HTTP Status: "+httpResp.Status, ) return } var createResp ThingResourceAPIModel err := json.NewDecoder(httpResp.Body).Decode(&createResp) if err != nil { resp.Diagnostics.AddError( "Unable to Create Resource", "An unexpected error occurred while parsing the resource creation response. "+ "Please report this issue to the provider developers.\n\n"+ "JSON Error: "+err.Error(), ) return } // Convert from the API data model to the Terraform data model // and set any unknown attribute values. data.Id = types.StringValue(createResp.Id) // Save data into Terraform state resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)}
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.