Skip to content

feat: support credential tokens for getter #4047

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

dlundgren
Copy link

@dlundgren dlundgren commented Mar 19, 2025

Description

Fixes #1771 by using the cliconfig to get the credentials. I've tested with ~/.terraformrc and the credentials worked as expected for a private Gitlab instance.

TODOs

Read the Gruntwork contribution guidelines.

  • Update the docs.
  • Run the relevant tests successfully, including pre-commit checks.
  • Ensure any 3rd party code adheres with our license policy or delete this line if its not applicable.
  • Include release notes. If this PR is backward incompatible, include a migration guide.

Release Notes (draft)

Updated source downloads to honor .terraformrc credentials

Summary by CodeRabbit

  • New Features

    • Enhanced authentication for HTTP requests by automatically using user credentials or fallback environment settings for authorization headers.
    • Introduced configuration files for private Terraform registries, enabling integration of external Terraform modules.
    • Added a new function to streamline the authentication process for requests.
  • Tests

    • Added new tests for validating interactions with private Terraform registries using both configuration file and environment variable tokens.

Copy link

vercel bot commented Mar 19, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
terragrunt-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 2, 2025 2:52pm

Copy link
Contributor

coderabbitai bot commented Mar 19, 2025

📝 Walkthrough

Walkthrough

This pull request introduces a new function, applyHostToken, in the tf package to centralize and streamline the authentication process for HTTP requests. The function loads the user configuration using cliconfig.LoadUserConfig() and retrieves host-specific credentials if available; otherwise, it falls back to the TG_TF_REGISTRY_TOKEN environment variable. The httpGETAndGetResponse function has been updated to utilize this new authentication helper, with error handling integrated to propagate any issues encountered during the process. Additionally, new test files and configuration files for private registries have been added.

Changes

Files Change summary
tf/getter.go Added new function applyHostToken to load credentials and manage authentication. Modified httpGETAndGetResponse to use applyHostToken and handle errors.
test/fixtures/private-registry/env.tfrc Created new file env.tfrc containing a credentials block with placeholders for registry host and token.
test/fixtures/private-registry/terragrunt.hcl Created new file terragrunt.hcl with a terraform block specifying a module source URL.
test/integration_private_registry_test.go Introduced new test file with functions for testing private Terraform registries using both configuration file and environment variable tokens.

Assessment against linked issues

