Reload Jenkins Using a Script and the API

Ansible’s system module restarts the jenkins service. If you call this to restart during the install process or during the boot process you cause Jenkins to be unavailable. At one point (because of errant Nessus scan configs) the instances at boot were so loaded that the restart could take 4+ minutes. This caused a cascading effect and required tuning the cloud formation templates and ASG parameters to allow jenkins to be unavailable for a period of time. Not great.

It’s possible to use the jenkins api and the jenkins-cli.jar to reload without a restart of the entire service – a HUP, or the same process Jenkins does under the hood when you click in the Manage Jenkins -> Reload configuration from disk in the UI.

This does that reload:

#! /bin/bash

# script to use the jenkins-cli to reload the config from disk
#/etc/alternatives/java -jar /opt/jenkins-cli.jar -s http://localhost:8080 reload-configuration --username [username] --password `cat /home/ec2-user/.ssh/[your password file]`


if [[ -f /home/ec2-user/.ssh/[your password file] ]]; then
  /etc/alternatives/java -jar /opt/jenkins-cli.jar -s http://localhost:8080 reload-configuration --username [username] --password `cat /home/ec2-user/.ssh/[your password file]`
else
  # jenkins cli requires the base actual user password be available to restart jenkins
  if [[ `$VAULT read -field passwd secret/path/keys/jenkins/[your password file]` ]]; then
    echo "...successflly retrieved user actual password string from vault..."
    LOCALPASS=`$VAULT read -field passwd secret/path/keys/jenkins/[your password file]`
    /etc/alternatives/java -jar /opt/jenkins-cli.jar -s http://localhost:8080 reload-configuration --username [username] --password ${LOCALPASS}
  else
     echo "ERROR:: Failed to get passwd from vault: secret/path/keys/jenkins/[your password file], passwd field"
    echo "Exiting..."
  fi
fi

Replace

[username]
[your password file]

with the strings for a local user name ([username]), and for the file you drop onto the server from vault.

That retrieve of the file [your password file], should execute before this does. But if not and if the file turns out to be easy to get, the script will grab it on the fly and continue. It doesn’t retrieve credentials, or secure any secrets beyond the single one – if it works, great, if not, it fails and we figure it out…

— doug