Provider Configuration Practice

15 minute read

Practice Questions

Test your understanding of provider configuration with these practice questions. Try to answer each question before reviewing the detailed answers.


Question 1: Configuration Precedence

Question: In what order does configuration precedence typically work in Terraform providers?

Click to reveal answer **Answer:** The standard configuration precedence order is: 1. **Explicit configuration** (in provider block) - Highest priority 2. **Environment variables** (e.g., `MYCLOUD_API_KEY`) 3. **Configuration files** (e.g., `~/.mycloud/config.json`) 4. **Default values** - Lowest priority **Example:** ```go func resolveString(attr types.String, envVar string, fileValue string, defaultValue string) string { // 1. Explicit if !attr.IsNull() && attr.ValueString() != "" { return attr.ValueString() } // 2. Environment if val := os.Getenv(envVar); val != "" { return val } // 3. Config file if fileValue != "" { return fileValue } // 4. Default return defaultValue } ``` This allows users to override configuration at each level, with explicit configuration having the highest priority.

Question 2: Provider Configure Method

Question: What are the key responsibilities of a provider’s Configure method?

Click to reveal answer **Answer:** The `Configure` method is responsible for: 1. **Parse configuration** - Get configuration values from request 2. **Resolve values** - Apply configuration precedence (explicit > env > file > default) 3. **Validate configuration** - Check required fields and valid values 4. **Create API client** - Initialize HTTP client with configuration 5. **Test connection** - Verify connectivity and authentication 6. **Share client** - Set `resp.ResourceData` and `resp.DataSourceData` 7. **Handle errors** - Add diagnostics for any failures **Example structure:** ```go func (p *MyProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) { // 1. Parse var config MyProviderModel req.Config.Get(ctx, &config) // 2. Resolve apiKey := resolveString(config.APIKey, "MY_API_KEY", fileConfig.APIKey, "") // 3. Validate if apiKey == "" { resp.Diagnostics.AddError("Missing API Key", ...) return } // 4. Create client client := api.NewClient(apiKey) // 5. Test connection if err := client.TestConnection(ctx); err != nil { resp.Diagnostics.AddError("Connection Failed", ...) return } // 6. Share client resp.ResourceData = client resp.DataSourceData = client } ```

Question 3: Shared Client Pattern

Question: How do resources access the shared client configured by the provider?

Click to reveal answer **Answer:** Resources access the shared client through the `Configure` method: **Step 1:** Resource implements `ResourceWithConfigure` interface: ```go type MyResource struct { client *api.Client // Store client } var _ resource.Resource = &MyResource{} var _ resource.ResourceWithConfigure = &MyResource{} ``` **Step 2:** Implement `Configure` method: ```go func (r *MyResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { // Check for nil (provider not yet configured) if req.ProviderData == nil { return } // Type assert to get client client, ok := req.ProviderData.(*api.Client) if !ok { resp.Diagnostics.AddError( "Unexpected Resource Configure Type", fmt.Sprintf("Expected *api.Client, got: %T", req.ProviderData), ) return } // Store client for use in CRUD operations r.client = client } ``` **Step 3:** Use client in CRUD operations: ```go func (r *MyResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // Use stored client result, err := r.client.CreateResource(ctx, ...) } ```

Question 4: Authentication Methods

Question: What are the common authentication methods for Terraform providers, and how do you validate that only one is used?

Click to reveal answer **Answer:** Common authentication methods include: 1. **API Key** - Single secret key 2. **Username/Password** - Basic authentication 3. **Bearer Token** - OAuth/JWT token 4. **Certificate-based** - mTLS with client certificates 5. **AWS-style** - Access key + secret key with signing **Validation pattern for mutually exclusive methods:** ```go func (p *MyProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) { var config MyProviderModel req.Config.Get(ctx, &config) // Check which methods are provided hasAPIKey := !config.APIKey.IsNull() && config.APIKey.ValueString() != "" hasToken := !config.Token.IsNull() && config.Token.ValueString() != "" hasUserPass := (!config.Username.IsNull() && config.Username.ValueString() != "") && (!config.Password.IsNull() && config.Password.ValueString() != "") // Count methods methodCount := 0 if hasAPIKey { methodCount++ } if hasToken { methodCount++ } if hasUserPass { methodCount++ } // Validate exactly one if methodCount == 0 { resp.Diagnostics.AddError( "Missing Authentication", "One of the following must be provided: api_key, token, or username+password", ) return } if methodCount > 1 { resp.Diagnostics.AddError( "Multiple Authentication Methods", "Only one authentication method can be specified", ) return } } ```

