Simplest Enterprise Continuous Integration Solutions

Saturday, December 13, 2014

Docker: Practice with Jenkins, Salt

Automate generate Dockerfile within Jenkins pipeline job


# generate Dockerfile
/bin/rm -rf ${WORKSPACE}/docker
/bin/mkdir -p ${WORKSPACE}/docker

cd ${WORKSPACE}/docker
touch Dockerfile

cat <<EOF > Dockerfile
# set the base image to Centos
FROM centos:6.7

# File Author / Maintainer
MAINTAINER buildmaster <buildmaster@qxc.com>

RUN rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm

RUN yum install -y salt salt-minion

# udpate salt file_roots, and pillar_roots
RUN echo 'file_roots:' >> /etc/salt/minion
RUN echo '  base:' >> /etc/salt/minion
RUN echo '    - /srv/salt' >> /etc/salt/minion
RUN echo '    - /srv/formulas' >> /etc/salt/minion
RUN echo '  dev:' >> /etc/salt/minion
RUN echo '    - /srv/salt' >> /etc/salt/minion
RUN echo '    - /srv/formulas' >> /etc/salt/minion
RUN echo 'pillar_roots:' >> /etc/salt/minion
RUN echo '  base:' >> /etc/salt/minion
RUN echo '    - /srv/pillar' >> /etc/salt/minion
RUN echo '  dev:' >> /etc/salt/minion
RUN echo '    - /srv/pillar/qa' >> /etc/salt/minion

# use local file_client
RUN echo 'file_client: local' >> /etc/salt/minion

# define Salt role
RUN salt-call grains.setval roles "[${MY_ROLE}]"
EOF

Build docker image, consume with docker container

# build a docker image from Dockerfile
cd ${WORKSPACE}/docker

docker build -t ${DOCKER_IMAGE}.v${PIPELINE_VERSION} .

# add host directory as a data volume (which only works with at least centos6.7)
# invoke salt-call with docker container 
docker run –v salt_scripts:/srv/rw -t ${DOCKER_IMAGE}.v${PIPELINE_VERSION} salt-call --local pillar.items | /usr/bin/tee ${OUTPUT}

# handle return code and clean up successful docker container
CHECK_SH=${WORKSPACE}/${PIPELINE_VERSION}.`date "+%Y%m%d%M%S"`.sh
/bin/echo "#!/bin.sh" > ${CHECK_SH}
/bin/echo "RET_CODE=0" >> ${CHECK_SH}
/bin/echo "/bin/grep -n -i error ${OUTPUT} > ${OUTPUT}.tmp" >> ${CHECK_SH}
/bin/echo "if [ ! -s ${OUTPUT}.tmp ]; then" >> ${CHECK_SH}
/bin/echo "   docker rmi -f ${DOCKER_IMAGE}.v${PIPELINE_VERSION}" >> ${CHECK_SH}
/bin/echo "else" >> ${CHECK_SH}
/bin/echo "   RET_CODE=1" >> ${CHECK_SH}
/bin/echo "fi" >> ${CHECK_SH}
/bin/echo "exit ${RET_CODE}" >> ${CHECK_SH}

/bin/sh ${CHECK_SH}