Skip to content

Commit 617e2d2

Browse files
Christian DoucetteChristian Doucette
authored andcommitted
Refactor based on review comments
1 parent 4c8fb8d commit 617e2d2

File tree

4 files changed

+67
-44
lines changed

4 files changed

+67
-44
lines changed

internal/client/client.go

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -74,17 +74,35 @@ func getTokenFromCreds(services *disco.Disco, hostname svchost.Hostname) string
7474
return ""
7575
}
7676

77+
// TFE Client along with other necessary information for the provider to run it
78+
type ProviderClient struct {
79+
TfeClient *tfe.Client
80+
tokenSource TokenSource
81+
}
82+
83+
// Using presence of TFC_AGENT_VERSION to determine if this provider is running on HCP Terraform / enterprise
84+
func providerRunningInCloud() bool {
85+
_, envVariablePresent := os.LookupEnv("TFC_AGENT_VERSION")
86+
return envVariablePresent
87+
}
88+
89+
func (pc *ProviderClient) SendAuthenticationWarning() bool {
90+
return pc.tokenSource == CredentialFiles && providerRunningInCloud()
91+
92+
}
93+
7794
// GetClient encapsulates the logic for configuring a go-tfe client instance for
7895
// the provider, including fallback to values from environment variables. This
7996
// is useful because we're muxing multiple provider servers together and each
8097
// one needs an identically configured client.
8198
//
8299
// Internally, this function caches configured clients using the specified
83100
// parameters
84-
func GetClient(tfeHost, token string, insecure bool) (*tfe.Client, bool, error) {
85-
config, sendCredentialDeprecationWarning, err := configure(tfeHost, token, insecure)
101+
func GetClient(tfeHost, token string, insecure bool) (*ProviderClient, error) {
102+
config, err := configure(tfeHost, token, insecure)
103+
86104
if err != nil {
87-
return nil, sendCredentialDeprecationWarning, err
105+
return nil, err
88106
}
89107

90108
clientCache.Lock()
@@ -93,13 +111,13 @@ func GetClient(tfeHost, token string, insecure bool) (*tfe.Client, bool, error)
93111
// Try to retrieve the client from cache
94112
cached := clientCache.GetByConfig(config)
95113
if cached != nil {
96-
return cached, sendCredentialDeprecationWarning, nil
114+
return &ProviderClient{cached, config.TokenSource}, nil
97115
}
98116

99117
// Discover the Terraform Enterprise address.
100118
host, err := config.Services.Discover(config.TFEHost)
101119
if err != nil {
102-
return nil, sendCredentialDeprecationWarning, fmt.Errorf("failed to create client: %w", err)
120+
return nil, fmt.Errorf("failed to create client: %w", err)
103121
}
104122

105123
// Get the full Terraform Enterprise service address.
@@ -109,7 +127,7 @@ func GetClient(tfeHost, token string, insecure bool) (*tfe.Client, bool, error)
109127
service, err := host.ServiceURL(tfeServiceID)
110128
target := &disco.ErrVersionNotSupported{}
111129
if err != nil && !errors.As(err, &target) {
112-
return nil, sendCredentialDeprecationWarning, fmt.Errorf("failed to create client: %w", err)
130+
return nil, fmt.Errorf("failed to create client: %w", err)
113131
}
114132

115133
// If discoErr is nil we save the first error. When multiple services
@@ -133,15 +151,15 @@ func GetClient(tfeHost, token string, insecure bool) (*tfe.Client, bool, error)
133151
// First check any constraints we might have received.
134152
if constraints != nil {
135153
if err := CheckConstraints(constraints); err != nil {
136-
return nil, sendCredentialDeprecationWarning, err
154+
return nil, err
137155
}
138156
}
139157
}
140158

141159
// When we don't have any constraints errors, also check for discovery
142160
// errors before we continue.
143161
if discoErr != nil {
144-
return nil, sendCredentialDeprecationWarning, discoErr
162+
return nil, discoErr
145163
}
146164

147165
// Create a new TFE client.
@@ -151,13 +169,13 @@ func GetClient(tfeHost, token string, insecure bool) (*tfe.Client, bool, error)
151169
HTTPClient: config.HTTPClient,
152170
})
153171
if err != nil {
154-
return nil, sendCredentialDeprecationWarning, fmt.Errorf("failed to create client: %w", err)
172+
return nil, fmt.Errorf("failed to create client: %w", err)
155173
}
156174

