我在Windows上运行Jenkins服务器。它在凭证插件中存储用户名:密码。这是一个定期更新密码的服务用户。
我正在寻找一种运行脚本的方法,最好是Powershell,它将更新Jenkins密码存储区中的凭据,以便在构建作业脚本中使用它时始终保持最新状态
密码由Thycotic Secret Server安装管理,因此我应该能够自动保持此密码的最新状态,但我发现如何完成此操作几乎没有任何线索,即使{{3}编写凭据api的人几乎完全提到了这个场景,然后继续链接到凭据插件的下载页面,该页面没有说明如何实际使用api。
更新
接受的答案完美无缺,但其余的方法调用示例使用curl,如果您使用Windows,则无法提供帮助。特别是如果您尝试调用REST URL但Jenkins服务器正在使用AD Integration。要实现此目的,您可以使用以下脚本。
转到People>找到userId和API令牌用户>配置>显示API令牌。
$user = "UserID"
$pass = "APIToken"
$pair = "${user}:${pass}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$headers = @{ Authorization = $basicAuthValue }
Invoke-WebRequest `
-uri "http://YourJenkinsServer:8080/scriptler/run/changeCredentialPassword.groovy?username=UrlEncodedTargetusername&password=URLEncodedNewPassword" `
-method Get `
-Headers $headers
答案 0 :(得分:19)
Jenkins支持使用Groovy语言编写脚本。您可以通过在浏览器中打开Jenkins实例的URL /script
来获取scripting console。 (即:http://localhost:8080/script)
Groovy语言(在powershell或其他任何方面)的优点是那些Groovy脚本在Jenkins中执行并且可以访问所有内容(配置,插件,作业等)。
然后以下代码将更改用户' BillHurt'到' s3crEt!':
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl
def changePassword = { username, new_password ->
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
Jenkins.instance
)
def c = creds.findResult { it.username == username ? it : null }
if ( c ) {
println "found credential ${c.id} for username ${c.username}"
def credentials_store = Jenkins.instance.getExtensionList(
'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
)[0].getStore()
def result = credentials_store.updateCredentials(
com.cloudbees.plugins.credentials.domains.Domain.global(),
c,
new UsernamePasswordCredentialsImpl(c.scope, c.id, c.description, c.username, new_password)
)
if (result) {
println "password changed for ${username}"
} else {
println "failed to change password for ${username}"
}
} else {
println "could not find credential for ${username}"
}
}
changePassword('BillHurt', 's3crEt!')
/scriptText
)要自动执行此脚本,您可以将其保存到文件中(让我们说/tmp/changepassword.groovy
)并运行以下curl命令:
curl -d "script=$(cat /tmp/changepassword.groovy)" http://localhost:8080/scriptText
应以HTTP 200
状态和文字回复:
找到用户名BillHurt的凭证801cf176-3455-4b6d-a461-457a288fd202
为BillHurt更改了密码
您也可以安装Jenkins Scriptler plugin并按以下步骤操作:
changeCredentialPassword.groovy
username
和password
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl
def changePassword = { username, new_password ->
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
jenkins.model.Jenkins.instance
)
def c = creds.findResult { it.username == username ? it : null }
if ( c ) {
println "found credential ${c.id} for username ${c.username}"
def credentials_store = jenkins.model.Jenkins.instance.getExtensionList(
'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
)[0].getStore()
def result = credentials_store.updateCredentials(
com.cloudbees.plugins.credentials.domains.Domain.global(),
c,
new UsernamePasswordCredentialsImpl(c.scope, null, c.description, c.username, new_password)
)
if (result) {
println "password changed for ${username}"
} else {
println "failed to change password for ${username}"
}
} else {
println "could not find credential for ${username}"
}
}
changePassword("$username", "$password")
现在您可以调用以下网址来更改密码(替换username
和password
参数):http://localhost:8080/scriptler/run/changeCredentialPassword.groovy?username=BillHurt&password=s3crEt%21(注意需要urlencode参数&#39 ;价值)
或使用curl:
curl -G http://localhost:8080/scriptler/run/changeCredentialPassword.groovy --data-urlencode 'username=BillHurt' --data-urlencode "password=s3crEt!"
来源:
搜索引擎提示:使用关键字'Jenkins.instance.'
,'com.cloudbees.plugins.credentials'
和UsernamePasswordCredentialsImpl
答案 1 :(得分:2)
决定写一个新的答案虽然它基本上是对@ Tomasleveil的答案的一些更新:
这就是:
credentialsDescription = "my credentials description"
newPassword = "hello"
// list credentials
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
// com.cloudbees.plugins.credentials.common.StandardUsernameCredentials to catch all types
com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials.class,
Jenkins.instance,
null,
null
);
// select based on description (based on ID might be even better)
cred = creds.find { it.description == credentialsDescription}
println "current values: ${cred.username}:${cred.password} / ${cred.id}"
// not sure what the other stores would be useful for, but you can list more stores by
// com.cloudbees.plugins.credentials.CredentialsProvider.all()
credentials_store = jenkins.model.Jenkins.instance.getExtensionList(
'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
)[0].getStore()
// replace existing credentials with a new instance
updated = credentials_store.updateCredentials(
com.cloudbees.plugins.credentials.domains.Domain.global(),
cred,
// make sure you create an instance from the correct type
new com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl(cred.scope, cred.id, cred.description, cred.username, newPassword)
)
if (updated) {
println "password changed for '${cred.description}'"
} else {
println "failed to change password for '${cred.description}'"
}
答案 2 :(得分:1)
我从未找到过让Groovy脚本停止更新凭据ID的方法,但我注意到如果我使用Web界面更新凭据,则ID不会更改。
考虑到这一点,下面的脚本实际上将编写Jenkins Web界面的脚本来进行更新。
只是为了澄清,这一点很重要的原因是因为如果您使用Credentials绑定插件之类的东西来使用作业中的凭据,那么将ID更新为凭据将破坏该链接并且您的作业将失败。请原谅$ args而不是param()的使用,因为这只是一个丑陋的黑客攻击,我将在稍后进行完善。
请注意将json有效内容添加到表单字段。我发现这种非常特殊的格式需要这么做,否则表单提交就会失败。
$username = $args[0]
$password = $args[1]
Add-Type -AssemblyName System.Web
#1. Log in and capture the session.
$homepageResponse = Invoke-WebRequest -uri http://Servername.domain.com/login?from=%2F -SessionVariable session
$loginForm = $homepageResponse.Forms['login']
$loginForm.Fields.j_username = $username
$loginForm.Fields.j_password = $password
$loginResponse = Invoke-WebRequest `
-Uri http://Servername.domain.com/j_acegi_security_check `
-Method Post `
-Body $loginForm.Fields `
-WebSession $session
#2. Get Credential ID
$uri = "http://Servername.domain.com/credential-store/domain/_/api/xml"
foreach($id in [string]((([xml](Invoke-WebRequest -uri $uri -method Get -Headers $headers -WebSession $session).content)).domainWrapper.Credentials | Get-Member -MemberType Property).Name -split ' '){
$id = $id -replace '_',''
$uri = "http://Servername.domain.com/credential-store/domain/_/credential/$id/api/xml"
$displayName = ([xml](Invoke-WebRequest -uri $uri -method Get -Headers $headers -WebSession $session).content).credentialsWrapper.displayName
if($displayName -match $username){
$credentialID = $id
}
}
#3. Get Update Form
$updatePage = Invoke-WebRequest -Uri "http://Servername.domain.com/credential-store/domain/_/credential/$credentialID/update" -WebSession $session
$updateForm = $updatePage.Forms['update']
$updateForm.Fields.'_.password' = $password
#4. Submit Update Form
$json = @{"stapler-class" = "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl";
"scope"="GLOBAL";"username"="domain\$username";"password"=$password;"description"="";"id"=$id} | ConvertTo-Json
$updateForm.Fields.Add("json",$json)
Invoke-WebRequest `
-Uri "http://Servername.domain.com/credential-store/domain/_/credential/$credentialID/updateSubmit" `
-Method Post `
-Body $updateForm.Fields `
-WebSession $session