如何通过API/CLI获取Sonatype Nexus中新创建用户的Nuget API Key
可行实现方案
完全可以实现全自动化配置,无需手动登录 Nexus 图形界面获取 API Key,具体操作步骤如下:
- 前提准备:提前在 Ansible 变量中存储 Nexus 管理员账号的用户名和密码,该账号具备用户管理权限,可用于调用管理员级别的 REST API。
- 调用 Nexus 原生 API 获取目标用户 API Key:
Nexus 官方提供了管理员获取指定用户 API Key 的端点,接口路径为GET /service/rest/v1/security/users/{目标用户名}/api-key,使用管理员凭证做基础认证即可调用,接口返回内容中直接包含对应用户的 API Key 字段。 - 集成到 Ansible Playbook 流程中:
在创建用户的任务之后,新增 Ansible uri 模块调用上述接口,将返回的 API Key 注册为变量,后续流程直接引用该变量即可,无需修改 Playbook 配置。
参考任务代码示例:- name: 获取指定 Nexus 用户的 API Key ansible.builtin.uri: url: "{{ nexus_base_url }}/service/rest/v1/security/users/{{ target_nexus_username }}/api-key" method: GET user: "{{ nexus_admin_username }}" password: "{{ nexus_admin_password }}" force_basic_auth: yes status_code: 200 register: nexus_user_api_key_resp retries: 5 delay: 2 until: nexus_user_api_key_resp is succeeded # 后续使用方法:API Key 存储在 {{ nexus_user_api_key_resp.json.apiKey }} 变量中 - 异常排查说明:如果调用接口返回404状态码,可先检查 Nexus 安全配置中是否已启用 API Key 功能,默认情况下 Nexus 3 较新版本均已默认开启该功能。
不需要额外使用 CLI 工具实现,CLI 本质也是封装了上述 REST API,直接调用 API 无需额外安装依赖,更适配 Ansible 自动化场景。
内容的提问来源于stack exchange,提问作者ZZTest
相关产品推荐
相关产品推荐

