feat(auth): add GKE kubeconfig integration - #2901
feat(auth): add GKE kubeconfig integration#2901Mikhail Shirkov (shirkevich) wants to merge 1 commit into
Conversation
|
Tip Atmos Pro
No affected stacks workflow was detected for this pull request. |
|
CodeRabbit (@coderabbitai) review |
✅ Action performedReview finished.
|
📝 WalkthroughWalkthroughThe pull request adds native GCP GKE authentication. It supports GKE cluster discovery, kubeconfig provisioning, dynamic Kubernetes tokens, CLI commands, configuration schema fields, integration caching, tests, and documentation. ChangesGCP GKE authentication
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant KubernetesExec
participant GKETokenCommand
participant AuthManager
participant GCPTokenProvider
KubernetesExec->>GKETokenCommand: Request ExecCredential
GKETokenCommand->>AuthManager: Authenticate selected identity
AuthManager->>GCPTokenProvider: Refresh or return GCP credentials
GCPTokenProvider-->>GKETokenCommand: Access token and expiry
GKETokenCommand-->>KubernetesExec: ExecCredential JSON
Suggested labels: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
🧪 Generate unit tests (beta)
Warning Tools execution failed with the following error: Failed to run tools: 14 UNAVAILABLE: read ECONNRESET Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
pkg/auth/integrations/gcp/gke.go (1)
168-175: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd performance tracking to
Environment.
Environmentis public and can return manager-construction errors. Adddefer perf.Track(nil, "gcp.GKEIntegration.Environment")()and a blank line.As per coding guidelines, “Add
defer perf.Track(atmosConfig, "pkg.FuncName")()plus a blank line to public functions.”🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/auth/integrations/gcp/gke.go` around lines 168 - 175, Add performance tracking at the start of the public GKEIntegration.Environment method by deferring perf.Track(nil, "gcp.GKEIntegration.Environment")(), followed by a blank line before the existing logic.Source: Coding guidelines
cmd/gcp/gcp.go (1)
12-17: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd the required embedded command usage.
gcpCmdhas static help text only. Embed its usage document fromcmd/markdown/*_usage.mdand render it withutils.PrintfMarkdown(). Include command examples in that document.As per coding guidelines, “Embed command usage examples from
cmd/markdown/*_usage.mdwith//go:embedand render them withutils.PrintfMarkdown().”🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@cmd/gcp/gcp.go` around lines 12 - 17, Update gcpCmd to embed its command usage markdown from cmd/markdown via //go:embed, and render the embedded document with utils.PrintfMarkdown() instead of relying only on static Long text. Add the relevant GCP command examples to the embedded usage document while preserving the existing cobra command configuration.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@cmd/gcp/gke/token.go`:
- Around line 53-62: The authentication context in executeTokenCommand must
preserve Cobra’s cancellation and deadline while retaining skip-integrations
behavior. Replace the context.Background() input to
auth.ContextWithSkipIntegrations with cmd.Context(), and add coverage verifying
cancellation/deadline inheritance reaches authenticateForTokenFn.
In `@pkg/auth/manager_integrations.go`:
- Around line 49-53: Update the GKE key generation in the KindGCPGKE handling to
include every kubeconfig output-affecting setting consumed by Execute, including
configured path, context alias, update behavior, and exec-plugin identity, so
integrations sharing a cluster but differing in any of these values produce
distinct keys; alternatively disable GKE target deduplication. Add coverage for
integrations sharing a cluster with different paths, aliases, or identities.
In `@pkg/datafetcher/schema_auth_validation_test.go`:
- Around line 241-243: Update the kubeconfig fixture in the relevant test to set
its path with filepath.Join(t.TempDir(), "example-kubeconfig") instead of the
hardcoded Unix path, and add the path/filepath import. Preserve the existing
fixture structure and values.
In `@website/docs/cli/commands/gcp/gke/gke.mdx`:
- Around line 8-12: Complete the CLI documentation template in
website/docs/cli/commands/gcp/gke/gke.mdx lines 8-12 by adding a static
CastPlayer, Usage, and Examples sections documenting only supported flags; in
website/docs/cli/commands/gcp/gke/token.mdx lines 7-11 and
website/docs/cli/commands/gcp/usage.mdx lines 7-12, add static CastPlayer and
Examples sections documenting only supported flags. Ensure all three pages
retain the required frontmatter, Intro, and <dl> argument/flag definitions,
using CastPlayer with static rather than Screengrab.
---
Nitpick comments:
In `@cmd/gcp/gcp.go`:
- Around line 12-17: Update gcpCmd to embed its command usage markdown from
cmd/markdown via //go:embed, and render the embedded document with
utils.PrintfMarkdown() instead of relying only on static Long text. Add the
relevant GCP command examples to the embedded usage document while preserving
the existing cobra command configuration.
In `@pkg/auth/integrations/gcp/gke.go`:
- Around line 168-175: Add performance tracking at the start of the public
GKEIntegration.Environment method by deferring perf.Track(nil,
"gcp.GKEIntegration.Environment")(), followed by a blank line before the
existing logic.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 84a66aac-c6bd-4206-a824-55c0b4403475
📒 Files selected for processing (32)
cmd/gcp/gcp.gocmd/gcp/gcp_test.gocmd/gcp/gke/gke.gocmd/gcp/gke/token.gocmd/gcp/gke/token_test.gocmd/root.godocs/prd/gke-kubeconfig-authentication.mderrors/errors.gopkg/auth/cloud/gcp/gke.gopkg/auth/cloud/gcp/gke_test.gopkg/auth/cloud/kube/config.gopkg/auth/integrations/gcp/gke.gopkg/auth/integrations/gcp/gke_test.gopkg/auth/integrations/types.gopkg/auth/manager.gopkg/auth/manager_gke_integration_test.gopkg/auth/manager_integrations.gopkg/auth/manager_integrations_test.gopkg/config/schema/gke_test.gopkg/datafetcher/schema/atmos/config/1.0.jsonpkg/datafetcher/schema_auth_validation_test.gopkg/schema/schema_auth.gotests/snapshots/TestCLICommands_atmos_--help.stdout.goldentests/snapshots/TestCLICommands_atmos_--help_config_aliases_section.stdout.goldentests/snapshots/TestCLICommands_help_flag_works.stdout.goldentests/test-cases/demo-stacks.yamlwebsite/docs/cli/commands/gcp/_category_.jsonwebsite/docs/cli/commands/gcp/gke/_category_.jsonwebsite/docs/cli/commands/gcp/gke/gke.mdxwebsite/docs/cli/commands/gcp/gke/token.mdxwebsite/docs/cli/commands/gcp/usage.mdxwebsite/docs/cli/configuration/auth/index.mdx
| func executeTokenCommand(cmd *cobra.Command, _ []string) error { | ||
| atmosConfig, err := initCliConfigFn(schema.ConfigAndStacksInfo{}, false) | ||
| if err != nil { | ||
| return fmt.Errorf(errUtils.ErrWrapFormat, errUtils.ErrFailedToInitConfig, err) | ||
| } | ||
| defer perf.Track(&atmosConfig, "gke.executeTokenCommand")() | ||
|
|
||
| identityName := resolveIdentity(cmd) | ||
| ctx := auth.ContextWithSkipIntegrations(context.Background()) | ||
| creds, err := authenticateForTokenFn(ctx, &atmosConfig.Auth, atmosConfig.CliConfigPath, identityName) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== candidate files =="
git ls-files | rg '(^cmd/gcp/gke/(token|gke)\.go$|^internal/auth/.*auth.*\.go$|^pkg/auth/.*\.go$|auth\.go$|cmd/.*flags.*\.go$)' || true
echo "== token.go outline =="
ast-grep outline cmd/gcp/gke/token.go || true
echo "== token.go relevant lines =="
sed -n '1,110p' cmd/gcp/gke/token.go
echo "== Authenticate definitions/usages =="
rg -n "func ContextWithSkipIntegrations|ContextWithSkipIntegrations|func .*Authenticate|Authenticate\(" internal pkg cmd --glob '*.go' || true
echo "== standard parser/usages =="
rg -n "flags\.NewStandardParser|NewStandardParser|cmd\.Context\(" cmd --glob '*.go' | head -n 80 || trueRepository: cloudposse/atmos
Length of output: 1918
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== repository status =="
pwd
git status --short || true
git ls-files | head -n 80 || true
echo "== token.go existence and lines =="
if [ -f cmd/gcp/gke/token.go ]; then
wc -l cmd/gcp/gke/token.go
sed -n '1,90p' cmd/gcp/gke/token.go
else
echo "missing cmd/gcp/gke/token.go"
fi
echo "== auth context wrapper definitions/usages =="
rg -n "ContextWithSkipIntegrations|func \([^)]*\) Context|type .*Context|authenticateForTokenFn|func \(.*Authenticate|Authenticate\(" . --glob '*.go' --glob '!vendor/**' | head -n 200 || true
echo "== command context and parser usage =="
rg -n "cmd\.Context\(\)|flags\.NewStandardParser\(|NewStandardParser\(\"" cmd --glob '*.go' | head -n 120 || trueRepository: cloudposse/atmos
Length of output: 1918
🌐 Web query:
atmos context.ContextWithSkipIntegrations cmd.Context context.Background auth.ContextWithSkipIntegrations
💡 Result:
In the context of the Atmos CLI project, these terms relate to context management, authentication workflows, and command-line execution: context.ContextWithSkipIntegrations: This is a function provided by the github.com/cloudposse/atmos/pkg/auth package [1]. It returns a context derived from a parent context that includes a specific key (skipIntegrationsKey) [2][3]. This modified context is used to signal the authentication manager to skip auto-triggered integrations [1][4]. This is typically employed when performing operations like token generation where explicit integration execution is required, and redundant auto-provisioning (such as re-writing kubeconfig) should be avoided [1][4]. cmd.Context: In Atmos, cmd.Context is the standard method for retrieving the context associated with a cobra.Command [5][6]. It is preferred over context.Background because it propagates cancellations and timeouts managed by the CLI framework throughout the command's execution [5]. context.Background: This is the standard Go library function used to return a non-nil, empty context. It is generally intended to be used as a root context in main functions, init, or tests. In the Atmos codebase, it is often replaced by cmd.Context to ensure that lifecycle management (like command cancellation) is respected [5]. In summary, when developing or interacting with Atmos, you should use cmd.Context to maintain CLI lifecycle awareness [5], and use auth.ContextWithSkipIntegrations when you need to perform authentication without triggering automatic side-effect integrations [1][4].
Citations:
- 1: https://pkg.go.dev/github.com/cloudposse/atmos/pkg/auth
- 2: https://github.com/cloudposse/atmos/blob/v1.221.1/pkg/auth/manager.go
- 3: https://github.com/cloudposse/atmos/blob/5e93aa15/pkg/auth/manager.go
- 4: https://github.com/cloudposse/atmos/blob/v1.221.1/pkg/auth/manager_integrations.go
- 5: Add auth console command for web console access #1684
- 6: https://github.com/cloudposse/atmos/blob/5e93aa15/cmd/git/clone.go
🌐 Web query:
github.com/cloudposse/atmos/pkg/auth ContextWithSkipIntegrations source
💡 Result:
The function ContextWithSkipIntegrations in the cloudposse/atmos Go package (pkg/auth) is a helper utility used to manage the execution of authentication integrations [1][2]. Function Purpose ContextWithSkipIntegrations returns a new context.Context derived from the provided context that contains a specific flag to skip auto-triggered integrations during the authentication process [1][3]. By adding this to a context, developers can signal the auth manager to bypass standard automated triggers [4]. Technical Details - Implementation: It works by using context.WithValue to attach a private key (skipIntegrationsKey) to the context with a boolean value of true [3][4]. - Use Case: It is primarily used when performing explicit operations where auto-triggered integrations are redundant or undesirable, such as generating tokens or executing specific integrations that are already being managed manually [1][4]. This prevents duplicate execution of integration logic, such as re-provisioning infrastructure or rewriting configuration files (e.g., kubeconfig) when they have already been handled by a caller [1][3][4]. - Integration check: The auth manager's triggerIntegrations method checks for the presence of this key in the context; if it is found, the manager logs the skip and returns early, avoiding the execution of linked integrations [4]. This function was introduced to improve the lifecycle management of authentication environments, specifically handling scenarios where explicit execution and auto-provisioning might overlap [2].
Citations:
- 1: https://pkg.go.dev/github.com/cloudposse/atmos/pkg/auth
- 2: feat: Add EKS kubeconfig authentication integration (ATMOS-157) #2149
- 3: https://github.com/cloudposse/atmos/blob/v1.221.1/pkg/auth/manager.go
- 4: https://github.com/cloudposse/atmos/blob/v1.221.1/pkg/auth/manager_integrations.go
Preserve the command cancellation context.
token.go:createAuthCtx currently replaces Cobra’s lifecycle context with context.Background(), so cancellation and deadlines cannot reach mgr.Authenticate. Use auth.ContextWithSkipIntegrations(cmd.Context()) as the command already needs the skip-integrations behavior; add a test for inheritance of the cancellation deadline.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@cmd/gcp/gke/token.go` around lines 53 - 62, The authentication context in
executeTokenCommand must preserve Cobra’s cancellation and deadline while
retaining skip-integrations behavior. Replace the context.Background() input to
auth.ContextWithSkipIntegrations with cmd.Context(), and add coverage verifying
cancellation/deadline inheritance reaches authenticateForTokenFn.
Source: Coding guidelines
| case integrations.KindGCPGKE: | ||
| if cfg.Spec != nil && cfg.Spec.Cluster != nil { | ||
| cluster := cfg.Spec.Cluster | ||
| return fmt.Sprintf("gcp/gke:%s:%s:%s", cluster.ProjectID, cluster.Location, cluster.Name) | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Include kubeconfig output settings in the GKE cache key.
This key identifies only the GKE cluster. Execute also writes a configured kubeconfig path, context alias, update behavior, and exec-plugin identity. If two linked integrations use the same cluster with different output settings, the cache skips the second integration. Its kubeconfig entry is then missing or has the wrong identity.
Include all output-affecting settings in the key, or skip GKE target deduplication. Add coverage for two integrations that share a cluster but use different kubeconfig paths, aliases, or identities.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@pkg/auth/manager_integrations.go` around lines 49 - 53, Update the GKE key
generation in the KindGCPGKE handling to include every kubeconfig
output-affecting setting consumed by Execute, including configured path, context
alias, update behavior, and exec-plugin identity, so integrations sharing a
cluster but differing in any of these values produce distinct keys;
alternatively disable GKE target deduplication. Add coverage for integrations
sharing a cluster with different paths, aliases, or identities.
| "kubeconfig": map[string]interface{}{ | ||
| "path": "/tmp/example-kubeconfig", | ||
| "update": "replace", |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Use a platform-neutral kubeconfig path in the fixture.
Line [242] hardcodes a Unix path in a Go test. Use filepath.Join(t.TempDir(), "example-kubeconfig") and import path/filepath.
As per coding guidelines, Go tests must use filepath.Join for paths and avoid Unix-specific paths.
Proposed fix.
import (
+ "path/filepath"
"testing"
@@
- "path": "/tmp/example-kubeconfig",
+ "path": filepath.Join(t.TempDir(), "example-kubeconfig"),📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "kubeconfig": map[string]interface{}{ | |
| "path": "/tmp/example-kubeconfig", | |
| "update": "replace", | |
| "kubeconfig": map[string]interface{}{ | |
| "path": filepath.Join(t.TempDir(), "example-kubeconfig"), | |
| "update": "replace", |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@pkg/datafetcher/schema_auth_validation_test.go` around lines 241 - 243,
Update the kubeconfig fixture in the relevant test to set its path with
filepath.Join(t.TempDir(), "example-kubeconfig") instead of the hardcoded Unix
path, and add the path/filepath import. Preserve the existing fixture structure
and values.
Source: Coding guidelines
| import Intro from '@site/src/components/Intro' | ||
|
|
||
| <Intro> | ||
| Configure a GKE kubeconfig whose short-lived access tokens are supplied dynamically by Atmos Auth. No `gcloud`, Application Default Credentials bootstrap, or external GKE authentication plugin is required. | ||
| </Intro> |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift
Complete the required CLI command documentation template.
These new command pages omit required user guidance. Add a static CastPlayer and an Examples section to each page. Add a Usage section to the GKE page. Document only flags that each command supports.
website/docs/cli/commands/gcp/gke/gke.mdx#L8-L12: Add staticCastPlayer, Usage, and Examples.website/docs/cli/commands/gcp/gke/token.mdx#L7-L11: Add staticCastPlayerand Examples.website/docs/cli/commands/gcp/usage.mdx#L7-L12: Add staticCastPlayerand Examples.
As per coding guidelines, “Every CLI command documentation file must include required frontmatter, Intro and Screengrab components, Usage, Examples, and <dl> argument/flag definitions.” Based on learnings, use CastPlayer with static instead of the legacy Screengrab component.
📍 Affects 3 files
website/docs/cli/commands/gcp/gke/gke.mdx#L8-L12(this comment)website/docs/cli/commands/gcp/gke/token.mdx#L7-L11website/docs/cli/commands/gcp/usage.mdx#L7-L12
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@website/docs/cli/commands/gcp/gke/gke.mdx` around lines 8 - 12, Complete the
CLI documentation template in website/docs/cli/commands/gcp/gke/gke.mdx lines
8-12 by adding a static CastPlayer, Usage, and Examples sections documenting
only supported flags; in website/docs/cli/commands/gcp/gke/token.mdx lines 7-11
and website/docs/cli/commands/gcp/usage.mdx lines 7-12, add static CastPlayer
and Examples sections documenting only supported flags. Ensure all three pages
retain the required frontmatter, Intro, and <dl> argument/flag definitions,
using CastPlayer with static rather than Screengrab.
Sources: Coding guidelines, Learnings
Summary
Adds native GKE kubeconfig authentication as an Atmos Auth integration, stacked on #2790.
gcp/gkewith requiredproject_id,location, and clusternameprojects/{project}/locations/{location}/clusters/{name}resource through the native GKE API using Atmos-issuedGCPCredentialsatmos gcp gke tokenas the kubeconfig exec plugin, which refreshes through Atmos Auth while suppressing recursive integration executionKUBECONFIGandKUBE_CONFIG_PATHthrough the Auth identity environmentArchitecture and security
The kubeconfig stores the GKE endpoint, CA data, and an Atmos exec stanza only. It never persists an OAuth bearer token. Cluster discovery and token output both require the GCP credential type already produced by Atmos Auth.
No
gcloud, Application Default Credentials bootstrap, orgke-gcloud-auth-pluginis used. The token command writes only KubernetesExecCredentialJSON to stdout and does not include sensitive token material in errors.Example configuration uses generic names:
The runtime identity needs permission to call
container.clusters.get; Kubernetes authorization remains controlled by cluster RBAC.Validation
go test -p=4 ./pkg/auth/... -count=1— 3,960 passed across 37 packagesgo test ./cmd/gcp/... -count=1— 12 passedgo test ./pkg/config/schema/... ./pkg/datafetcher/... -count=1— 210 passedgo build .— passedgit diff --check— passedStack dependency
This PR intentionally targets
osterman/aks-acr-supportand contains only the GKE/Auth commit on top of #2790. No Helm or secrets implementation was changed. After #2790 merges, this branch should be rebased or retargeted tomainwhile preserving the single GKE commit.Summary by CodeRabbit
atmos gcp gke tokenfor Kubernetes-compatible authentication tokens.