Question 5: Configuration Validation

Question: What’s the difference between schema-level validation and Configure-time validation?

Click to reveal answer **Answer:** **Schema-Level Validation:** - Built into schema definition using validators - Validates individual attribute constraints - Runs before `Configure` method - Good for: value ranges, formats, enums ```go "timeout": schema.NumberAttribute{ Optional: true, Validators: []validator.Number{ numbervalidator.Between(1, 300), }, }, ``` **Configure-Time Validation:** - Custom logic in `Configure` method - Validates complex rules and relationships - Can check external dependencies - Good for: required fields, mutual exclusivity, connectivity ```go func (p *MyProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) { // Complex validation if enableFeature && featureConfig == "" { resp.Diagnostics.AddError( "Missing Configuration", "feature_config required when enable_feature is true", ) return } // Connection test if err := client.TestConnection(ctx); err != nil { resp.Diagnostics.AddError("Connection Failed", ...) } } ``` **Use both:** Schema validation for simple constraints, Configure-time validation for complex rules and connection testing.

Question 6: Configuration Files

Question: How do you load and parse configuration from a JSON file in a provider?

Click to reveal answer **Answer:** **Step 1:** Define configuration structure: ```go type ConfigFile struct { APIKey string `json:"api_key"` Endpoint string `json:"endpoint"` Timeout int `json:"timeout"` } ``` **Step 2:** Load and parse file: ```go func loadConfigFile(path string) (*ConfigFile, error) { // Expand home directory if path == "" { homeDir, _ := os.UserHomeDir() path = filepath.Join(homeDir, ".mycloud", "config.json") } else if strings.HasPrefix(path, "~/") { homeDir, _ := os.UserHomeDir() path = filepath.Join(homeDir, path[2:]) } // Check if exists if _, err := os.Stat(path); os.IsNotExist(err) { return &ConfigFile{}, nil // Return empty config } // Read and parse data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("failed to read config: %w", err) } var config ConfigFile if err := json.Unmarshal(data, &config); err != nil { return nil, fmt.Errorf("failed to parse config: %w", err) } return &config, nil } ``` **Step 3:** Use in Configure: ```go func (p *MyProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) { fileConfig, err := loadConfigFile(config.ConfigFile.ValueString()) if err != nil { resp.Diagnostics.AddWarning("Config File Error", err.Error()) fileConfig = &ConfigFile{} } // Use file values with precedence apiKey := resolveString(config.APIKey, "MY_API_KEY", fileConfig.APIKey, "") } ```

Question 7: Connection Testing

Question: Why should you test the API connection in the provider’s Configure method, and how?

Click to reveal answer **Answer:** **Why test connection:** - ✅ Fail fast during `terraform plan` - ✅ Validate authentication before resource operations - ✅ Provide clear error messages early - ✅ Avoid cryptic errors during resource creation - ✅ Verify network connectivity **How to test:** **In API client:** ```go func (c *Client) TestConnection(ctx context.Context) error { req, err := http.NewRequestWithContext( ctx, "GET", c.baseURL+"/api/v1/health", nil, ) if err != nil { return fmt.Errorf("failed to create request: %w", err) } // Add authentication req.Header.Set("Authorization", "Bearer "+c.token) resp, err := c.httpClient.Do(req) if err != nil { return fmt.Errorf("connection failed: %w", err) } defer resp.Body.Close() if resp.StatusCode == 401 || resp.StatusCode == 403 { return fmt.Errorf("authentication failed (HTTP %d)", resp.StatusCode) } if resp.StatusCode >= 400 { return fmt.Errorf("API error (HTTP %d)", resp.StatusCode) } return nil } ``` **In provider Configure:** ```go tflog.Info(ctx, "Testing API connection") if err := client.TestConnection(ctx); err != nil { resp.Diagnostics.AddError( "Connection Test Failed", fmt.Sprintf( "Could not connect to API at %s.\n"+ "Error: %s\n\n"+ "Please verify:\n"+ " - Credentials are valid\n"+ " - Endpoint is correct\n"+ " - Network connectivity", endpoint, err.Error(), ), ) return } tflog.Info(ctx, "Successfully connected to API") ```

