Chuan Chuan Law

DevOps | Software Automation | Continuous Integration

Category: Ansible

Jenkins – How To Automate Credentials Creation

Below is how to create a Jenkins new credentials of type Username & Password via Jenkins API using Ansible

– name: Automatically create Jenkins username & password credentials
body: |
“”: “0”,
“credentials”: {
“scope”: “GLOBAL”,
“id”: “abcdefg”,
“username”: “”,
“password”: “{{ testuser_password }}”,
“description”: “test jenkins credentials”,
“$class”: “com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl”
follow_redirects: all
force_basic_auth: true
method: POST
password: “{{ jenkins_admin_password }}”
return_content: true
url: “{{ jenkins_url }}/credentials/store/system/domain/_/createCredentials”
user: “admin”
validate_certs: false

Ansible: Install Different Versions Locally

If we want to use different versions of Ansible:

pip install virtualenv

virtualenv ansible194

ansible194/bin/pip install ansible==1.9.4

source ansible194/bin/activate

Ansible – How to fix Failed to import docker-py – No module named websocket. Try `pip install docker-py`

Set the path of Python site-packages in your playbook:

PYTHONPATH: “{{ lookup(‘env’,’PYTHONPATH’) }}:/Users/claw/Library/Python/2.7/lib/python/site-packages:/Users/claw/Library/Python/2.7/lib/python/site-packages”

How To Write Jenkinsfile

Jenkinsfile is another great feature from Jenkins2.

Below is an example of a Jenkinsfile:



   //Parameters of a Jenkins build  
text(defaultValue: ”, description: ‘URL’, name: ‘ARTIFACT’),
choice(choices: ‘qa’, description: ‘Deploy_Env’, name: ‘DEPLOY_ENV’),
string(defaultValue: ‘master’ , description: ‘ Branch’,name:’BRANCH’)

//Which node the job should run on


//Delete directory before job starts


//Git checkout certain branch using defined Git credentials

checkout([$class: ‘GitSCM’, branches: [[name: “${branch}”]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: ‘abc’, url: GIT_URL]]])

//Name of which stage of task that is running

//Credentials with secret file configured in Jenkins

withCredentials([file(credentialsId: ‘PASS’, variable: ‘FILE’)]) {

//Execute shell script

sh ‘ansible-galaxy install -r requirements.yml –force’

//Ansible command

playbook: ‘deploy.yml’,
inventory: ‘inventory/qa.inventory’,
artifact_url: “${ARTIFACT}”,
extras: ‘–diff –vault-password-file ${FILE} –tags ${ACTION}’,
colorized: true




Enter Jenkinsfile into Jenkins2 as below:

Screen Shot 2017-10-24 at 11.14.39 AM

References on Jenkinsfile

Screen Shot 2017-10-20 at 1.28.07 PM

© 2020 Chuan Chuan Law

Theme by Anders NorenUp ↑