ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Argo CD CLI 深度解析:argocd account generate-token 账号 API Token 生成全流程

Argo CD CLI 深度解析:argocd account generate-token 账号 API Token 生成全流程 Argo CD CLI 深度解析argocd account generate-token 账号 API Token 生成全流程【免费下载链接】argo-cdDeclarative Continuous Deployment for Kubernetes项目地址: https://gitcode.com/GitHub_Trending/ar/argo-cd本文围绕 argocd account generate-token 命令参考 展开完整讲解该命令的语法、全部参数含继承自父命令的通用参数并结合 cmd/argocd/commands/account.go 与 server/account/account.go 的源码还原从 CLI 发起请求到服务端签发 JWT 的完整调用链。读完本文你将掌握为 Argo CD 账号生成 API Token 的方法、Token 的能力边界apiKeycapability、RBAC 权限要求以及 Token 的撤销与生命周期管理可以直接用于 CI/CD 流水线或脚本中的免交互认证。命令定位什么是 Account Tokenargocd account generate-token用于为一个账号生成API Token。与登录产生的会话 TokenSession Token不同通过该命令生成的 Token面向 API 调用--auth-token参数或Authorization: Bearer头适合无头环境CI、脚本、Kubernetes Job默认永不过期--expires-in默认为0s可以长期作为服务账号凭证可以被显式撤销——服务端会记录每个 Token 的id删除记录后该 Token 即失效详见下文 Token 生命周期一节。在 CLI 命令参考目录 中它与session-token、delete-token、get、update-password等命令共同构成账号管理命令族。命令语法与官方示例argocd account generate-token [flags]官方文档给出的两个基本用法继承自 docs/user-guide/commands/argocd_account_generate-token.md# 为当前登录的账号生成 token argocd account generate-token # 为指定名称的账号生成 token argocd account generate-token --account account-name常用实战组合# 为当前账号生成一个 24 小时后过期、id 为 ci-bot 的 token argocd account generate-token --expires-in 24h --id ci-bot # 生成的 token 可直接用于后续 CLI 调用 export ARGOCD_AUTH_TOKEN$(argocd account generate-token --expires-in 72h)注意命令输出为纯 token 字符串无额外格式因此可以直接用命令替换写入环境变量或 Secret。完整参数说明本命令自有选项选项说明默认值-a, --account string目标账号名。缺省时为当前登录账号当前账号-e, --expires-in stringToken 过期时长Go duration 格式如24h、30d。默认永不过期0s不过期--id string可选的 Token id。未指定时服务端回退为随机 UUID随机 UUID-h, --help显示帮助-从源码看--expires-in在客户端用timeutil.ParseDuration解析后以秒数传入服务端见 NewAccountGenerateTokenCommand因此支持 Kubernetes 风格的时长单位。继承自父命令的通用选项以下选项继承自argocd根命令完整列表与官方文档一致在实际使用中--server、--auth-token、--grpc-web等最常出现--argocd-context string The name of the Argo-CD server context to use --auth-token string Authentication token; set this or the ARGOCD_AUTH_TOKEN environment variable --client-crt string Client certificate file --client-crt-key string Client certificate key file --config string Path to Argo CD config (default /home/user/.config/argocd/config) --controller-name string Name of the Argo CD Application controller; set this or the ARGOCD_APPLICATION_CONTROLLER_NAME environment variable when the controllers name label differs from the default, for example when installing via the Helm chart (default argocd-application-controller) --core If set to true then CLI talks directly to Kubernetes instead of talking to Argo CD API server --grpc-web Enables gRPC-web protocol. Useful if Argo CD server is behind proxy which does not support HTTP2. --grpc-web-root-path string Enables gRPC-web protocol. Useful if Argo CD server is behind proxy which does not support HTTP2. Set web root. -H, --header strings Sets additional header to all requests made by Argo CD CLI. (Can be repeated multiple times to add multiple headers, also supports comma separated headers) --http-retry-max int Maximum number of retries to establish http connection to Argo CD server --insecure Skip server certificate and domain verification --kube-context string Directs the command to the given kube-context --logformat string Set the logging format. One of: json|text (default json) --loglevel string Set the logging level. One of: debug|info|warn|error (default info) --plaintext Disable TLS --port-forward Connect to a random argocd-server port using port forwarding --port-forward-namespace string Namespace name which should be used for port forwarding --prompts-enabled Force optional interactive prompts to be enabled or disabled, overriding local configuration. If not specified, the local configuration value will be used, which is false by default. --redis-compress string Enable this if the application controller is configured with redis compression enabled. (possible values: gzip, none) (default gzip) --redis-haproxy-name string Name of the Redis HA Proxy; set this or the ARGOCD_REDIS_HAPROXY_NAME environment variable when the HA Proxys name label differs from the default, for example when installing via the Helm chart (default argocd-redis-ha-haproxy) --redis-name string Name of the Redis deployment; set this or the ARGOCD_REDIS_NAME environment variable when the Rediss name label differs from the default, for example when installing via the Helm chart (default argocd-redis) --repo-server-name string Name of the Argo CD Repo server; set this or the ARGOCD_REPO_SERVER_NAME environment variable when the servers name label differs from the default, for example when installing via the Helm chart (default argocd-repo-server) --server string Argo CD server address --server-crt string Server certificate file --server-name string Name of the Argo CD API server; set this or the ARGOCD_SERVER_NAME environment variable when the servers name label differs from the default, for example when installing via the Helm chart (default argocd-server)客户端执行流程源码解析命令的客户端实现在 NewAccountGenerateTokenCommandcmd/argocd/commands/account.go。其执行逻辑可以归纳为四步// 1. 未指定 --account 时先调用 Session.GetUserInfo 取当前登录用户名 if account { account getCurrentAccount(ctx, clientset).Username } // 2. 把 --expires-in 的字符串解析成 duration expiresIn, err : timeutil.ParseDuration(expiresIn) // 3. 通过 gRPC AccountClient 的 CreateToken 方法把 {Name, ExpiresIn, Id} 发给服务端 response, err : client.CreateToken(ctx, accountpkg.CreateTokenRequest{ Name: account, ExpiresIn: int64(expiresIn.Seconds()), Id: id, }) // 4. 把返回的 token 字符串直接打印到 stdout fmt.Println(response.Token)几个值得注意的细节--account的默认值不是本地配置而是服务端确认的当前身份。客户端会先调用 Session 服务的GetUserInfo获取用户名再把它作为CreateTokenRequest.Name发给服务端getCurrentAccount实现见 cmd/argocd/commands/account.go#L296-L302。Token id 由调用方决定--id留空时客户端传空字符串UUID 由服务端生成下文说明。过期时长以秒为单位传输ExpiresIn: int64(expiresIn.Seconds())0表示永不过期。服务端 CreateToken签发、校验与持久化服务端的实现在 Server.CreateTokenserver/account/account.go。这是整个流程的核心做了五件关键的事1. RBAC 权限校验if err : s.ensureHasAccountPermission(ctx, rbac.ActionUpdate, r.Name); err ! nil { return nil, fmt.Errorf(permission denied to create token for account %s: %w, r.Name, err) }ensureHasAccountPermissionserver/account/account.go#L187-L198的判定规则是账号对自己天然有权限当请求者身份等于目标账号、且 Token 签发方是 Argo CD 本地的 SessionManager即本地用户而非 SSO 登录时直接放行其余情况要求调用者对accounts资源拥有update权限s.enf.EnforceErr(..., rbac.ResourceAccounts, rbac.ActionUpdate, account)否则返回permission denied for account %s with action update。这意味着普通用户只能为自己生成 Token要替其他账号生成 Token需要在 RBAC 策略中授予accounts资源的update权限。2. Token id 的缺省与去重id : r.Id if id { uniqueId, err : uuid.NewRandom() id uniqueId.String() }未传--id时服务端生成随机 UUID随后在账号更新闭包中通过account.TokenIndex(id) -1检查 id 冲突重复会报account already has token with id %s。这解释了为什么给 CI 指定固定--id便于后续审计但重复执行会失败——需要先delete-token。3. apiKey 能力capability校验if !account.HasCapability(settings.AccountCapabilityApiKey) { return fmt.Errorf(account %s does not have %s capability, r.Name, settings.AccountCapabilityApiKey) }账号能力定义在 util/settings/accounts.go#L36-L43const ( // AccountCapabilityLogin represents capability to create UI session tokens. AccountCapabilityLogin AccountCapability login // AccountCapabilityLogin represents capability to generate API auth tokens. AccountCapabilityApiKey AccountCapability apiKey )也就是说Ardo CD 把“能登录 UI 产生会话 Token”login和“能生成 API Token”apiKey拆成了两种独立能力。如果目标账号没有apiKey能力generate-token 会直接失败并提示account xxx does not have apiKey capability。这也是区分“人类用户账号”和“API 服务账号”的核心机制。4. 签发 JWTtokenString, err s.sessionMgr.Create(fmt.Sprintf(%s:%s, r.Name, settings.AccountCapabilityApiKey), r.ExpiresIn, id)Token 本身由 SessionManager 签发为 JWT实现见 util/session/sessionmanager.go其主题subject是账号名:apiKey形式的标识并携带id与可选的过期时间。5. 登记到账号的 Token 清单var expiresAt int64 if r.ExpiresIn 0 { expiresAt now.Add(time.Duration(r.ExpiresIn) * time.Second).Unix() } account.Tokens append(account.Tokens, settings.Token{ ID: id, IssuedAt: now.Unix(), ExpiresAt: expiresAt, })Token 的元数据ID/IssuedAt/ExpiresAt以Token结构util/settings/accounts.go#L45-L50追加到账号的Tokens列表最终随账号信息持久化到 SettingsManager 管理的 Kubernetes Secret/ConfigMap见saveAccountutil/settings/accounts.go#L93-L99。这个登记动作正是 Token 可被撤销的基础util/session/sessionmanager.go 在验证 JWT 时对apiKey类 Token 会检查account.TokenIndex(id) -1即拒绝——Token 的 id 不在账号清单里就等于已被吊销。Token 生命周期管理生成只是第一步完整生命周期包含查看、使用与撤销对应的 CLI 命令都在 docs/user-guide/commands 目录中有参考文档查看已有 Tokenargocd account getdocs/user-guide/commands/argocd_account_get.md会列出账号及其 Token 表。其展示逻辑在 printAccountDetailsTokens: ID ISSUED AT EXPIRING AT uuid 2025-01-01T00:00:00Z never # ExpiresAt 0 时显示 never id 2025-01-01T00:00:00Z 2025-02-01T00:00:00Z (expired) # 过期后会追加 (expired)撤销 Tokenargocd account delete-token IDdocs/user-guide/commands/argocd_account_delete-token.md按 id 删除 Token 记录。客户端实现NewAccountDeleteTokenCommand在执行前会有Are you sure you want to delete id token? [y/n]的交互确认--prompts-enabled控制服务端实现 Server.DeleteToken 要求同样具备accounts资源的update权限并从账号的Tokens列表移除该记录——从此该 JWT 在服务端验签时会被拒绝。与 session-token 的关系argocd account session-tokendocs/user-guide/commands/argocd_account_session-token.md输出的是当前登录会话的 Token支持 SSO 刷新适用于交互式调试而generate-token生成的 API Token 独立于任何一次登录会话适合写入ARGOCD_AUTH_TOKEN长期供脚本使用。两者的取舍可概括为会话 Token 随登录态走API Token 随账号生命周期走、可显式撤销。常见报错与排查报错原因处理permission denied for account name with action update调用者对该账号无accounts资源的update权限且不是本地登录的自己用有权限的账号执行或调整 RBAC 策略可用argocd account can-i自查account xxx does not have apiKey capability目标账号缺少apiKey能力为目标账号启用 apiKey 能力如使用内置 admin 类服务账号account already has token with id xxx指定了已存在的--id更换 id或先argocd account delete-token id另外注意generate-token要求先有有效登录态本地用户登录或 SSO 会话才能发起请求生成的 Token 权限上限就是该账号的 RBAC 权限不会因此获得额外授权。小结argocd account generate-token表面上只是一行命令背后串联了一条完整的链路CLI 通过Session.GetUserInfo确定目标账号并解析--expires-incmd/argocd/commands/account.go→ 服务端CreateToken依次做 RBACupdate校验、id 去重、apiKeycapability 校验、JWT 签发与账号 Token 清单登记server/account/account.go→ Token 元数据持久化于账号配置util/settings/accounts.go并通过“id 不在清单即拒绝”的机制支持随时撤销。理解了这条链路你就能按需选择--expires-in/--id、正确配置服务账号能力并在 CI/CD 中安全地管理与回收这些 API Token。【免费下载链接】argo-cdDeclarative Continuous Deployment for Kubernetes项目地址: https://gitcode.com/GitHub_Trending/ar/argo-cd创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表