Question 8: Error Messages

Question: What makes a good provider configuration error message?

Click to reveal answer **Answer:** Good error messages are: 1. **Clear** - State exactly what's wrong 2. **Actionable** - Tell user how to fix it 3. **Complete** - Show all possible solutions 4. **Contextual** - Include relevant details 5. **Formatted** - Easy to read with examples **❌ Bad:** ```go resp.Diagnostics.AddError("Error", "Missing authentication") ``` **✅ Good:** ```go resp.Diagnostics.AddError( "Missing API Key", // Clear, specific title "API key must be provided via one of:\n"+ " - api_key attribute in provider block\n"+ " - MYCLOUD_API_KEY environment variable\n"+ " - ~/.mycloud/config.json configuration file\n\n"+ "Example:\n"+ " provider \"mycloud\" {\n"+ " api_key = \"sk-abc123...\"\n"+ " }", // All solutions + example ) ``` **For connection failures:** ```go resp.Diagnostics.AddError( "Connection Test Failed", fmt.Sprintf( "Could not connect to API at %s.\n"+ "Error: %s\n\n"+ "Troubleshooting:\n"+ " 1. Verify API key is valid\n"+ " 2. Check endpoint URL: %s\n"+ " 3. Test network connectivity: curl -v %s\n"+ " 4. Review firewall rules", endpoint, err.Error(), endpoint, endpoint, ), ) ```

Question 9: Sensitive Attributes

Question: How do you handle sensitive configuration like API keys in provider schemas?

Click to reveal answer **Answer:** **Mark as sensitive in schema:** ```go "api_key": schema.StringAttribute{ Optional: true, Sensitive: true, // Mark as sensitive MarkdownDescription: "API key for authentication", }, ``` **What `Sensitive: true` does:** - ✅ Values are masked in plan output (`(sensitive value)`) - ✅ Not shown in logs - ✅ Redacted in state file display - ✅ Protected in CLI output **Best practices:** 1. **Always mark credentials as sensitive:** ```go "api_key": {Sensitive: true} "api_secret": {Sensitive: true} "password": {Sensitive: true} "token": {Sensitive: true} "private_key": {Sensitive: true} ``` 2. **Don't log sensitive values:** ```go tflog.Debug(ctx, "Configuration loaded", map[string]any{ "endpoint": endpoint, // ✅ OK to log // Don't log: "api_key": apiKey // ❌ Never log }) ``` 3. **Use environment variables:** ```go apiKey := config.APIKey.ValueString() if apiKey == "" { apiKey = os.Getenv("MYCLOUD_API_KEY") // Support env var } ``` 4. **Support config files with proper permissions:** ```go // Load from ~/.mycloud/config.json (mode 0600) fileConfig, _ := loadConfigFile(configPath) ```

Question 10: HTTP Client Configuration

Question: What HTTP client settings should a production provider configure?

