我正在尝试使用.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,但实际上并没有删除。我没有收到错误。
答案 0 :(得分:0)
以以下代码为例: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)
}
}
如果有人认为可以更好地优化此代码,我肯定会提出建议。