Skip to content

Instantly share code, notes, and snippets.

@ThabetAmer
Last active April 8, 2020 07:29
Show Gist options
  • Save ThabetAmer/bb4843f7e95b1e218e79ab2595d9ee18 to your computer and use it in GitHub Desktop.
Save ThabetAmer/bb4843f7e95b1e218e79ab2595d9ee18 to your computer and use it in GitHub Desktop.
Creates Jenkins credentials with username and password, made for Harbor Robot Accounts, but can be used for any username/password json file
#!/bin/bash
# Creates Jenkins credentials with username and password,
# made for Harbor Robot Accounts, but can be used for any username/password json file
# @author [email protected]
# @since Jenkins 2.222.1
# @params json file with {"name":"","token":""} tags
# @output Jenkins credential with ID name "harbor-NAME"
[ -f "$1" ] || exit 1
# Jenkins login info - please fill accordingly
JENKINS_URL=''
JENKINS_USR=''
JENKINS_PSW=''
JENKINS_JAR='~/jenkins-cli.jar'
# parsed credential details
CRED_FILE=$1
CRED_USR=`cat $CRED_FILE | jq -r '.name'`
CRED_PSW=`cat $CRED_FILE | jq -r '.token'`
CRED_NAME=harbor-`echo $USR | cut -d$ -f2`
# temp file with xml format for Jenkins plugin [email protected]
OUT_FILE=`basename $CRED_FILE | cut -d. -f1`-cred.xml
# creates the xml file
cat > /tmp/$OUT_FILE << EOL
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl plugin="[email protected]">
<scope>GLOBAL</scope>
<id>$CRED_NAME</id>
<description>$CRED_NAME</description>
<username>$CRED_USR</username>
<password>$CRED_PSW</password>
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
EOL
# Applies for Jenkins, within the Global domain
cat /tmp/$OUT_FILE | java -jar $JENKINS_JAR -s $JENKINS_URL -auth $JENKINS_USR:$JENKINS_PSW create-credentials-by-xml system::system::jenkins _
rm /tmp/$OUT_FILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment