Use password parameter in Jenkins as Secret in Pipeline - jenkins

I have a Jenkins pipeline job that needs to provide the username and password to checkout from RTC as parameters.
The checkout action can use a userId and password variable, but the Password must be of the class "Secret".
When trying to create a secret using hudson.util.Secret secret = hudson.util.Secret.fromString("${Build_Password}"), I get the following error:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod hudson.util.Secret fromString java.lang.String
Is there a way to create a Secret or Credential from parameters?

I had to disable the groovy sandbox. After that, I was able to use the Secret class:
hudson.util.Secret secret = hudson.util.Secret.fromString(Build_Password)

checkout([$class: 'TeamFoundationServerScm', localPath: 'D:\Build-Code-Scm', projectPath: '$/RootDirectory/SubFolder', serverUrl: 'http://TEST.TEST.com:8080/TEST/TEST', useOverwrite: true, useUpdate: true, userName: 'UNMAME', password: hudson.util.Secret.fromString('PASSWORD'), workspaceName: 'Hudson-${JOB_NAME}-${NODE_NAME}'])

Related

what can I do on Jenkinsfile to get credentials?

I'm new to jenkins and I'm creating a jenkinsfile with a declarative pipeline that supports different parameters. I also need to access to a credential stored in Jenkins, that I created already. How can I access to this credentials though jenkinsfile? do I need to call them inside of the stage or like this is ok? I got very confused in this part :S
I saw something like this on internet:
steps {
withCredentials([usernamePassword(credentialsId: 'x'....
}
Until now I have this:
pipeline {
agent any
environment{
my_credentials = credentials('x-credentials-id')
}
stages{
stage('Setup parameters') {
steps {
parameters([
string(name: 'a', defaultValue: 'x', description: 'test'),
text(name: 'b', defaultValue: ''),
text(name: 'b2', defaultValue: ''),
text(name: 'c', defaultValue: ''),
text(name: 'c2', defaultValue: '')
])
//])
}
}
}
}
From Jenkins documentation.
Jenkins' declarative Pipeline syntax has the credentials() helper
method (used within the environment directive) which supports secret
text, username and password, as well as secret file credentials.
So basically credentials('x-credentials-id') will support the aforementioned credential types and you should be using this helper method within an Environment block. You can use this approach if you want to declare your credentials globally so they can be used anywhere in the pipeline.
example
environment {
AWS_ACCESS_KEY_ID = credentials('jenkins-aws-secret-key-id')
AWS_SECRET_ACCESS_KEY = credentials('jenkins-aws-secret-access-key')
}
For other types, you can use withCredentials directive.(This is coming from Credentials Binding plugin) Both will get the Job done.
withCredentials(bindings: [certificate(credentialsId: 'jenkins-certificate-for-xyz', \
keystoreVariable: 'CERTIFICATE_FOR_XYZ', \
passwordVariable: 'XYZ-CERTIFICATE-PASSWORD')]) {
//
}
Although it says secrettext, username and password etc are not supported with Bind Credentials plugin, you can use WithCredentials for those types as well.
withCredentials([usernamePassword(credentialsId: 'amazon', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
echo "username is $USERNAME"
}
Read more from here and here

Retrieving secrets from HashiCorp Vault in jenkins pipeline using HashiCorp Vault Plugin

I have setup a connection between my Jenkins and Vault and by using "withVault" method
https://www.jenkins.io/doc/pipeline/steps/hashicorp-vault-plugin/#hashicorp-vault-plugin
I am retrieving vault secrets from Vault in my jenkins pipeline. Secret is stored in the environment variable github_token, which is then used to form URL for accessing git in the pipeline. Retrieving secrets works, the problem is, that $github_token variable contains asterisks.
I need it to contain actual value of the the token
def secrets = [
[path: 'ddci/data/test', engineVersion: 2, secretValues: [
[envVar: 'github_token', vaultKey: 'token']
]]
]
def configuration = [vaultUrl: 'https://vault.tools.sap/',
vaultNamespace: 's4',
vaultCredentialId: 'hashicorp_vault',
skipSslVerification: true,
engineVersion: 2]
pipeline {
agent any
stages{
stage('use token to authenticate GITHub') {
steps {
withVault([configuration: configuration, vaultSecrets: secrets]) {
sh 'git_url= https://username:${github_token}#github.tools.sap/AZURE-PIPELINES-SYSDEV/decdev-ci-verification'
git url: '$git_url', branch: 'master'
}
}
}
}
}
The $github_token variable doesn't contain asterisks, Jenkins displays any Vault secret using asterisks on console, to protect the real value.
if you want to check the $github_token value, write it to a file in the workspace, doing something like this:
echo $github_token > token.txt
Some other problem is preventing you to access the GitHub server (Is the token correct? Is the path correct? Has the Jenkins node access to the GitHub?). Log to the Jenkins node and try to execute the same command manually.

Jenkins credentials - how to pass into Fastlane?

I have a secret file in Jenkins Credentials. And I am trying to use it as an environment variable to use later in Fastlane script. But inside the Fastlane script I am getting only ****. How can I get the secret key in Fastlane from Jenkins?
Piece of Jenkins Groovy file:
pipeline {
agent any
environment {
APP_STORE_KEY = credentials('ASC_KEY')
#...
}
#...
stage('Upload to TestFlight') {
steps {
sh "bundle exec fastlane deploy --env $APP_ENV"
}
}
}
Piece of Fastfile:
lane :deploy do
api_key = app_store_connect_api_key(
key_id: ENV['ASCAPI_KEY_ID'],
issuer_id: ENV['ASCAPI_ISSUER_ID'],
key_content: ENV['APP_STORE_KEY']
)
pilot(
username: ENV['APPLE_ID'],
app_identifier: ENV['APP_BUNDLE_IDENTIFIER'],
dev_portal_team_id: ENV['TEAM_ID'],
team_id: ENV['TEAM_ID'],
api_key: api_key,
app_platform: "ios",
ipa: ENV['OUTPUT_IPA_NAME'],
skip_waiting_for_build_processing: true
)
end
I've tried to print APP_STORE_KEY with puts(ENV['APP_STORE_KEY']) in Fastfile and it returns ****.
Maybe you know some workaround or a better way to do this.
I've managed it to work. it works perfectly with the base64 encoded content of .p8 file.
First of all we need to get base64 encoded string from .p8 file. and copy the result. Then in Jenkins Credentials create a credential with type of Secret text and paste base64 encoded string.
cat AuthKey_12345ABCD.p8 | base64
LS0tCk1...5cUdTTTQ #It's a result of encoding, copy it.
In Fastfile add is_key_content_base64 parameter to app_store_connect_api_key. And remove username parameter from pilot (it will cause conflict with the api_key parameter).
api_key = app_store_connect_api_key(
key_id: ENV['ASCAPI_KEY_ID'],
issuer_id: ENV['ASCAPI_ISSUER_ID'],
key_content: ENV['APP_STORE_KEY']
is_key_content_base64: true #Add this parameter ++++++++++++
)
pilot(
#username: ENV['APPLE_ID'], #Remove this row ------------
app_identifier: ENV['APP_BUNDLE_IDENTIFIER'],
.....
Did not make a deep test with other types of secrets but works great with the above solution.

How to use jenkins plugin for username with password in dsl?

I'm new to jenkins and I'm trying to use the credentials in a dsl using the credentials plugin
template.xml
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
<scope>GLOBAL</scope>
<id>PROD</id>
<description>prod credentials</description>
<username>prod</username>
<password>{{ encrypted_password_prod }}</password
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
I have defined the credentials in jenkins as username with password . the above encrypted value is saved in ansible.
My question is how should i call them in my dsl
Map credentials = [:]
credentialsBinding {
credentials.each { key, value ->
string("${key}", "${value}")
}
.credentials(["TF_VAR_username": "PROD" ,"TF_VAR_password" : "password_prod"])
Error:
22:11:16 FATAL: Credentials 'PROD' is of type 'Username with password'
where 'org.jenkinsci.plugins.plaincredentials.StringCredentials' was
expected
You can put credentials in Jenkins keystore (Jenkins -> Credentials -> System -> Global credentials -> Add Credentials), and then refer to them in your pipeline using withCredentials block like this:
node {
withCredentials([usernameColonPassword(credentialsId: 'mylogin', variable: 'USERPASS')]) {
sh '''
set +x
curl -u "$USERPASS" https://private.server/ > output
'''
}
}
More info here: https://jenkins.io/doc/pipeline/steps/credentials-binding/

How to programmatically set Authentication Token in Jenkins groovy script?

I'm looking to set the Authentication Token in groovy similar to how I setup other options for the build:
properties([[$class: 'BuildConfigProjectProperty'],
buildDiscarder(logRotator(numToKeepStr: '25')),
parameters([
password(name: 'aws_access_key', defaultValue: 'AWS Access Key', description: 'Enter AWS Access Key ID'),
])])
The field I wish to set (from the UI):
Picture of UI
How does one set this field?

Resources