Setting build args for dockerfile agent using a Jenkins declarative pipeline

前端 未结 5 1195
名媛妹妹
名媛妹妹 2020-12-31 00:56

I\'m using the declarative pipeline syntax to do some CI work inside a docker container.

I\'ve noticed that the Docker plugin for Jenkins runs a container using the

5条回答
  •  耶瑟儿~
    2020-12-31 01:35

    I believe we found a good way of dealing with this.

    We have a Jenkins deployment which runs as a docker instance, I've mapped a volume for /var/jenkins_home and added the .ssh folder to /var/jenkins_home/.ssh

    We also run all builds inside docker containers, using the dockerfile agent directive. Sometimes we need to access some of our private composer libraries via git over ssh.

    We leverage docker image caching by installing project deps (composer) which means we only rebuild the build containers if our deps change. This means we need to inject an SSH key during docker build.

    See these example files:

    project/Jenkinsfile

    def SSH_KEY
    
    node {
      SSH_KEY = sh(returnStdout: true, script: 'cat /var/jenkins_home/.ssh/id_rsa')
    }
    
    pipeline {
      agent {
        dockerfile {
          filename 'Dockerfile'
          additionalBuildArgs '--build-arg SSH_KEY="' + SSH_KEY + '"'
          reuseNode true
        }
      }
      stages {
        stage('Fetch Deps') {
          steps {
            sh 'mv /home/user/app/vendor vendor'
          }
        }
        stage('Run Unit Tests') {
          steps {
            sh './vendor/bin/phpunit'
          }
        }
      }
    }
    

    project/Dockerfile

    FROM mycompany/php7.2-common:1.0.2
    
    # Provides the image for building mycompany/project on Jenkins.
    
    WORKDIR /home/user/app
    
    ARG SSH_KEY # should receive a raw SSH private key during build.
    ADD composer.json .
    RUN add-ssh-key "${SSH_KEY}" ~/.ssh/id_rsa && \
        composer install && \
        remove-ssh-keys
    
    # Note: add-ssh-key and remove-ssh-keys are our shell scripts put in
    # the base image to reduce boilerplate for common tasks.
    

提交回复
热议问题