157175
client.RetryServerErrors(true)
158176
clientCache.Set(client, config)
159177

160-
return client, sendCredentialDeprecationWarning, nil
178+
return &ProviderClient{client, config.TokenSource}, nil
161179
}
162180

163181
// CheckConstraints checks service version constrains against our own

internal/client/config.go

Lines changed: 29 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,22 @@ type ConfigHost struct {
4141
Services map[string]interface{} `hcl:"services"`
4242
}
4343

44-
// ClientConfiguration is the refined information needed to configure a tfe.Client
44+
type TokenSource int
45+
46+
const (
47+
ProviderArgument TokenSource = iota
48+
EnvironmentVariable
49+
CredentialFiles
50+
)
51+
52+
// ClientConfiguration is the refined information needed to configureClient a tfe.Client
4553
type ClientConfiguration struct {
46-
Services *disco.Disco
47-
HTTPClient *http.Client
48-
TFEHost svchost.Hostname
49-
Token string
50-
Insecure bool
54+
Services *disco.Disco
55+
HTTPClient *http.Client
56+
TFEHost svchost.Hostname
57+
Token string
58+
TokenSource TokenSource
59+
Insecure bool
5160
}
5261

5362
// Key returns a string that is comparable to other ClientConfiguration values
@@ -165,17 +174,9 @@ func credentialsSource(credentials CredentialsMap) auth.CredentialsSource {
165174
return creds
166175
}
167176