Objective Addressed Explanation
Add support for token configuration that Terraform supports (#1771)

Suggested reviewers

  • levkohimins
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@yhakbar
Copy link
Collaborator

yhakbar commented Mar 19, 2025

Thanks for submitting this, @dlundgren .

Would you mind adding an integration test that confirms this, but is ignored unless a build flag is provided?
Something like this.

That would confirm that we can do automated testing to determine regression if we hook it up to a private GitLab instance, or that someone contributing features related to a private GitLab instance can test for regression locally.

@dlundgren
Copy link
Author

Thanks for the pointer on the test! I was trying to figure out how to add one, but got tripped up on the private registry part of it.

@yhakbar yhakbar marked this pull request as draft March 21, 2025 14:11
@yhakbar
Copy link
Collaborator

yhakbar commented Mar 21, 2025

@dlundgren , we're happy to work with you on resolving this. It seems like a good implementation of the feature request. I've moved the PR in-draft until you get a chance to add those tests. Please mark it as ready for review once we can take a look.

@dlundgren
Copy link
Author

dlundgren commented Apr 2, 2025

I've added the private_registry tag to the tests.

I cloned yorinasub17 terraform-null-terragrunt-registry-test to my gitlab-ce instance, and published the module. I noticed the same repo also lives in gruntwork-io right after I committed this.

The hashicorp/null resource failed to install for me, so I utilized the errors considering the fact this is about downloading the module using credentials versus actually running the terraform code itself.

It also will require two env variables:

  • PRIVATE_REGISTRY_TOKEN
  • PRIVATE_REGISTRY_URL

@dlundgren dlundgren marked this pull request as ready for review April 2, 2025 05:34
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (6)
test/integration_private_registry_test.go (6)

48-48: Remove unnecessary t.Helper() call

The t.Helper() function should only be used in helper functions that are called by test functions, not in the test functions themselves. It helps with reporting the correct file and line number when a test fails.

func TestPrivateRegistryWithConfgFileToken(t *testing.T) {
-	t.Helper()

52-52: Remove or replace debug output to stdout

Writing directly to stdout in tests can interfere with the test runner's output. If you need to debug, consider using t.Logf() instead.

-	os.Stdout.Write([]byte(host))
+	t.Logf("Using registry host: %s", host)

68-68: Remove unnecessary t.Helper() call

Same issue as in the previous test function - t.Helper() is meant for helper functions, not test functions.

func TestPrivateRegistryWithEnvToken(t *testing.T) {
-	t.Helper()

72-73: Improve host name transformation for environment variables

The current transformation replaces dots and hyphens, but Terraform's environment variable naming convention might require additional transformations for other special characters. Consider using a more comprehensive approach.

-	host = strings.ReplaceAll(strings.ReplaceAll(host, ".", "_"), "-", "__")
+	// Convert host to format suitable for Terraform env vars (replace all non-alphanumeric with underscore)
+	host = strings.ToUpper(host)
+	var result strings.Builder
+	for _, c := range host {
+		if (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') {
+			result.WriteRune(c)
+		} else {
+			result.WriteRune('_')
+		}
+	}
+	host = result.String()
	t.Setenv(fmt.Sprintf("TF_TOKEN_%s", host), token)

61-64: Add a comment explaining the test's success criteria

The test expects a specific error about "hashicorp/null", which is an unusual pattern. A comment explaining why this indicates success would improve maintainability.

	_, _, err := helpers.RunTerragruntCommandWithOutput(t, "terragrunt init --non-interactive --log-level=trace --working-dir="+rootPath)

-	// the hashicorp/null provider errors on install, but that indicates that the private tfr module was downloaded
+	// The test is considered successful if we get an error specifically about the hashicorp/null provider.
+	// This indicates that authentication worked correctly and we were able to download the private module,
+	// but then failed at a later step when trying to install the null provider.
	require.Contains(t, err.Error(), "hashicorp/null", "Error accessing the private registry")

21-45: Add better documentation and consider refactoring the setup function

The setup function is quite complex and would benefit from more documentation. It also performs multiple responsibilities: environment checking, test setup, URL validation, and file manipulation.

Consider splitting it into smaller, more focused functions:

  1. A function to check and validate environment variables
  2. A function to set up the test environment
  3. A function to customize the test files

This would improve maintainability and testability of the code.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 241ea22 and 8060374.

📒 Files selected for processing (3)
  • test/fixtures/private-registry/env.tfrc (1 hunks)
  • test/fixtures/private-registry/terragrunt.hcl (1 hunks)
  • test/integration_private_registry_test.go (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • test/fixtures/private-registry/env.tfrc
  • test/fixtures/private-registry/terragrunt.hcl
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

**/*.go: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

  • test/integration_private_registry_test.go

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
test/integration_private_registry_test.go (2)

42-44: Consider combining URL validation checks.

This hostname check is separate from the URL parsing error check above. While this works as defensive programming, you could simplify by combining these checks.

	URL, err := url.Parse("tfr://" + registryUrl)
-	if err != nil {
-		t.Fatalf("REGISTRY_URL is invalid: %f", err)
-	}
-
-	if URL.Hostname() == "" {
-		t.Fatal("REGISTRY_URL is invalid")
-	}
+	if err != nil || URL.Hostname() == "" {
+		t.Fatalf("REGISTRY_URL is invalid: %v", err)
+	}

65-66: Consider enhancing test assertion messages.

While the test logic is correct, the error message could be more descriptive about why seeing "hashicorp/null" in the error output indicates success.

-	require.Contains(t, err.Error(), "hashicorp/null", "Error accessing the private registry")
+	require.Contains(t, err.Error(), "hashicorp/null", "Expected error about hashicorp/null provider, which indicates successful private module download")

Also applies to: 80-82

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8060374 and 7b3d828.

📒 Files selected for processing (1)
  • test/integration_private_registry_test.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

**/*.go: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

  • test/integration_private_registry_test.go
🔇 Additional comments (4)
test/integration_private_registry_test.go (4)

53-67: LGTM: Test configuration file token implementation.

The test correctly verifies that Terragrunt can authenticate with a private registry using credentials from a configuration file.


69-83: LGTM: Test environment variable token implementation.

The test properly validates the environment variable-based authentication method, including the host name transformation logic that matches the implementation.


1-20: LGTM: File structure and build constraints.

The build constraint properly isolates these tests to run only when the private_registry tag is specified, and the imports and constants are well-organized.


21-51: LGTM: Test setup function implementation.

The setup function correctly initializes the test environment, validates required environment variables, and prepares the test directory structure. The conditional check for skipping tests now correctly uses the OR operator as previously suggested.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
test/integration_private_registry_test.go (3)

37-44: Improve URL validation logic and error messages

The URL validation logic is currently split into two separate checks - one for parsing errors and one for empty hostname. Consider consolidating these checks for better readability and providing more descriptive error messages.

 URL, err := url.Parse("tfr://" + registryUrl)
-	if err != nil {
-		t.Fatalf("REGISTRY_URL is invalid: %v", err)
-	}
-
-	if URL.Hostname() == "" {
-		t.Fatal("REGISTRY_URL is invalid")
+	if err != nil || URL.Hostname() == "" {
+		t.Fatalf("REGISTRY_URL is invalid: %v. Expected a valid hostname.", err)
 	}

63-67: Extract duplicate test assertion logic to a helper function

Both test functions contain nearly identical code for running the Terragrunt command and checking the error message. Consider extracting this to a helper function to reduce duplication.

+func runTerragruntInitAndVerify(t *testing.T, rootPath string) {
+	t.Helper()
+	_, _, err := helpers.RunTerragruntCommandWithOutput(t, "terragrunt init --non-interactive --log-level=trace --working-dir="+rootPath)
+
+	// the hashicorp/null provider errors on install, but that indicates that the private tfr module was downloaded
+	require.Contains(t, err.Error(), "hashicorp/null", "Error accessing the private registry")
+}

 func TestPrivateRegistryWithConfgFileToken(t *testing.T) {
 	// ... existing setup code ...
 	t.Setenv("TF_CLI_CONFIG_FILE", util.JoinPath(rootPath, "env.tfrc"))
-
-	_, _, err := helpers.RunTerragruntCommandWithOutput(t, "terragrunt init --non-interactive --log-level=trace --working-dir="+rootPath)
-
-	// the hashicorp/null provider errors on install, but that indicates that the private tfr module was downloaded
-	require.Contains(t, err.Error(), "hashicorp/null", "Error accessing the private registry")
+	runTerragruntInitAndVerify(t, rootPath)
 }

 func TestPrivateRegistryWithEnvToken(t *testing.T) {
 	// ... existing setup code ...
 	t.Setenv(fmt.Sprintf("TF_TOKEN_%s", host), token)
-
-	_, _, err := helpers.RunTerragruntCommandWithOutput(t, "terragrunt init --non-interactive --log-level=trace --working-dir="+rootPath)
-
-	// The main test is for authentication against the private registry, so if the null provider fails then we know
-	// that terragrunt authenticated and downloaded the module.
-	require.Contains(t, err.Error(), "hashicorp/null", "Error accessing the private registry")
+	runTerragruntInitAndVerify(t, rootPath)
 }

Also applies to: 78-83


26-27: Enhance documentation about the recommended repository clone

The comment mentions a recommended repository clone but doesn't explain why this particular repository is recommended or what its purpose is. Consider adding more detail to help other developers understand the test requirements better.

-	// the private registry test is recommended to be a clone of gruntwork-io/terraform-null-terragrunt-registry-test
+	// The private registry test expects a Terraform registry module similar to 
+	// gruntwork-io/terraform-null-terragrunt-registry-test, which is a minimal
+	// module that references the hashicorp/null provider. This allows us to test
+	// authentication without needing the module to actually work completely.
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7b3d828 and 5f23745.

📒 Files selected for processing (1)
  • test/integration_private_registry_test.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

**/*.go: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

  • test/integration_private_registry_test.go
🔇 Additional comments (1)
test/integration_private_registry_test.go (1)

1-84: LGTM! The integration test implementation looks solid.

The test structure and implementation effectively validate both authentication methods for private Terraform registries:

  1. Using credentials from a config file via TF_CLI_CONFIG_FILE
  2. Using credentials from environment variables

The test appropriately handles environment setup, validation, and assertions. The skipping logic for when credentials aren't available is also correctly implemented.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Terraform Registry Support: Add support for token configuration that terraform supports.
2 participants