Click to reveal answer **Answer:** Key HTTP client settings for production: **1. Timeouts:** ```go httpClient := &http.Client{ Timeout: 30 * time.Second, // Overall request timeout } transport := &http.Transport{ DialContext: (&net.Dialer{ Timeout: 5 * time.Second, // Connection timeout KeepAlive: 30 * time.Second, }).DialContext, TLSHandshakeTimeout: 10 * time.Second, ResponseHeaderTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, } ``` **2. Connection Pooling:** ```go transport := &http.Transport{ MaxIdleConns: 100, // Total idle connections MaxIdleConnsPerHost: 10, // Per host MaxConnsPerHost: 100, // Max connections per host IdleConnTimeout: 90 * time.Second, // Keep alive } ``` **3. TLS Configuration:** ```go transport := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: false, // Verify certificates MinVersion: tls.VersionTLS12, MaxVersion: tls.VersionTLS13, }, } ``` **4. Retry Logic:** ```go type RetryTransport struct { Transport http.RoundTripper MaxRetries int } func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error) { for attempt := 0; attempt <= t.MaxRetries; attempt++ { resp, err := t.Transport.RoundTrip(req) // Success if err == nil && resp.StatusCode < 500 { return resp, nil } // Wait with exponential backoff if attempt < t.MaxRetries { time.Sleep(time.Duration(attempt+1) * time.Second) } } return resp, err } ``` **5. Custom Headers:** ```go type HeaderTransport struct { Transport http.RoundTripper Headers map[string]string } func (t *HeaderTransport) RoundTrip(req *http.Request) (*http.Response, error) { for key, value := range t.Headers { req.Header.Set(key, value) } return t.Transport.RoundTrip(req) } ``` **Complete example:** ```go client, err := api.NewClient(api.Config{ APIKey: apiKey, BaseURL: endpoint, Timeout: 30 * time.Second, MaxRetries: 3, MaxIdleConns: 100, InsecureSkipVerify: false, UserAgent: fmt.Sprintf("terraform-provider-mycloud/%s", version), }) ```

Scenario-Based Questions

Scenario 1: Multiple Authentication Methods

Question: Your provider supports three authentication methods: API key, username/password, and OAuth token. Users report errors when they provide multiple methods. How do you fix this?

Click to reveal answer **Answer:** Implement mutually exclusive validation: ```go func (p *MyProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) { var config MyProviderModel req.Config.Get(ctx, &config) // Detect which methods are provided hasAPIKey := !config.APIKey.IsNull() && config.APIKey.ValueString() != "" hasUserPass := (!config.Username.IsNull() && config.Username.ValueString() != "") && (!config.Password.IsNull() && config.Password.ValueString() != "") hasToken := !config.Token.IsNull() && config.Token.ValueString() != "" // Count methods authMethods := []string{} if hasAPIKey { authMethods = append(authMethods, "api_key") } if hasUserPass { authMethods = append(authMethods, "username/password") } if hasToken { authMethods = append(authMethods, "token") } // Validate exactly one if len(authMethods) == 0 { resp.Diagnostics.AddError( "Missing Authentication", "One of the following authentication methods must be provided:\n"+ " - api_key\n"+ " - username and password\n"+ " - token", ) return } if len(authMethods) > 1 { resp.Diagnostics.AddError( "Multiple Authentication Methods", fmt.Sprintf( "Only one authentication method can be specified at a time.\n"+ "Found: %s\n\n"+ "Please provide only one authentication method.", strings.Join(authMethods, ", "), ), ) return } // Create appropriate client based on method var client *api.Client var err error if hasAPIKey { client, err = api.NewClientWithAPIKey(config.APIKey.ValueString()) } else if hasUserPass { client, err = api.NewClientWithUserPass( config.Username.ValueString(), config.Password.ValueString(), ) } else if hasToken { client, err = api.NewClientWithToken(config.Token.ValueString()) } if err != nil { resp.Diagnostics.AddError("Client Creation Failed", err.Error()) return } resp.ResourceData = client resp.DataSourceData = client } ```

Scenario 2: Configuration File Not Loading

Question: Users report that configuration from ~/.mycloud/config.json isn’t being loaded. What could be wrong and how do you debug it?

