terraformterraform-provider

terraform plugin that enforces the existence of a resource


I'm developing a terraform plugin using the plugin framework. I have defined my resources, and users can add and remove them and things are working. However, there's one resource that's required. I can't figure out how to fail the whole thing if that resource isn't listed. I'd like to fail quickly, before any other resources are changed.

Is it possible to validate the plan for the existence of a resource before taking any REST actions?

I see there are things like Validate Configuration on the terraform site, which talks about ValidateResourceConfig but then just shows me an picture of RPC.

My Provider() function returns a schema.Provider{} with ResourceMap, DataSourceMap, ConfigureCOntextFunc, and Schema set. Do I need to implement a Provider myself to get validation calls? Any examples would be very helpful.


Solution

  • Terraform providers work on a resource-by-resource basis, and so if there is no resource block of the type of resource you want to check for then Terraform will never ask for any resources of that type to be validated.

    A provider does not ever get access to the full global scope of everything in a configuration -- Terraform Core only asks it about one resource at a time -- so I don't think it will be possible to meet your requirement using only provider logic.

    A requirement for an object of a particular type to be declared seems like something that would normally be considered a policy decision in typical Terraform usage, and that sort of thing would be implemented outside of Terraform in some wrapping automation that serves effectively as an automatic plan reviewer.

    To implement such a thing, the usual steps would be:

    1. Create and save a plan using terraform plan -out=tfplan

    2. Use terraform show -json tfplan to obtain a machine-readable description of the plan in JSON format.

    3. Use a custom program you design yourself to check whether the plan meets your policy rules.

      In your case, I would expect to search across all of the resource instances mentioned in the planned_values section of the plan output -- which describes the "desired state" -- and fail if there isn't at least one with whose provider address and resource type match the one you want to require.

    Terraform is not designed to enforce such a requirement itself.