1

I'm preparing a project with Jenkins in Docker container.

After a lot of research, I don't find any solution how to add new Jenkins user with Ansible or cURL. There are some suggestions (https://linuxacademy.com/community/show/5636-how-to-secure-and-create-users-in-jenkins-using-ansible-playbooks/) but it was not usable at all in Jenkins container

So I bit reverse engineering (check request in Chrome, do a trace) I figure out that it can be done with Ansible uri module, same like adding new credentials (https://getintodevops.com/blog/how-to-add-jenkins-credentials-with-curl-or-ansible)

Here is the result code. Since it is during initial setup, it requires default admin token.

path_to_jenkins-home_at_docker_host is directory at Docker host which will be mounted as Jenkins home in container (-v /path_to_jenkins-home_at_docker_host:/var/jenkins_home)

with cURL:

USERNAME="admin"
PASSTOKEN="[content_of_/path_to_jenkins-home_at_docker_host/secrets/initialAdminPassword]"
SERVER="[jenkins_host]"
SRVPORT="8088"
COOKIEJAR=$(mktemp)
AUTH=${USERNAME}:${PASSTOKEN}
APIADDR=${SERVER}:${SRVPORT}
CRUMB=$(curl -u "${AUTH}" --cookie-jar "$COOKIEJAR" "http://${APIADDR}/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,%22:%22,//crumb)")

curl -v -u "${AUTH}" --cookie "$COOKIEJAR" -H "$CRUMB" "http://${APIADDR}"/securityRealm/createAccountByAdmin \
--data 'username=user2&password1=pass&password2=pass&fullname=fullname&email=bubba%40dummy.bg'

with Ansible:

- name: JENKINS-PASSTOKEN | Get initial authentication token
  shell: 'cat /path_to_jenkins-home_at_docker_host/secrets/initialAdminPassword'
  register: admin_auth_token

- name: JENKINS-CTEDENTIALS | Create CRUMB authentication request
  uri:
    url: 'http://localhost:{{ jenkins_port }}/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)'
    user: admin
    password: '{{ admin_auth_token.stdout }}'
    force_basic_auth: yes
    return_content: yes
  register: crumb

- name: JENKINS-CTEDENTIALS | Add Jenkins administration account
  uri:
    method: POST
    url: 'http://localhost:{{ jenkins_port }}/securityRealm/createAccountByAdmin'
    user: admin
    password: '{{ admin_auth_token.stdout }}'
    force_basic_auth: yes
    follow_redirects: all
    headers:
      Jenkins-Crumb: '{{ crumb.content.split(":")[1] }}'
      Cookie: '{{ crumb.set_cookie }}'
    # body: 'username=user2&password1=pass&password2=pass&fullname=fullname&email=bubba%40dummy.bg'
    body: 'username={{ jenkins_user }}&password1={{ jenkins_pass }}&password2={{ jenkins_pass }}&fullname={{ jenkins_fullname }}&email={{ jenkins_email }}'
ptsonkov
  • 11
  • 3

0 Answers0