Last active
June 9, 2021 12:17
-
-
Save ismet55555/01352adb3bc30bfabab5e1ec3d89f840 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
############################################################################## | |
# | |
# Usage: | |
# 1. Hardcode parameters and run the script | |
# 2. Pass parameters into script. | |
# Example: ./jenkins-generate-api-token.sh https://localhost:8080 test-token myid mypassword | |
# | |
# NOTE: For security purposes, maybe better to pass password with environmental variable | |
# | |
############################################################################## | |
set -e | |
# Assign default values if parameters are not passed into script | |
PASSWORD=${1:-'<DEFAULT PASSWORD>'} | |
USERNAME=${2:-'<DEFAULT USERNAME>'} | |
JENKINS_SERVER_URL=${3:-"<DEFAULT SERVER URL>"} | |
NEW_TOKEN_NAME=${4:-"my-new-generated-api-token"} # No spaces | |
# Creating the cookie crumb to Jeknins server | |
echo "Generating server cookie ..." | |
CRUMB=$(curl ${JENKINS_SERVER_URL}/crumbIssuer/api/xml?xpath=concat\(//crumbRequestField,%22:%22,//crumb\) \ | |
--silent \ | |
--cookie-jar temp_cookie_file \ | |
--user "${USERNAME}:${PASSWORD}" ) | |
echo "Cookie: ${CRUMB}" | |
# Make the request to generate the API token (uses jq package) | |
echo "Generating API token ..." | |
TOKEN_VALUE=$(curl -X POST ${JENKINS_SERVER_URL}/me/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken/api/json?newTokenName="${NEW_TOKEN_NAME}&tree=data[tokenValue]" \ | |
--silent \ | |
--header ${CRUMB} \ | |
--cookie temp_cookie_file \ | |
--user "${USERNAME}:${PASSWORD}" \ | |
| jq -r '.data.tokenValue') | |
echo "API Token Value: ${TOKEN_VALUE}" | |
# Remove the cookie crumb file | |
echo "Removing temporary cookie file ..." | |
rm -f temp_cookie_file | |
echo "Done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment