Skip to content

Instantly share code, notes, and snippets.

@mkutz
Last active August 11, 2022 10:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mkutz/6de3233f5ff40ad9e453bc107069bd23 to your computer and use it in GitHub Desktop.
Save mkutz/6de3233f5ff40ad9e453bc107069bd23 to your computer and use it in GitHub Desktop.
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