diff --git a/cloudsmith/provider.go b/cloudsmith/provider.go index c7487f5..c8fae78 100644 --- a/cloudsmith/provider.go +++ b/cloudsmith/provider.go @@ -27,6 +27,12 @@ func Provider() *schema.Provider { Optional: true, DefaultFunc: schema.EnvDefaultFunc("CLOUDSMITH_API_HOST", "https://api.cloudsmith.io/v1"), }, + "headers": { + Type: schema.TypeMap, + Elem: &schema.Schema{Type: schema.TypeString}, + Description: "Additional HTTP headers to include in API requests", + Optional: true, + }, }, DataSourcesMap: map[string]*schema.Resource{ "cloudsmith_namespace": dataSourceNamespace(), @@ -72,8 +78,9 @@ func Provider() *schema.Provider { apiHost := requiredString(d, "api_host") apiKey := requiredString(d, "api_key") userAgent := fmt.Sprintf("(%s %s) Terraform/%s", runtime.GOOS, runtime.GOARCH, terraformVersion) + headers := d.Get("headers").(map[string]interface{}) - return newProviderConfig(apiHost, apiKey, userAgent) + return newProviderConfig(apiHost, apiKey, headers, userAgent) } return p diff --git a/cloudsmith/provider_config.go b/cloudsmith/provider_config.go index 92f6860..c029eb9 100644 --- a/cloudsmith/provider_config.go +++ b/cloudsmith/provider_config.go @@ -3,6 +3,7 @@ package cloudsmith import ( "context" "errors" + "fmt" "net/http" "github.com/cloudsmith-io/cloudsmith-api-go" @@ -20,17 +21,21 @@ type providerConfig struct { APIClient *cloudsmith.APIClient } -func newProviderConfig(apiHost, apiKey, userAgent string) (*providerConfig, diag.Diagnostics) { +func newProviderConfig(apiHost string, apiKey string, headers map[string]interface{}, userAgent string) (*providerConfig, diag.Diagnostics) { if apiKey == "" { return nil, diag.FromErr(errMissingCredentials) } httpClient := http.DefaultClient - httpClient.Transport = logging.NewSubsystemLoggingHTTPTransport("Cloudsmith", http.DefaultTransport) + httpClient.Transport = logging.NewSubsystemLoggingHTTPTransport("Cloudsmith", &headerTransport{ + headers: headers, + rt: http.DefaultTransport, + }) config := cloudsmith.NewConfiguration() config.Debug = logging.IsDebugOrHigher() config.HTTPClient = httpClient + config.Servers = cloudsmith.ServerConfigurations{ {URL: apiHost}, } @@ -58,3 +63,15 @@ func (pc *providerConfig) GetAPIKey() string { apiKeys, _ := pc.Auth.Value(cloudsmith.ContextAPIKeys).(map[string]cloudsmith.APIKey) return apiKeys["apikey"].Key } + +type headerTransport struct { + headers map[string]interface{} + rt http.RoundTripper +} + +func (t *headerTransport) RoundTrip(req *http.Request) (*http.Response, error) { + for k, v := range t.headers { + req.Header.Add(k, fmt.Sprint(v)) + } + return t.rt.RoundTrip(req) +}