Click to reveal answer **Answer:** Common issues and solutions: **1. File path expansion:** ```go func loadConfigFile(path string) (*ConfigFile, error) { // Expand ~ to home directory if strings.HasPrefix(path, "~/") { homeDir, err := os.UserHomeDir() if err != nil { return nil, fmt.Errorf("failed to get home directory: %w", err) } path = filepath.Join(homeDir, path[2:]) } tflog.Debug(ctx, "Loading config file", map[string]any{ "path": path, // Log resolved path }) // Check if file exists if _, err := os.Stat(path); os.IsNotExist(err) { tflog.Warn(ctx, "Config file not found", map[string]any{ "path": path, }) return &ConfigFile{}, nil // Return empty config } // Read file data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("failed to read config file %s: %w", path, err) } // Parse JSON var config ConfigFile if err := json.Unmarshal(data, &config); err != nil { return nil, fmt.Errorf("failed to parse JSON in %s: %w", path, err) } tflog.Info(ctx, "Config file loaded successfully", map[string]any{ "path": path, }) return &config, nil } ``` **2. Configuration precedence:** ```go // Ensure config file is checked in correct order apiKey := config.APIKey.ValueString() // 1. Explicit if apiKey == "" { apiKey = os.Getenv("MYCLOUD_API_KEY") // 2. Environment } if apiKey == "" { apiKey = fileConfig.APIKey // 3. Config file } if apiKey == "" { apiKey = "default-value" // 4. Default } ``` **3. Error handling:** ```go fileConfig, err := loadConfigFile(config.ConfigFile.ValueString()) if err != nil { // Don't fail completely, warn and continue resp.Diagnostics.AddWarning( "Failed to Load Config File", fmt.Sprintf("Could not load configuration file: %s\nContinuing with other sources.", err.Error()), ) fileConfig = &ConfigFile{} // Use empty config } ``` **4. Enable debug logging:** ```bash export TF_LOG=DEBUG terraform plan ``` Look for log messages like: ``` [DEBUG] Loading config file: path=/Users/username/.mycloud/config.json [INFO] Config file loaded successfully ```

Scenario 3: Connection Timeouts

Question: Users report that terraform plan hangs for a long time before failing. The API is slow to respond. How do you fix this?

