Configure Jenkins 2.0 with Ansible

PumpkinSeed picture PumpkinSeed · Apr 13, 2016 · Viewed 9.3k times · Source

I am using Ansible for provision our servers, I installed the Jenkins 2.0 but it is becomeing with a startup configuration when I open the web UI. How can I do it with Ansible or shell or jenkins-cli. CentOS 7, Ansible 2.0.1.0. So,

  1. Installing Jenkins 2.0 from http://pkg.jenkins-ci.org/redhat-rc/jenkins-2.0-1.1.noarch.rpm rpm.
  2. Install java with yum.
  3. Service start jenkins.
  4. Open 192.168.46.10:8080, which is opening the Jenkins.
  5. In Web UI adding the initial admin password.
  6. In web UI select and install plugins.
  7. In web UI create a new admin user.

The 5,6,7 points are all the startup config of the new Jenkins. I haven't idea how we can install it autmatically.

Edit 1:

The 1,2,3 point is already done, just I didn't share because it is not necessary, because I only need an advice how can I configure the Jenkins. But now I add it to my question.

---
- name: Jenkins - install | Install java
  yum: name=java state=installed

- name: Jenkins - install | Install Jenkins 2.0
  yum: pkg=http://pkg.jenkins-ci.org/redhat-rc/jenkins-2.0-1.1.noarch.rpm state=installed

- name: Jenkins - install | Start and enable Jenkins 2.0
  service: name=jenkins state=started enabled=yes

Answer

Anton Pelykh picture Anton Pelykh · Dec 12, 2016

You can create an initialization script (in groovy) to add an admin account. Script should be present in $JENKINS_HOME/init.groovy.d/*.groovy. See Jenkins CI Wiki for more details.

Here's an example.

security.groovy.j2 file:

#!groovy
import java.util.logging.Level
import java.util.logging.Logger
import hudson.security.*
import jenkins.model.*

def instance = Jenkins.getInstance()
def logger = Logger.getLogger(Jenkins.class.getName())

logger.log(Level.INFO, "Ensuring that local user '{{ jenkins.admin_username }}' is created.")

if (!instance.isUseSecurity()) {
    logger.log(Level.INFO, "Creating local admin user '{{ jenkins.admin_username }}'.")

    def strategy = new FullControlOnceLoggedInAuthorizationStrategy()
    strategy.setAllowAnonymousRead(false)

    def hudsonRealm = new HudsonPrivateSecurityRealm(false)
    hudsonRealm.createAccount("{{ jenkins.admin_username }}", "{{ jenkins.admin_password }}")

    instance.setSecurityRealm(hudsonRealm)
    instance.setAuthorizationStrategy(strategy)
    instance.save()
}

How to use in Ansible playbook:

- name: Create initialization scripts directory
  file: path={{ jenkins.home }}/init.groovy.d
        state=directory
        owner=jenkins
        group=jenkins
        mode=0775

- name: Add initialization script to setup basic security
  template: src=security.groovy.j2
            dest={{ jenkins.home }}/init.groovy.d/security.groovy

I was inspired by this GitHub reposiotry.