简体   繁体   中英

callback with results of apply in terraform provider

I'm writing a custom terraform provider. I need to wrap the calls to the backed API in a "session", opening it before any calls are made and then closing it once all the terraform calls have completed.

Opening the session is straightforward, I can do that in the ConfigureContextFunc of the schema.Provider. Is there a way to set up a callback (or something) at the end of the application so I can close/"finalize" the session? I can imagine something specific to my resources, but that seems hacky. In my dream world I'd also be able to fail the apply if the close had an error.

Absent a nice finalize call is there a way to access the plan that I could use to determine that the current call is the last needed for the apply?

Update: I thought I could use a StopContext:

stopCtx, ok := schema.StopContext(ctx)
    ...
    go func(ctx context.Context) {
        // Wait for stop context cancellation
        <-stopCtx.Done()
        ...
    }

However, this is both deprecated and seems to only get called when stopping due to some outside trigger, like SIGINT, and not a regular exit (at least that's what I've been seeing).

After a fair amount of floundering I have what I believe to be a reasonable solution, and it even matches @Ben Hoyt's comment. We can defer and teardown in main.


func main() {
    var prov *schema.Provider
    defer func() {
        xyz.PrividerTeardown(prov)
    }()
    plugin.Serve(&plugin.ServeOpts{
        ProviderFunc: func() *schema.Provider {
            prov = xyz.Provider()
            return prov
        },
    })
}

I'll note that my comment on the question about not being around when the provider is made is incorrect. The provider is made in a main function in the provider code. In my (flimsy) defense I used the example scaffolding so that code came pre-written.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM