Jenkins CLI 사용 시 쉘 스크립트 파일 및 XML을 사용해서 Credential 설정을 해보는 것을 설명하려고 한다.
Credential 종류는 여러가지가 있지만 내가 사용하고 있거나 사용할 것을 위주로 먼저 정리해보았다.
1. Username with password
2. Google Service Account from private key
3. Secret text
4. Secret file
5. AWS Credential
6. SSH Username with private key
6가지 중 값만 다르고 형식은 비슷하기 때문에 1. Username with password 를 기준으로 설명해보려고 한다.
XML 파일을 생성하여 반영하는 방식인데 생성 후 XML 파일을 암호화 하는 방식으로 구성하였다.
Jenkins CLI를 사용하기 위해 사용자정보를 입력받고 Username with password Credential을 저장하기 위한 5가지 변수를 입력받는다.
입력 받은 변수들을 통해 XML 파일을 생성하고 그 정보로 Jenkins CLI로 반영해준다.
이후 파일을 .enc 파일로 생성 후 암호화 알고리즘을 사용하여 파일을 암호화 처리 후 기존 xml 파일을 삭제하여 Credential 에 대한 정보를 암호화 처리하여 보관할 수 있도록 설정하였다.
create_credential_user.sh
#!/bin/bash
# 사용자 입력 받기
read -p "Jenkins 계정 입력 :" Jenkins_USER
read -sp "Jenkins 패스워드 입력 :" Jenkins_PW
echo
read -p "Enter scope: " scope
read -p "Enter id: " id
read -p "Enter description: " description
read -p "Enter username: " username
read -sp "Enter password: " password
echo
CLI_JAR=jenkins-cli.jar
# XML 파일 생성
xml_file="user_${username}_credential.xml"
cat <<EOF > $xml_file
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
<scope>$scope</scope>
<id>$id</id>
<description>$description</description>
<username>$username</username>
<password>$password</password>
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
EOF
java -jar $CLI_JAR -s $JENKINS_URL -auth $Jenkins_USER:$Jenkins_PW create-credentials-by-xml system::system::jenkins _ < $xml_file
# 암호화할 파일 경로와 암호화된 파일 저장 경로
encrypted_file="${xml_file}.enc"
# 암호화에 사용할 비밀번호 입력 받기
read -sp "Enter encryption password: " enc_password
echo
# 파일 암호화 (AES-256-CBC 알고리즘 사용)
openssl enc -aes-256-cbc -salt -in "$xml_file" -out "./encrypted_file/user/$encrypted_file" -pass pass:"$enc_password"
# 암호화된 파일 확인
if [ $? -eq 0 ]; then
echo "File has been encrypted successfully: $encrypted_file"
else
echo "File encryption failed"
fi
# 원본 XML 삭제
rm $xml_file
쉘 스크립트 실행 결과
해당 정보를 입력 후 Enter encryption password를 입력하게 하여 xml.enc 파일을 보안처리하였다.
생성된 파일 위치에 보면 xml.enc 파일이 생성되어 있고 파일을 열었을 시 암호화되어 보이지 않게 된다.
Jenkins 콘솔에서 생성 정보 확인