通过脚本更新Jenkins凭证 [英] update Jenkins credentials by script

查看:679
本文介绍了通过脚本更新Jenkins凭证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在Windows上运行的Jenkins服务器.它将用户名:密码存储在凭据插件中.这是服务用户,其密码会定期更新.

I have a Jenkins server running on Windows. It stores a username:password in the credentials plugin. This is a service user that gets its password updated regularly.

我正在寻找一种运行脚本的方法,最好是Powershell,它将更新Jenkins密码存储区中的该凭证,以便在构建作业脚本中使用该凭证时始终是最新的.

I'm looking for a way to run a script, preferably Powershell, that will update that credential in the Jenkins password store so that it's always up to date when I use it in a build job script.

该密码由Thycotic Secret Server安装管理,因此我应该能够使该密码保持最新状态,但是即使博客文章撰写凭据api的人几乎完全提到了这种情况,然后继续链接到凭据插件的下载页面,该页面未说明如何实际使用api.

The password is managed by a Thycotic Secret Server install so I should be able to automate the process of keeping this password up to date, but I have found almost no leads for how to accomplish this, even though the blog post by the guy who wrote the credentials api mentions almost exactly this scenario and then proceeds to just link to the credentials plugin's download page that says nothing about how to actually use the api.

更新

Update

可接受的答案效果很好,但是其余方法调用示例使用的是curl,如果您使用的是Windows,则无济于事.特别是如果您尝试调用REST URL,但您的Jenkins服务器正在使用AD Integration.为此,您可以使用以下脚本.

The accepted answer works perfectly, but the rest method call example is using curl, which if you're using windows doesn't help much. Especially if you are trying to invoke the REST URL but your Jenkins server is using AD Integration. To achieve this you can use the following script.

通过转到人员">用户">配置">显示API令牌"来查找userId和API令牌.

Find the userId and API Token by going to People > User > configure > Show API Token.

$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

推荐答案

Jenkins支持使用Groovy语言编写脚本.您可以通过在浏览器中打开URL来获取脚本编写控制台.您的Jenkins实例的/script. (即: http://localhost:8080/script )

Jenkins supports scripting with the Groovy language. You can get a scripting console by opening in a browser the URL /script of your Jenkins instance. (i.e: http://localhost:8080/script)

Groovy语言的优势(通过Powershell或其他方式)的优点是,这些Groovy脚本在Jenkins中执行,并且可以访问所有内容(配置,插件,作业等).

The advantage of the Groovy language (over powershell, or anything else) is that those Groovy scripts are executed within Jenkins and have access to everything (config, plugins, jobs, etc).

然后下面的代码会将用户'BillHurt'的密码更改为's3crEt!':

Then the following code would change the password for user 'BillHurt' to '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命令:


Classic automation (/scriptText)

To automate the execution of this script, you can save it to a file (let's say /tmp/changepassword.groovy) and run the following curl command:

curl -d "script=$(cat /tmp/changepassword.groovy)" http://localhost:8080/scriptText

应该以HTTP 200状态和文字回应:

which should respond with a HTTP 200 status and text:

找到了用户名BillHurt的凭据801cf176-3455-4b6d-a461-457a288fd202

found credential 801cf176-3455-4b6d-a461-457a288fd202 for username BillHurt

BillHurt的密码已更改

password changed for BillHurt

使用Scriptler插件实现自动化

您还可以安装Jenkins Scriptler插件,然后按照以下步骤进行操作:

Automation with the Scriptler plugin

You can also install the Jenkins Scriptler plugin and proceed as follow:

  • 打开侧面菜单中的 Scriptler 工具

  • 填写第三个字段,注意将 Id 字段设置为changeCredentialPassword.groovy
  • 选中定义脚本参数复选框
  • 添加2个参数:usernamepassword
  • 粘贴以下脚本:
  • fill up the 3 first field taking care to set the Id field to changeCredentialPassword.groovy
  • check the Define script parameters checkbox
  • add 2 parameters: username and password
  • paste the following script:
    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")

  • 然后单击提交按钮
    • and click the Submit button
    • 现在,您可以调用以下URL来更改密码(替换usernamepassword参数): urlencode 参数的值)

      Now you can call the following URL to change the password (replacing the username and password parameter): http://localhost:8080/scriptler/run/changeCredentialPassword.groovy?username=BillHurt&password=s3crEt%21 (notice the need to urlencode the parameters' value)

      或卷曲:

      curl -G http://localhost:8080/scriptler/run/changeCredentialPassword.groovy --data-urlencode 'username=BillHurt' --data-urlencode "password=s3crEt!"
      


      来源:


      sources:

      • Printing a list of credentials and their IDs
      • Create UserPrivateKeySource Credential via Groovy?
      • credential plugin source code
      • Scriptler plugin

      搜索引擎提示:使用关键字'Jenkins.instance.''com.cloudbees.plugins.credentials'UsernamePasswordCredentialsImpl

      Search engine tip: use keywords 'Jenkins.instance.', 'com.cloudbees.plugins.credentials' and UsernamePasswordCredentialsImpl

      这篇关于通过脚本更新Jenkins凭证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