Skip to content

Commit

Permalink
tailscale: use a custom User-Agent header while making API requests
Browse files Browse the repository at this point in the history
This passes a custom user-agent header value to the API client for
making HTTP requests.

It uses an existing UserAgent helper provided by the plugin SDK:
https://github.com/hashicorp/terraform-plugin-sdk/blob/8bde488a9529d281bc6858ca2b0a3708c2f93658/helper/schema/provider.go#L489

Signed-off-by: Anton Tolchanov <[email protected]>
  • Loading branch information
knyar committed Aug 17, 2023
1 parent da3ced6 commit 685f729
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
16 changes: 15 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,24 @@ import (
"github.com/tailscale/terraform-provider-tailscale/tailscale"
)

// version is filled by goreleaser at build time.
var version = "dev"

func main() {
plugin.Serve(&plugin.ServeOpts{
ProviderFunc: func() *schema.Provider {
return tailscale.Provider()
return tailscale.Provider(addUserAgent)
},
})
}

// addUserAgent adds a `user_agent` configuration key to the provider with a
// default value based on provider version.
func addUserAgent(p *schema.Provider) {
p.Schema["user_agent"] = &schema.Schema{
Type: schema.TypeString,
Default: p.UserAgent("terraform-provider-tailscale", version),
Optional: true,
Description: "User-Agent header for API requests",
}
}
4 changes: 4 additions & 0 deletions tailscale/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ func providerConfigure(_ context.Context, d *schema.ResourceData) (interface{},
return nil, diag.Errorf("tailscale provider argument 'oauth_client_secret' is empty")
}

userAgent := d.Get("user_agent").(string)

if oauthClientID != "" && oauthClientSecret != "" {
var oauthScopes []string
oauthScopesFromConfig := d.Get("scopes").([]interface{})
Expand All @@ -121,6 +123,7 @@ func providerConfigure(_ context.Context, d *schema.ResourceData) (interface{},
"",
tailnet,
tailscale.WithBaseURL(baseURL),
tailscale.WithUserAgent(userAgent),
tailscale.WithOAuthClientCredentials(oauthClientID, oauthClientSecret, oauthScopes),
)
if err != nil {
Expand All @@ -134,6 +137,7 @@ func providerConfigure(_ context.Context, d *schema.ResourceData) (interface{},
apiKey,
tailnet,
tailscale.WithBaseURL(baseURL),
tailscale.WithUserAgent(userAgent),
)
if err != nil {
return nil, diagnosticsError(err, "failed to initialise client")
Expand Down

0 comments on commit 685f729

Please sign in to comment.