Skip to content

Instantly share code, notes, and snippets.

@mkutz
Last active Aug 11, 2022
Embed
What would you like to do?
Configure a secret text credential in Jenkins using a post-initialization script (https://wiki.jenkins.io/display/JENKINS/Post-initialization+script)
import static com.cloudbees.plugins.credentials.CredentialsScope.GLOBAL
import com.cloudbees.plugins.credentials.domains.Domain
import com.cloudbees.plugins.credentials.SystemCredentialsProvider
import hudson.util.Secret
import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;
import com.cloudbees.plugins.credentials.CredentialsStore
/*
* Add a credentials
*/
CredentialsStore credentialsStore = SystemCredentialsProvider.getInstance().getStore()
StringCredentialsImpl secretTextCredentials = new StringCredentialsImpl(
GLOBAL,
"my-secret-text-crendentials-id",
"Secret Text for something",
Secret.fromString("S3cr3t")
)
credentialsStore.addCredentials(Domain.global(), secretTextCredentials)
UsernamePasswordCredentialsImpl userNamePasswordCredentials = new UsernamePasswordCredentialsImpl(
GLOBAL,
"my-username-password-crendentials-id",
"Username and password for something",
"my-user-name",
"4l50S3cr3t"
)
credentialsStore.addCredentials(Domain.global(), userNamePasswordCredentials)
pipeline {
agent any
environment {
SECRET_TEXT = credentials("my-secret-text-crendentials-id")
USERNAME_PASSWORD = credentials("my-username-password-crendentials-id")
}
stages {
stage("Don't tell secrets") {
steps {
echo "My secret text is ${env.SECRET_TEXT}" // My secret text is *****
echo "My username is ${env.USERNAME_PASSWORD_USR}" // My username is ****
echo "My password is ${env.USERNAME_PASSWORD_PSW}" // My password is ****
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment