A friend of mine asked me to try to attach Slave nodes to Jenkins Master. And Yes, it is straigthforward in jenkins, you just need to go to :
Manage Jenkins -> Manage Nodes -> Add Node
Some basic configuration and you’re DONE.
But the interesting part of this is, he wants these slaves to be docker containers. (This is Interesting =D ).
I don’t know if my method is the best way, but this is how I did it.
Make a new directory and put in these files, or grab them from here
So let’s start with the Dockerfile
:
FROM ubuntu:14.04
MAINTAINER ayoubensalem
RUN apt-get update && apt-get -y install git openssh-server curl software-properties-common
RUN apt-add-repository -y ppa:openjdk-r/ppa \
&& apt-get update \
&& apt-get install -y openjdk-8-jdk
RUN sed -i 's/PermitRootLogin\ without-password/PermitRootLogin\ no/' /etc/ssh/sshd_config
RUN mkdir -p /var/run/sshd
RUN mkdir /var/lib/jenkins
RUN useradd -m -d /var/lib/jenkins jenkins
RUN cd var/lib/jenkins && mkdir .ssh && chmod 700 .ssh && chown -R jenkins:jenkins .ssh
RUN sudo adduser jenkins sudo
RUN echo "jenkins ALL=NOPASSWD: ALL" >> /etc/sudoers
RUN echo "PasswordAuthentication no">> /etc/ssh/sshd_config
COPY ./run.sh /scripts/run.sh
RUN chmod 777 /scripts/run.sh
WORKDIR var/lib/jenkins
EXPOSE 22
ENTRYPOINT [ "/scripts/run.sh" ]
And the run.sh
script :
#!/bin/bash
export BASEDIR="var/lib/jenkins"
export USER_GROUP="jenkins:jenkins"
set_authorized_keys()
{
echo ${SSH_KEY} >> ${BASEDIR}/.ssh/authorized_keys
chmod 644 ${BASEDIR}/.ssh/authorized_keys
}
echo ${SSH_KEY}
set_authorized_keys
chown -R ${USER_GROUP} ${BASEDIR}
/usr/sbin/sshd -D
So let’s spin up some containers, and add them as nodes to jenkins master.
We need first to do a quick setup before launching the containers :
- Build the image from Dockerfile
- First Genereate an SSH KEY for Jenkins user
- Export Jenkins PUB KEY as an Environment variable
- Run the container and passing the PUB key as an Arguemnt
First let’s build the image :
$ docker build -t ayoubensalem/jdocker:latest .
then login as jenkins, and :
$ ssh-keygen -b 2048 -t rsa -f ~/.ssh/id_rsa -q -N ""
$ export JENKINS_PUB_KEY="$(cat ~/.ssh/id_rsa.pub)"
$ docker run -d -P -e SSH_KEY=$JENKINS_PUB_KEY ayoubensalem/jdocker:latest
After doing this steps, you should see some running docker containers :
$ docker ps
Now let’s grab the IPAdress of a running container :
$ docker inspect <CONTIAINER_ID> | jq -r ".[0].NetworkSettings.Networks.bridge.IPAddress"
Note : You may not have jq
installed. ( apt-get install jq )
And let’s try ssh to the container :
$ ssh jenkins@<CONTAINER_IP>
ET VOILA, we’re able to ssh to the container.
Now the last steps is to configure the new node like so :
