如何使用groovy存储秘密文本或文件

时间:2015-11-09 16:38:48

标签: groovy jenkins

我已经找到了如何使用基于groovy的Jenkins存储用户名/密码或SSH用户名/私钥。

https://gist.github.com/iocanel/9de5c976cc0bd5011653

domain = Domain.global()
store = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()

priveteKey = new BasicSSHUserPrivateKey(
CredentialsScope.GLOBAL,
"jenkins-slave-key",
"root",
new BasicSSHUserPrivateKey.UsersPrivateKeySource(),
"",
""
)

usernameAndPassword = new UsernamePasswordCredentialsImpl(
CredentialsScope.GLOBAL,
"jenkins-slave-password", "Jenkis Slave with Password Configuration",
"root",
"jenkins"
)

store.addCredentials(domain, priveteKey)
store.addCredentials(domain, usernameAndPassword)

可以存储更多种类的凭据。我该怎么做:

  • 秘密文件
  • 秘密文字

2 个答案:

答案 0 :(得分:3)

经过一番研究,我发现plain-credentials插件实现了Secret Text和Secret File凭证。我在上面提出了要点,并为这两种类型添加了代码(请参阅reqwuired导入的要点)。

https://gist.github.com/chrisvire/383a2c7b7cfb3f55df6a

secretText = new StringCredentialsImpl(
CredentialsScope.GLOBAL,
"secret-text",
"Secret Text Description",
Secret.fromString("some secret text goes here"))

file = new File("/path/to/some/file")
noFileItem = [ getName: { return "" } ] as FileItem
FileCredentailsImpl can take a file from a do
secretFile = new FileCredentialsImpl(
CredentialsScope.GLOBAL,
"secret-file",
"Secret File Description"
noFileItem, // Don't use FileItem
file.getName(),
file.text)

store.addCredentials(domain, secretText)
store.addCredentials(domain, secretFile)

答案 1 :(得分:1)

使用另一个FileCredentialsImpl构造函数实现:

setlocal /?
import com.cloudbees.plugins.credentials.*;
import com.cloudbees.plugins.credentials.domains.Domain;
import org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl;

def secret = '''Hi
there,
only
test'''

def secretBytes = SecretBytes.fromBytes(secret.getBytes())
def credentials = new FileCredentialsImpl(CredentialsScope.GLOBAL, 'my test file', 'description', 'file.txt', secretBytes)

SystemCredentialsProvider.instance.store.addCredentials(Domain.global(), credentials)