Click to reveal answer **Answer:** Implement proper timeouts at multiple levels: **1. Add timeout configuration:** ```go "timeout": schema.NumberAttribute{ Optional: true, MarkdownDescription: "Request timeout in seconds. Defaults to 30.", Validators: []validator.Number{ numbervalidator.Between(1, 300), }, }, ``` **2. Configure HTTP client timeouts:** ```go func (p *MyProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) { timeout := 30 if !config.Timeout.IsNull() { val, _ := config.Timeout.ValueBigFloat().Int64() timeout = int(val) } // Create client with timeout client, err := api.NewClient(api.Config{ Timeout: time.Duration(timeout) * time.Second, }) } ``` **3. Implement multi-level timeouts in client:** ```go func NewClient(config Config) (*Client, error) { transport := &http.Transport{ DialContext: (&net.Dialer{ Timeout: 5 * time.Second, // Connection timeout KeepAlive: 30 * time.Second, }).DialContext, TLSHandshakeTimeout: 10 * time.Second, // TLS timeout ResponseHeaderTimeout: 10 * time.Second, // Header timeout } httpClient := &http.Client{ Timeout: config.Timeout, // Overall request timeout Transport: transport, } return &Client{ httpClient: httpClient, }, nil } ``` **4. Add timeout to connection test:** ```go func (p *MyProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) { // Create context with timeout for connection test testCtx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() tflog.Info(ctx, "Testing API connection with 10s timeout") if err := client.TestConnection(testCtx); err != nil { resp.Diagnostics.AddError( "Connection Test Failed", fmt.Sprintf( "Could not connect to API within 10 seconds.\n"+ "Error: %s\n\n"+ "Try increasing the timeout:\n"+ " provider \"mycloud\" {\n"+ " timeout = 60\n"+ " }", err.Error(), ), ) return } } ``` **5. Document timeout settings:** ```markdown ## Configuration - `timeout` - (Optional) Request timeout in seconds. Defaults to 30. Range: 1-300. Example: ```hcl provider "mycloud" { timeout = 60 # Increase for slow networks } ``` ```

Scenario 4: Debugging Configuration Issues

Question: A user reports that their provider configuration isn’t working, but they won’t share their actual API key. How do you help them debug?

Click to reveal answer **Answer:** Add comprehensive logging and diagnostic output: **1. Log configuration resolution (without sensitive values):** ```go func (p *MyProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) { // Log which sources are being used apiKeySource := "not set" if !config.APIKey.IsNull() && config.APIKey.ValueString() != "" { apiKeySource = "explicit" } else if os.Getenv("MYCLOUD_API_KEY") != "" { apiKeySource = "environment" } else if fileConfig.APIKey != "" { apiKeySource = "config file" } tflog.Info(ctx, "Configuration resolved", map[string]any{ "api_key_source": apiKeySource, "endpoint": endpoint, "timeout": timeout, }) // Log validation results if apiKey == "" { tflog.Error(ctx, "API key validation failed", map[string]any{ "checked_explicit": !config.APIKey.IsNull(), "checked_env": os.Getenv("MYCLOUD_API_KEY") != "", "checked_file": fileConfig.APIKey != "", }) } } ``` **2. Add diagnostic output:** ```go // If debug mode, show configuration summary if os.Getenv("TF_LOG") == "DEBUG" { resp.Diagnostics.AddWarning( "Configuration Summary", fmt.Sprintf( "Provider configured with:\n"+ " API Key Source: %s\n"+ " Endpoint: %s\n"+ " Timeout: %ds\n"+ " Max Retries: %d", apiKeySource, endpoint, timeout, maxRetries, ), ) } ``` **3. Provide troubleshooting guide:** ```go resp.Diagnostics.AddError( "Missing API Key", "API key must be provided. Follow these steps to troubleshoot:\n\n"+ "1. Check explicit configuration:\n"+ " provider \"mycloud\" { api_key = \"...\" }\n\n"+ "2. Check environment variable:\n"+ " echo $MYCLOUD_API_KEY\n\n"+ "3. Check config file:\n"+ " cat ~/.mycloud/config.json\n\n"+ "4. Enable debug logging:\n"+ " export TF_LOG=DEBUG\n"+ " terraform plan\n\n"+ "5. Test API connectivity manually:\n"+ " curl -H 'X-API-Key: YOUR_KEY' https://api.mycloud.com/health", ) ``` **4. Create validation script:** ```bash #!/bin/bash # debug-provider.sh echo "=== Provider Configuration Debug ===" echo "" echo "1. Environment Variables:" env | grep MYCLOUD_ || echo " None found" echo "" echo "2. Config File:" if [ -f ~/.mycloud/config.json ]; then echo " File exists: ~/.mycloud/config.json" echo " Size: $(stat -f%z ~/.mycloud/config.json) bytes" echo " Permissions: $(stat -f%A ~/.mycloud/config.json)" else echo " File not found: ~/.mycloud/config.json" fi echo "" echo "3. Connectivity Test:" curl -v https://api.mycloud.com/health 2>&1 | head -20 echo "" echo "4. Run Terraform with debug:" echo " export TF_LOG=DEBUG" echo " terraform plan 2>&1 | grep -i 'configuration\|api.key\|connect'" ```

Key Takeaways

  • ✅ Provider configuration involves schema, Configure method, validation, and client sharing
  • ✅ Configuration precedence: explicit > environment > file > default
  • ✅ Always implement ResourceWithConfigure interface in resources
  • ✅ Test API connectivity during provider configuration
  • ✅ Validate mutually exclusive authentication methods
  • ✅ Provide clear, actionable error messages with examples
  • ✅ Mark sensitive attributes with Sensitive: true
  • ✅ Configure HTTP client with timeouts, retries, and connection pooling
  • ✅ Support multiple configuration sources for flexibility
  • ✅ Log configuration steps for debugging (without sensitive values)

Next Steps

Congratulations! You’ve completed Module 5: Provider Configuration.

Next module: Learn how to implement resources with full CRUD operations.

Next Module: Resource Implementation →


Previous: ← Provider Configuration Lab

Last updated: June 30, 2026

Updated:

Leave a comment