====== Jenkins ====== ===== Básico ===== Puedes crear distintas tareas de Jenkins. Los más útiles a día de hoy: * Pipeline: Un archivo de código en Groovy para definir una serie de pasos. * Freestyle project: Para añadir más configuración. * Pipeline multibranch: Cuando quieres hacer una pipeline por cada branch del proyecto. La más fácil para mi hasta ahora es la pipeline pero escogiendo la opción "Pipeline script from SCM" que obtiene el Jenkinsfile de un SCM (SCM = gestor de código tipo Git). Para crear un pipeline necesitarás un Jenkinsfile, para desarrollarlo tienes los siguientes consejos: * Usa el editor "pipeline sintax" para configurar un paso y obtener la línea de código que lo lanzaría. * Usa la extensión de visual studio code "Jenkins runner" para editar un jenkinsfile y lanzarlo localmente. * Accediendo a la página de un build encontrarás un botón "reply" este te permite relanzar el build pero editando el código del jenkinsfile que se usa. Así puedes ir debugando fácilmente. Existen plugins para Docker y para Docker Compose. Para el segundo, por ejemplo, puedes definir un step en el pipeline sintax definiendo un ''stage: General build step'' y ''Docker-compose build step''. Con esto podrás parar y detener contenedores y ejecutar comandos en estos. Pero antes tendrás que dar acceso a jenkins a docker, para ello haz los siguientes mapeos si los corres con docker: ports: - "8080:8080" - "50000:50000" volumes: - jenkins_vol:/var/jenkins_home - /home/alfred/PycharmProjects/WgfSeleniumTests:/home:ro - /var/run/docker.sock:/var/run/docker.sock - /usr/bin/docker:/usr/bin/docker ===== Jenkinsfiles ===== ==== Basic one ==== pipeline { agent any stages { stage ('Initialize') { steps { echo 'Place' echo 'holder' } } } } === Correr una pipeline en contenedor === Simplemente has de seleccionar el agente docker: pipeline { agent { docker { image 'node:14-alpine' } } stages { stage('Test') { steps { sh 'node --version' } } } } === Correr pipeline en varios contenedores === pipeline { agent none stages { stage('Back-end') { agent { docker { image 'maven:3-alpine' } } steps { sh 'mvn --version' } } stage('Front-end') { agent { docker { image 'node:14-alpine' } } steps { sh 'node --version' } } } } === Los últimos pasos con post === pipeline { agent any stages { stage('Test') { steps { sh 'echo "Fail!"; exit 1' } } } post { always { echo '[*] This will always run' } success { echo '[*] This will run only if successful' } failure { echo '[*] This will run only if failed' } unstable { echo '[*] This will run only if the run was marked as unstable' } changed { echo '[*] This will run only if the state of the Pipeline has changed' echo '[*] For example, if the Pipeline was previously failing but is now successful' } } } ==== Útiles ==== * https://www.jenkins.io/doc/book/pipeline/jenkinsfile/ * https://www.jenkins.io/doc/book/pipeline/syntax/ * ''checkout scm'' para obtener el código del SCM. * ''sh'' para ejecutar un comando shell. * ''sleep'' para dormir unos segundos. * ''echo'' para escribir. === Definir variables === def docker_registry = 'https://118864902010.dkr.ecr.us-east-1.amazonaws.com'; === String format === def docker_registry = 'https://118864902010.dkr.ecr.us-east-1.amazonaws.com'; def docker_registry_credential = 'ecr:us-east-1:AWSJenkins'; pipeline { agent any environment { PYPI_CREDS = credentials('pip_jenkins') } stages { stage('Clone') { steps { echo docker_registry echo "a: ${docker_registry}" // Importarte las dobles comillas } } } } === Definir funciones === ... post { failure { notifyBuild(currentBuild.result); } } ... def notifyBuild(String buildStatus = 'STARTED') { // build status of null means successful buildStatus = buildStatus ?: 'SUCCESSFUL' // Default values def recipientProviders = [[$class: 'DevelopersRecipientProvider']] def colorName = 'RED' def colorCode = '#FF0000' def subject = "${buildStatus}: ${env.JOB_NAME} #${env.BUILD_NUMBER}" def summary = "${subject} (${env.BUILD_URL})" def details = """

STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':

Check console output at "${env.JOB_NAME} [${env.BUILD_NUMBER}]"

""" // Override default values based on build status if (buildStatus == 'STARTED') { color = 'YELLOW' colorCode = '#FFFF00' } else if (buildStatus == 'SUCCESSFUL') { color = 'GREEN' colorCode = '#00FF00' } else { color = 'RED' colorCode = '#FF0000' recipientProviders = [[$class: 'CulpritsRecipientProvider'], [$class: 'RequesterRecipientProvider']] } // Send notifications slackSend(color: colorCode, message: summary) emailext( subject: "[Jenkins] ${subject}", mimeType: 'text/html', body: '''${JELLY_SCRIPT,template="html"}''', recipientProviders: recipientProviders ) }
===== Gotchas ===== ==== Jenkins runner ==== There is a Visual Studio Code extension called Jenkins runner: https://marketplace.visualstudio.com/items?itemName=dave-hagedorn.jenkins-runner Thanks to that extension we will be able to directly run local code into a Jenkins task. However, you will need to previously configure the extension. For that, lets imagine an existent Jenkins pipeline called `testpipeline`. You would open your Visual Studio Code settings file and add the next configuration: "jenkins-runner.hostConfigs": { "local": { "url": "http://127.0.0.1:8080", "user": "your-jenkins-user", "password": "your-password" } }, "jenkins-runner.jobs": { "job-testpipeline": { "isDefault": true, "runWith": "local", "name": "testpipeline", }, } Locally you would create a Jenkinsfile like this example: pipeline { agent any stages { stage ('Initialize') { steps { echo 'Hello Jenkins!' } } } } If we do ''ctrl+shift+p'' there will appear a menu where we can select ''Jenkins runner: Run pipeline script on a default job''. Doing that you should see what Jenkins says in the same Visual Studio Code output window. ==== Notas ==== * Si Jenkins a de obtener el código de un repositorio local suyo usa: file:///''