Getting a callback after a successful apply

I’m writing a custom provider using terraform-plugin-sdk/v2 . I’d like to be able to bookend the REST calls generated during an apply inside a transaction. I need to find a callback (or some other mechanism) for running code when all the step of the apply have occurred.

Opening the transaction is easy, I do it in the ConfigureContextFunc of my provider. I can close it in the failure case in the various calls or via schema.StopContext (which I understand is deprecated). However, I can’t figure out how to close it when things are successful. StopContext seems to only be called on “non-standard” exits and I can’t defer the closing because I’m not making the provider.

Is there a way to know when the plan’s actions are complete?

Is there a way to get the plan for the provider so that I can keep track of the status in the provider?

It would be even better if whatever mechanism we find lets me fail the apply.

Here’s where I ended up. The Provider() call does the setup and the defer is doing the teardown.

func main() {
	var prov *schema.Provider
	defer func() {
		ProviderFunc: func() *schema.Provider {
			prov = xyz.Provider()
			return prov

One thing that threw me was the docs for plugin.Serve

Serve serves a plugin. This function never returns and should be the final function called in the main function of the plugin.

It turns out that when the terraform action is done and the plugin is no longer needed, Serve does return and allows our defer to run. I did need to keep track of success or failure of all the calls that were made while Serve was active to know the status in my ProviderTeardown, but it is working.

This behavior seems reasonable, returning to main, but is it something I can rely upon going forward, given the documentation?