Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for credential files #672

Merged
merged 4 commits into from
Nov 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changelog/672.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:feature
Add support to authenticate the provider using credential files.
```
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ resource "hcp_vault_cluster" "example" {

- `client_id` (String) The OAuth2 Client ID for API operations.
- `client_secret` (String) The OAuth2 Client Secret for API operations.
- `credential_file` (String) The path to an HCP credential file to use to authenticate the provider to HCP. You can alternatively set the HCP_CRED_FILE environment variable to point at a credential file as well. Using a credential file allows you to authenticate the provider as a service principal via client credentials or dynamically based on Workload Identity Federation.
- `project_id` (String) The default project in which resources should be created.
-> **Note:** See the [authentication guide](guides/auth.md) about a use case when specifying `project_id` is needed.

Expand Down
28 changes: 16 additions & 12 deletions internal/clients/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,9 @@ type Client struct {

// ClientConfig specifies configuration for the client that interacts with HCP
type ClientConfig struct {
ClientID string
ClientSecret string
ClientID string
ClientSecret string
CredentialFile string

// OrganizationID (optional) is the organization unique identifier to launch resources in.
OrganizationID string
Expand All @@ -83,13 +84,18 @@ type ClientConfig struct {

// NewClient creates a new Client that is capable of making HCP requests
func NewClient(config ClientConfig) (*Client, error) {
hcp, err := hcpConfig.NewHCPConfig(
hcpConfig.FromEnv(),
hcpConfig.WithClientCredentials(
config.ClientID,
config.ClientSecret,
),
)
// Build the HCP Config options
var opts []hcpConfig.HCPConfigOption
if config.ClientID != "" && config.ClientSecret != "" {
opts = append(opts, hcpConfig.WithClientCredentials(config.ClientID, config.ClientSecret))
} else if config.CredentialFile != "" {
opts = append(opts, hcpConfig.WithCredentialFilePath(config.CredentialFile))
} else {
opts = append(opts, hcpConfig.FromEnv())
}

// Create the HCP Config
hcp, err := hcpConfig.NewHCPConfig(opts...)
if err != nil {
return nil, fmt.Errorf("invalid HCP config: %w", err)
}
Expand All @@ -108,14 +114,12 @@ func NewClient(config ClientConfig) (*Client, error) {
}

httpClient.SetLogger(logger{})

if ShouldLog() {
httpClient.Debug = true
}

client := &Client{
Config: config,

Config: config,
Billing: cloud_billing.New(httpClient, nil).BillingAccountService,
Boundary: cloud_boundary.New(httpClient, nil).BoundaryService,
Consul: cloud_consul.New(httpClient, nil).ConsulService,
Expand Down
31 changes: 25 additions & 6 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@ import (
"os"

"github.com/hashicorp/hcp-sdk-go/clients/cloud-resource-manager/stable/2019-12-10/client/project_service"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/provider"
"github.com/hashicorp/terraform-plugin-framework/provider/schema"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-provider-hcp/internal/clients"

Expand All @@ -34,9 +37,10 @@ type ProviderFrameworkConfiguration struct {
}

type ProviderFrameworkModel struct {
ClientSecret types.String `tfsdk:"client_secret"`
ClientID types.String `tfsdk:"client_id"`
ProjectID types.String `tfsdk:"project_id"`
ClientSecret types.String `tfsdk:"client_secret"`
ClientID types.String `tfsdk:"client_id"`
CredentialFile types.String `tfsdk:"credential_file"`
ProjectID types.String `tfsdk:"project_id"`
}

func (p *ProviderFramework) Metadata(ctx context.Context, req provider.MetadataRequest, resp *provider.MetadataResponse) {
Expand All @@ -50,15 +54,29 @@ func (p *ProviderFramework) Schema(ctx context.Context, req provider.SchemaReque
"client_id": schema.StringAttribute{
Optional: true,
Description: "The OAuth2 Client ID for API operations.",
Validators: []validator.String{
stringvalidator.AlsoRequires(path.MatchRoot("client_secret")),
stringvalidator.ConflictsWith(path.MatchRoot("credential_file")),
},
},
"client_secret": schema.StringAttribute{
Optional: true,
Description: "The OAuth2 Client Secret for API operations.",
Validators: []validator.String{
stringvalidator.AlsoRequires(path.MatchRoot("client_id")),
},
},
"project_id": schema.StringAttribute{
Optional: true,
Description: "The default project in which resources should be created.",
},
"credential_file": schema.StringAttribute{
Optional: true,
Description: "The path to an HCP credential file to use to authenticate the provider to HCP. " +
"You can alternatively set the HCP_CRED_FILE environment variable to point at a credential file as well. " +
"Using a credential file allows you to authenticate the provider as a service principal via client " +
"credentials or dynamically based on Workload Identity Federation.",
},
},
}
}
Expand Down Expand Up @@ -132,9 +150,10 @@ func (p *ProviderFramework) Configure(ctx context.Context, req provider.Configur
}

client, err := clients.NewClient(clients.ClientConfig{
ClientID: clientID,
ClientSecret: clientSecret,
SourceChannel: "terraform-provider-hcp",
ClientID: clientID,
ClientSecret: clientSecret,
CredentialFile: data.CredentialFile.ValueString(),
SourceChannel: "terraform-provider-hcp",
})

if err != nil {
Expand Down
15 changes: 12 additions & 3 deletions internal/providersdkv2/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,14 @@ func New() func() *schema.Provider {
ValidateFunc: validation.IsUUID,
Description: "The default project in which resources should be created.",
},
"credential_file": {
Type: schema.TypeString,
Optional: true,
Description: "The path to an HCP credential file to use to authenticate the provider to HCP. " +
"You can alternatively set the HCP_CRED_FILE environment variable to point at a credential file as well. " +
"Using a credential file allows you to authenticate the provider as a service principal via client " +
"credentials or dynamically based on Workload Identity Federation.",
},
},
ProviderMetaSchema: map[string]*schema.Schema{
"module_name": {
Expand Down Expand Up @@ -116,9 +124,10 @@ func configure(p *schema.Provider) func(context.Context, *schema.ResourceData) (
}

client, err := clients.NewClient(clients.ClientConfig{
ClientID: clientID,
ClientSecret: clientSecret,
SourceChannel: userAgent,
ClientID: clientID,
ClientSecret: clientSecret,
CredentialFile: d.Get("credential_file").(string),
SourceChannel: userAgent,
})
if err != nil {
diags = append(diags, diag.Errorf("unable to create HCP api client: %v", err)...)
Expand Down