用于通过 ID(而不是用户名)删除 Jenkins 全局凭据用户的 groovy 脚本



我正在尝试使用 .groovy 脚本删除存储在全局凭据存储中的凭据。 我想按 ID 值而不是用户名进行搜索和删除。

这是我到目前为止的代码:

import hudson.model.User
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
    com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
    Jenkins.instance,
    null,
    null
)

//ID I intend on deleting
id_name ='test-id-name'

//here we cycle through all the credentials until we find the intended id
for (c in creds) {
  if (c.id == id_name){
    println("Found existing ID")
    //here we attempt to delete  by id
    User u = User.get(id_name)
    u.delete()
  }
}

当我运行代码时,它会打印出一行,说它找到了 ID,但实际上并没有删除。 我没有收到错误。

以这段代码为例:https://github.com/jenkinsci/jenkins-scripts/blob/master/scriptler/deleteAllGlobalCredentials.groovy

以下代码有效。

import com.cloudbees.plugins.credentials.domains.Domain
def credentialsStore = jenkins.model.Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()
allCreds = credentialsStore.getCredentials(Domain.global())
//ID we intend on deleting
id_name ='test-id-name'
//here we cycle through all the credentials until we find the intended id
allCreds.each{
  //if we find the intended ID, delete it
  if (it.id == id_name){
    println ("Found ID")
    credentialsStore.removeCredentials(Domain.global(), it)
  }
}

如果有人认为这段代码可以更好地优化,我绝对愿意接受建议。

最新更新