168-
// Using presence of TFC_AGENT_VERSION to determine if this provider is running on HCP Terraform / enterprise
169-
func providerRunningInCloud() bool {
170-
_, present := os.LookupEnv("TFC_AGENT_VERSION")
171-
return present
172-
}
173-
174177
// configure accepts the provider-level configuration values and creates a
175178
// clientConfiguration using fallback values from the environment or CLI configuration.
176-
func configure(tfeHost, token string, insecure bool) (*ClientConfiguration, bool, error) {
177-
sendCredentialDeprecationWarning := false
178-
179+
func configure(tfeHost, token string, insecure bool) (*ClientConfiguration, error) {
179180
if tfeHost == "" {
180181
if os.Getenv("TFE_HOSTNAME") != "" {
181182
tfeHost = os.Getenv("TFE_HOSTNAME")
@@ -194,7 +195,7 @@ func configure(tfeHost, token string, insecure bool) (*ClientConfiguration, bool
194195
v := os.Getenv("TFE_SSL_SKIP_VERIFY")
195196
insecure, err = strconv.ParseBool(v)
196197
if err != nil {
197-
return nil, sendCredentialDeprecationWarning, fmt.Errorf("TFE_SSL_SKIP_VERIFY has unrecognized value %q", v)
198+
return nil, fmt.Errorf("TFE_SSL_SKIP_VERIFY has unrecognized value %q", v)
198199
}
199200
}
200201

@@ -206,7 +207,7 @@ func configure(tfeHost, token string, insecure bool) (*ClientConfiguration, bool
206207
// Parse the hostname for comparison,
207208
hostname, err := svchost.ForComparison(tfeHost)
208209
if err != nil {
209-
return nil, sendCredentialDeprecationWarning, fmt.Errorf("invalid hostname %q: %w", tfeHost, err)
210+
return nil, fmt.Errorf("invalid hostname %q: %w", tfeHost, err)
210211
}
211212

212213
httpClient := tfe.DefaultConfig().HTTPClient
@@ -241,25 +242,28 @@ func configure(tfeHost, token string, insecure bool) (*ClientConfiguration, bool
241242
// If a token wasn't set in the provider configuration block, try and fetch it
242243
// from the environment or from Terraform's CLI configuration or configured credential helper.
243244

245+
tokenSource := ProviderArgument
244246
if token == "" {
245247
if os.Getenv("TFE_TOKEN") != "" {
246248
token = getTokenFromEnv()
249+
tokenSource = EnvironmentVariable
247250
} else {
248-
sendCredentialDeprecationWarning = providerRunningInCloud()
249251
token = getTokenFromCreds(services, hostname)
252+
tokenSource = CredentialFiles
250253
}
251254
}
252255

253256
// If we still don't have a token at this point, we return an error.
254257
if token == "" {
255-
return nil, sendCredentialDeprecationWarning, ErrMissingAuthToken
258+
return nil, ErrMissingAuthToken
256259
}
257260

258261
return &ClientConfiguration{
259-
Services: services,
260-
HTTPClient: httpClient,
261-
TFEHost: hostname,
262-
Token: token,
263-
Insecure: insecure,
264-
}, sendCredentialDeprecationWarning, nil
262+
Services: services,
263+
HTTPClient: httpClient,
264+
TFEHost: hostname,
265+
Token: token,
266+
TokenSource: tokenSource,
267+
Insecure: insecure,
268+
}, nil
265269
}

internal/provider/provider.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -153,30 +153,31 @@ func configure() schema.ConfigureContextFunc {
153153
providerOrganization = os.Getenv("TFE_ORGANIZATION")
154154
}
155155

156-
tfeClient, sendCredentialDeprecationWarning, err := configureClient(rd)
156+
providerClient, err := configureClient(rd)
157157
if err != nil {
158158
return nil, diag.FromErr(err)
159159
}
160160

161161
var diagnosticWarnings diag.Diagnostics = nil
162-
if sendCredentialDeprecationWarning {
162+
163+
if providerClient.SendAuthenticationWarning() {
163164
diagnosticWarnings = diag.Diagnostics{
164165
diag.Diagnostic{
165166
Severity: diag.Warning,
166-
Summary: "Authentication method invalid for TFE Provider with HCP Terraform and Terraform Enterprise",
167+
Summary: "Authentication with configuration file is invalid for TFE Provider running on HCP Terraform or Terraform Enterprise",
167168
Detail: "Use a TFE_TOKEN variable in the workspace or the token argument for the provider. This authentication method will be deprecated in a future version.",
168169
},
169170
}
170171
}
171172

172173
return ConfiguredClient{
173-
tfeClient,
174+
providerClient.TfeClient,
174175
providerOrganization,
175176
}, diagnosticWarnings
176177
}
177178
}
178179

179-
func configureClient(d *schema.ResourceData) (*tfe.Client, bool, error) {
180+
func configureClient(d *schema.ResourceData) (*client.ProviderClient, error) {
180181
hostname := d.Get("hostname").(string)
181182
token := d.Get("token").(string)
182183
insecure := d.Get("ssl_skip_verify").(bool)

internal/provider/provider_next.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,19 +111,19 @@ func (p *frameworkProvider) Configure(ctx context.Context, req provider.Configur
111111
}
112112
}
113113

114-
tfeClient, sendCredentialDeprecationWarning, err := client.GetClient(data.Hostname.ValueString(), data.Token.ValueString(), data.SSLSkipVerify.ValueBool())
114+
providerClient, err := client.GetClient(data.Hostname.ValueString(), data.Token.ValueString(), data.SSLSkipVerify.ValueBool())
115115

116116
if err != nil {
117117
res.Diagnostics.AddError("Failed to initialize HTTP client", err.Error())
118118
return
119119
}
120120

121-
if sendCredentialDeprecationWarning {
122-
res.Diagnostics.AddWarning("Authentication method invalid for TFE Provider with HCP Terraform and Terraform Enterprise", "Use a TFE_TOKEN variable in the workspace or the token argument for the provider. This authentication method will be deprecated in a future version.")
121+
if providerClient.SendAuthenticationWarning() {
122+
res.Diagnostics.AddWarning("Authentication with configuration files is invalid for TFE Provider running on HCP Terraform or Terraform Enterprise", "Use a TFE_TOKEN variable in the workspace or the token argument for the provider. This authentication method will be deprecated in a future version.")
123123
}
124124

125125
configuredClient := ConfiguredClient{
126-
Client: tfeClient,
126+
Client: providerClient.TfeClient,
127127
Organization: data.Organization.ValueString(),
128128
}
129129

0 commit comments

Comments
 (0)