简介
Jenkins 凭据功能允许你在 Jenkins 中存储密码、令牌和密钥,而无需将敏感信息直接硬编码到作业脚本中。作业可以通过 ID 来引用这些凭据。
在本实验中,你将使用 Jenkins 控制面板打开全局凭据存储区,创建一个用户名/密码凭据,确认 Jenkins 会对密钥进行掩码处理和加密,并在不更改 ID 的情况下更新该凭据。
打开全局凭据存储区
在此步骤中,你将在控制面板中找到 Jenkins 凭据存储区。Jenkins 按存储区(Store)和域(Domain)来组织凭据。对于初学者工作流,最常用的位置是 System 存储区和 Global 域。
打开桌面界面。Firefox 会自动打开 Jenkins。如果未打开,请访问 http://localhost:8080。
在 Jenkins 控制面板中:
点击左侧边栏的 Manage Jenkins,然后点击 Credentials。在 Credentials 页面上,点击 System,然后点击 Global。
页面标题应为 Global,并且页面会显示这些凭据在任何地方均可用。

在终端中运行以下命令,记录已成功访问全局凭据页面:
curl -fsS http://localhost:8080/manage/credentials/store/system/domain/_/ | grep -o 'Credentials that should be available everywhere' | tee /home/labex/project/credential-storage-page.txt
你应该会看到:
Credentials that should be available everywhere
添加用户名和密码凭据
在此步骤中,你将使用 Jenkins 表单创建一个凭据。凭据 ID 非常重要,因为作业和流水线稍后将通过此 ID 进行引用。
在 Global 凭据页面上,点击 Add Credentials。
在表单中填入以下值:
Kind:Username with passwordScope:GlobalUsername:guided-userPassword:guided-password-v1ID:guided-credsDescription:Guided lab credential for Jenkins storage
点击 Create。
Jenkins 返回 Global 域页面后,你应该能看到一个名为 guided-creds 的凭据。Jenkins 会显示用户名,但会对密码进行掩码处理。

检查 Jenkins 如何存储密钥
在此步骤中,你将检查 Jenkins 写入磁盘的内容。这通常不是日常 Jenkins 工作中需要做的操作,但它能帮你理解为什么凭据比作业脚本中的明文密码更安全。
在终端中,仅打印 Jenkins credentials.xml 文件中的相关行:
docker exec jenkins sh -lc "grep -n -E '<id>guided-creds</id>|<username>guided-user</username>|<password>' /var/jenkins_home/credentials.xml" | tee /home/labex/project/credential-file-lines.txt
输出应包含凭据 ID 和用户名。密码行应包含用大括号包裹的加密 Jenkins 密钥,而不是原始文本 guided-password-v1。
输出示例:
...<id>guided-creds</id>
...<username>guided-user</username>
...<password>{...}</password>
回到 Firefox 中的 Jenkins Global 域页面。凭据行也应将密码显示为掩码文本,而不是真实密码。
在不更改 ID 的情况下更新凭据
在此步骤中,你将通过 Jenkins 控制面板更新凭据描述,同时保持凭据 ID 不变。这展示了初学者首先需要掌握的核心理念:作业应引用稳定的 ID(如 guided-creds),而管理员可以在后续调整凭据元数据。
在 Global 凭据页面上:
点击 guided-creds 凭据,然后点击 Update credential。保持 Username、Password 和 ID 不变。将 Description 修改为 Updated guided lab credential,然后点击 Save。
保存后,返回 Global 域页面。相同的凭据 ID 应该仍然可见,但描述现在应变为 Updated guided lab credential。

运行以下命令,确认 Jenkins 仍保留相同的 ID 和更新后的描述:
docker exec jenkins sh -lc "grep -n -E '<id>guided-creds</id>|<description>Updated guided lab credential</description>|<password>' /var/jenkins_home/credentials.xml" | tee /home/labex/project/updated-credential-lines.txt
密码应保持加密状态,且不应出现原始文本 guided-password-v1。
总结
你使用了 Jenkins 控制面板打开全局凭据存储区,创建了一个用户名/密码凭据,观察到 Jenkins 对密钥进行了掩码和加密处理,并在保持稳定 ID 的前提下更新了凭据元数据。