【问题标题】:How to make my project deploy automatically from dev to staging and manually to production in Jenkins using only a master git branch如何仅使用主 git 分支在 Jenkins 中使我的项目自动从开发部署到登台并手动部署到生产
【发布时间】:2019-09-22 10:04:34
【问题描述】:

我有大约 30 个 Wordpress 网站,因此配置 Jenkins 的方式是我为每个网站都有一份工作。开发过程如下(我不知道它是否是最优的,但我们就是这样):

  1. 由于我们有外包开发人员,他们在自己的存储库托管提供商中托管了自己的存储库。每当代码准备好进行 QA 时,他们就会将所有更改提交到我们在主分支中的存储库。
  2. 然后我使用 jenkinsfile 手动运行 Jenkins 作业,如下所示。
  3. 工作流必须是:部署到开发环境,当且仅当之前的部署成功,部署到阶段。在这里,我们必须停下来让 QA 人员检查网站是否存在任何断开的链接、错误等。
  4. 如果一切都和我们预期的一样,并且没有发现错误,那么最后部署到生产环境。

注意:有些人建议我只进行登台和制作。我们没有那个配置的原因是因为dev环境不能在线访问,而之所以这样是因为我使用这个环境来测试后端配置(例如apache conf等)。

另外,其他一些人建议为每个环境建立一个分支,这在理论上是有道理的,但我认为这将改变我们的外包开发人员将代码提交到存储库的方式,我的意思是,他们总是必须将代码提交到 dev 分支,然后合并到 stage 分支以部署到 stage,我认为这不是很好。

现在,步骤 2-4 如下所示: 为了给您举例说明该流程的外观,我们将创建一个名为“Bearitos”的示例网站和工作:

在名为“Bearitos”的工作中,有一个名为“Bearitos to any”的项目

这基本上意味着在该项目内部,我有一个配置有三个阶段的管道:dev、staging 和 prod,它们使用以下参数进行参数化:DEPLOY_TO: Dev/staging/prod 和 DEPLOY_DB: Yes/No。因此,根据用户的选择,Jenkins 将部署到我认为甚至没有必要拥有这些选项的特定环境,因为正确的部署流程应该是 dev -> staging -> prod,不应该有场景将跳过开发或登台,然后在生产旁边部署,所以我认为这应该更好地更新

在 Jenkinsfile 中,我定义了 Dev、Staging 或 Prod 三个阶段,以及是否选择构建数据库的选项,以下是我的 Jenkinsfile 的示例:

// Deployment template for CMS-based websites (Drupal or Wordpress)
// 
//
pipeline {
    agent any

    parameters {
        choice choices: ['Dev', 'Staging', 'Production'], description: "Choose which environment to push changes to.", name: "DEPLOY_TO"
        booleanParam defaultValue: true, "Choose whether to deploy the database.", name: "DEPLOY_DB"
    }

    environment {
         SITEID = "lb"
        NOFLAGS = "0"
        DBNAME = "wpress_myproject"
        DBSERVER = "dbserver"
        DBUSER = "WordpressUser"
        DBPASS = "hiddenpassword"
        EXCLUDE = "domain_commentmeta,domain_comments"  // separate multiple tables with commas
        DEPLOY_TO = "${params.DEPLOY_TO}"
        DEPLOY_DB = "${params.DEPLOY_DB}"
    }

    stages {
        stage("deploy-db-dev") {
            when {
                allOf { 
                    environment ignoreCase: true, name: "DEPLOY_TO", value: "dev"; 
                    environment ignoreCase: true, name: "DEPLOY_DB", value: "true"; 
                }
            }
            steps {
                // this stage only required until we make our dev the master DB
                // copy full dev database from bolwebdev1
                // import latest database dump to dev server
                script {
                    FILENM = sh(script: 'ls -t myproject-s-dump* | head -1', returnStdout: true)
                }
                //Fixing the problem with the collation existing in the sql dump file, refer to: https://stackoverflow.com/questions/42385099/1273-unknown-collation-utf8mb4-unicode-520-ci 
                //apparently, this is due to a version of mysql issue. Once the problem is fixed from the server side we can then remove the following lines. 

                sh """sed -i s/utf8mb4_unicode_520_ci/utf8mb4_unicode_ci/g ${FILENM}
                # The following line was added because the site is pointing to a staging server which we don't have control over, again, once this is fixed we can delete the following line of code. 
                sed -i s/myproject.staging.websites.3pth.com/myproject.example.net/g ${FILENM}
                mysql -h devserver2 -u ${env.DBUSER} --password='${env.DBPASS}' ${env.DBNAME}_dev < ${WORKSPACE}/${FILENM}
                rm -f ${WORKSPACE}/${FILENM}"""
        }
        }
        stage("deploy-dev") {
            when {
                environment ignoreCase: true, name: "DEPLOY_TO", value: "dev"
            }
            steps {
                // copy files to devserver2
                // NOTE: if we move the repo to SVN, we should change httpdocs/ to ${env.SITEID}docs/
                sh """sudo chown jenkins:jenkins *

                #Replace the wp-config.php file with our domain file with our information. 
        /bin/cp httpdocs/wp-config-domain.php httpdocs/wp-config.php

                # prepare the dev server to receive files by changing the owner
                ssh webadmin@devserver2 'sudo chown -R webadmin:webadmin /var/opt/httpd/${env.SITEID}docs/'
                # copy files from control server to dev
                rsync --exclude=Jenkinsfile -rav -e ssh --delete ${WORKSPACE}/httpdocs/ webadmin@devserver2:/var/opt/httpd/${env.SITEID}docs/
                # fix the owner/permissions on the dev server
        ssh webadmin@devserver2 'sudo chown -R apache:${env.SITEID}-web /var/opt/httpd/${env.SITEID}docs/ && sudo chmod -R g+w /var/opt/httpd/${env.SITEID}docs/ && sudo find /var/opt/httpd/${env.SITEID}docs/ -type d -exec chmod g+s {} \\;'"""
            }
        }
        stage("deploy-db-staging") {
            when {
                allOf { 
                    environment ignoreCase: true, name: "DEPLOY_TO", value: "staging"; 
                    environment ignoreCase: true, name: "DEPLOY_DB", value: "true"; 
                }
            }
            steps {
                script {
                    def myexcludes = env.EXCLUDE.split(',').toList()
                    MYFLAGS = "-Q -K -c -e --default-character-set=utf8 "
                    if (env.NOFLAGS == "0") {
                        myexcludes.each {
                            MYFLAGS = "${MYFLAGS} --ignore-table=${env.DBNAME}_dev.${it}"
                        }
                    }
                }
                // pull a backup of the current dev database (may exclude some tables)
                sh """mysqldump -h devserver2 -u ${env.DBUSER} --password='${env.DBPASS}' ${env.DBNAME}_dev ${MYFLAGS} > ${env.DBNAME}_dev.sql
        #Searching and replace for the URL to change from the dev sever to the staging server
                sed -i s/myproject.example.net/stage-myproject.example.net/g ${env.DBNAME}_dev.sql

        # create a backup copy of the current staging database (full backup)
                mysqldump -h ${env.DBSERVER} -u ${env.DBUSER} --password='${env.DBPASS}' ${env.DBNAME}_stage > ${env.DBNAME}_stage_bak.sql
                # upload the dev database dump to the staging database
                mysql -h ${env.DBSERVER} -u ${env.DBUSER} --password='${env.DBPASS}' ${env.DBNAME}_stage < ${WORKSPACE}/${env.DBNAME}_dev.sql
                rm -f ${WORKSPACE}/${env.DBNAME}_dev.sql"""
       }
        }
        stage("deploy-staging") {
            when {
                environment ignoreCase: true, name: "DEPLOY_TO", value: "staging"
            }
            steps {
                // copy files from dev to control server
                sh """rsync --exclude=.svn --exclude=.git -rav -e ssh webadmin@devserver2:/var/opt/httpd/${env.SITEID}docs/ /tmp/${env.SITEID}docs/

                #Replace the wp-config.php file with our domain file with our information. 
            /bin/cp httpdocs/wp-config-domain.php httpdocs/wp-config.php

                #prepare the staging server to receive files by changing the owner
                ssh webadmin@stageserver 'sudo chown -R webadmin:webadmin /var/opt/httpd/${env.SITEID}docs/'
                # copy files from control server to staging
                rsync --exclude=.svn --exclude=.git -rav -e ssh --delete /tmp/${env.SITEID}docs/ webadmin@stageserver:/var/opt/httpd/${env.SITEID}docs/
                # fix the owner/permissions on the staging server
                ssh webadmin@stageserver 'sudo chown -R apache:${env.SITEID}-web /var/opt/httpd/${env.SITEID}docs/ && sudo chmod -R g+w /var/opt/httpd/${env.SITEID}docs/ && sudo find /var/opt/httpd/${env.SITEID}docs/ -type d -exec chmod g+s {} \\;'

                #delete the temporary files on the control server
                rm -Rf /tmp/${env.SITEID}docs/
                # clear the Incapsula caches
                if [[ \$( curl -sS -X POST \"http://www.example.net/incapcache.php?api_key=asdaswwGR)feasdsdda&site_id=stage&resource_url=stage-myproject.example.net\" | jq -r .debug_info.id_info) != \"incapsula cache cleared successfuly\" ]]; then exit 255; fi"""
            }
        }
        stage("deploy-db-production") {
            when {
                allOf { 
                    environment ignoreCase: true, name: "DEPLOY_TO", value: "production"; 
                    environment ignoreCase: true, name: "DEPLOY_DB", value: "true"; 
                }
            }
            steps {
                script {
                    def myexcludes = env.EXCLUDE.split(',').toList()
                    MYFLAGS = "-Q -K -c -e --default-character-set=utf8 "
                    if (env.NOFLAGS == "0") {
                        myexcludes.each {
                            MYFLAGS = "${MYFLAGS} --ignore-table=${env.DBNAME}_stage.${it}"
                        }
                    }
                }
                sh """cd ${WORKSPACE}
                # pull a backup of the current staging database (may exclude some tables)
                mysqldump -h ${env.DBSERVER} -u ${env.DBUSER} --password='${env.DBPASS}' ${env.DBNAME}_stage ${MYFLAGS} > ${env.DBNAME}_stage.sql
        #Searching and replace for the URL to change from the stage sever to the prod server
                sed -i s/stage-myproject.example.net/www.myproject.com/g ${env.DBNAME}_stage.sql

                # create a backup copy of the current production database (full backup)
                mysqldump -h ${env.DBSERVER} -u ${env.DBUSER} --password='${env.DBPASS}' ${env.DBNAME}_prod > ${env.DBNAME}_prod_bak.sql
                # upload the staging database dump to the production database
                mysql -h ${env.DBSERVER} -u ${env.DBUSER} --password='${env.DBPASS}' ${env.DBNAME}_prod < ${WORKSPACE}/${env.DBNAME}_stage.sql
                rm -f ${WORKSPACE}/${env.DBNAME}_stage.sql"""
        }
        }
        stage("deploy-production") {
            when {
                environment ignoreCase: true, name: "DEPLOY_TO", value: "production"
            }
            steps {
                // copy files from staging to control server
                sh """rsync --exclude=.svn --exclude=.git -rav -e ssh webadmin@stageserver:/var/opt/httpd/${env.SITEID}docs/ /tmp/${env.SITEID}docs/

                # prepare the production server to receive files by changing the owner
                ssh webadmin@prodserver1 'sudo chown -R webadmin:webadmin /var/opt/httpd/${env.SITEID}docs'
                ssh webadmin@prodserver2 'sudo chown -R webadmin:webadmin /var/opt/httpd/${env.SITEID}docs'
                # copy files from control server to production
                rsync --exclude=.svn --exclude=.git -rav -e ssh --delete /tmp/${env.SITEID}docs/ webadmin@prodserver1:/var/opt/httpd/${env.SITEID}docs/
                rsync --exclude=.svn --exclude=.git -rav -e ssh --delete /tmp/${env.SITEID}docs/ webadmin@prodserver2:/var/opt/httpd/${env.SITEID}docs/
                # fix the owner/permissions on the production server
                ssh webadmin@prodserver1 'sudo chown -R apache:${env.SITEID}-web /var/opt/httpd/${env.SITEID}docs/'
                ssh webadmin@prodserver2 'sudo chown -R apache:${env.SITEID}-web /var/opt/httpd/${env.SITEID}docs/'
                ssh webadmin@prodserver1 'sudo chmod -R g+w /var/opt/httpd/${env.SITEID}docs/'
                ssh webadmin@prodserver2 'sudo chmod -R g+w /var/opt/httpd/${env.SITEID}docs/'
                ssh webadmin@prodserver1 'sudo find /var/opt/httpd/${env.SITEID}docs/ -type d -exec chmod g+s {} \\;'
                ssh webadmin@prodserver2 'sudo find /var/opt/httpd/${env.SITEID}docs/ -type d -exec chmod g+s {} \\;'

                # delete the temporary files on the control server
                rm -Rf /tmp/${env.SITEID}docs/
                # clear the Incapsula caches
                if [[ \$( curl -sS -X POST \"http://www.example.net/incapcache.php?api_key=asdaswwGR)feasdsdda&site_id=088&resource_url=www.myproject.com\" | jq -r .debug_info.id_info) != \"incapsula cache cleared successfuly\" ]]; then exit 255; fi"""
            }
        }
    }
}

我目前使用这种方法面临的问题是:

  1. 我无法弄清楚如何使部署自动化,因为它是 参数化管道,所以我不确定如何使其自动化。这 期望的过程是使部署自动化一次 Jenkins 在 git 存储库上每 X 分钟轮询一次, 自动部署到 Dev > Stage(仅当 Dev 部署成功时)然后停止 在我们对 Staging 进行 QA 后手动部署到 Prod 之前。

  2. 当前Git配置只配置了一个分支 (master) 这是开发人员推送更改的地方 想要部署到 Dev -> Stage -> Prod。但我认为 理想的情况是有一个用于开发部署的开发分支然后 stage 分支,用于部署到 Stage 环境,然后 master for 一旦我们将这些 dev 和 staging 分支合并到 主分支。我不确定这是否是最佳的,所以我会 感谢您对此的任何建议或想法。

理想的方法是解决所提到的问题,并且一旦 dev -> staging 部署成功,还可以采用自动化的方式进行部署和通知。除了可以选择手动执行上述工作流程,就像我们现在正在做的那样(这不是那么重要,但如果有这个功能会很好)。

提前感谢您的帮助!

【问题讨论】:

    标签: git jenkins jenkins-pipeline


    【解决方案1】:
    1. 去掉你的参数,它们不是必需的(会阻止你自动化)。
    2. deploy to prod 阶段手动输入
    pipeline {
        agent any
        stages {
            stage('Deploy to prod') {
                input {
                    message "Should we continue?"
                    ok "Yes, we should."
                }
                steps {
                    echo "Deploying."
                }
            }
        }
    }
    
    1. 这应该是 Jenkins 中的多分支管道项目(因为您希望在所有分支上都使用它)
    2. 如果你想为不同的分支使用不同的阶段,请使用when
    pipeline {
        agent any
        stages {
            stage('Example Build') {
                steps {
                    echo 'Hello World'
                }
            }
            stage('Example Deploy') {
                when {
                    branch 'production'
                }
                steps {
                    echo 'Deploying'
                }
            }
        }
    }
    

    至于建议 - 我会说您需要将您的 git 流程与您的 CI/CD 流程相匹配。给定 git 分支类型的生命周期是什么?给定阶段的结果是什么?你想为所有分支执行阶段,deploy to prod 只为一个分支执行?

    【讨论】:

    • 感谢您的回复!关于第 1 点,即使不是那么重要,我也希望能够手动部署。关于你的最后一个问题,我已经更新了我的主要帖子。再次感谢您!
    • 手动我的意思是我现在正在这样做,进入jenkins选择工作,然后选择“部署到开发”等,然后单击按钮进行部署,但就像我一样说这不是很重要,我认为对我来说更重要的是要知道詹金斯的工作是什么样的,我的意思是,你能告诉我这次我必须如何在詹金斯创造这份工作吗?创建三个文件夹或三个管道,或者会是什么样子?
    • 好问题。一种选择是在 jenkins 中创建多分支管道项目,并将配置作为代码表示 Jenkinsfile(您需要将其提交给 git)。你不会有 3 个单独的工作,每个项目只有一个工作,内部每个分支都有部门,在这个内部你会有舞台视图。如果您的某些阶段仅适用于某些分支,那么这些阶段可能看起来不同(例如,没有 deploy to prod 用于开发分支)。但是,嘿,这几乎就是你现在所拥有的。
    • 当您提到“每个分支都会有一个部门”时,我认为您认为我每个环境都有一个分支,而我没有。我现在只有一个主分支。目前我没有计划为每个环境创建一个分支。
    • 但是您正在使用 Jenkinsfiles。一般来说,您可以在 Jenkins 中只有一个管道项目,并且仍然遵循相同的设计。带有分支的想法假设您将使用相同的 Jenkinsfile,但您将有一些条件来包含某些分支。
    【解决方案2】:

    除了实现一个单独的部署管道,它能够部署到所有环境并被参数化并实现另一个管道,该管道被调度并触发管道部署到开发(阶段开发),当这个工作成功时触发管道再次部署到阶段(阶段 qa)。然后可以手动完成对 prod 的部署。

    https://jenkins.io/doc/pipeline/steps/pipeline-build-step/#-build-%20build%20a%20job

    【讨论】:

      【解决方案3】:
      pipeline 
      {
              stages 
              {
                     stage('Build')
                     {
                           steps
                           {
                              echo 'building the codes from the git'
                            }
                      }
                      stage('developer-branch-stuff')
                      {
                         when
                         {
                             branch 'developer'
                         }
                         steps
                         {
                            echo 'run this stage - only if the branch = developer branch'
                         }
                      }
              stage('Deliver for development') 
              {
                  when 
                  {
                      branch 'developer'
                  }
                  steps 
                  {
                      sh 'your_filename_along_with_your_filepath'
                      input message: 'shall we deploy it? (Click "Proceed" to continue)'
                  }
              }
              stage('Deploy for production') 
              {
                  when
                  {
                      branch 'developer'
                  }
                  steps
                  {
                      sh 'your_filename_along_with_your_filepath'
                      input message: 'shall we proceed to production? (Click "Proceed" to continue)'
                  }
              }
          }
      }
      

      【讨论】:

      • 感谢您的回答,这段代码是否假设我每个环境都有一个 git 分支?
      • 是的,假设您对所有环境都有单独的特定分支。
      • 就像我的帖子所说的,在我的情况下,我在;在这种情况下,你有 master 分支。
      • 如果您有 master 分支,那么您可以将分支名称更改为“master”。一旦您将该分支名称更改为 master,那么只有 master 分支将被允许用于部署和生产...条件语句中的分支名称取决于您创建的分支。
      • 只是让您知道我正在使用主分支部署到开发环境,然后进行登台然后到生产,这只是一个线性部署,所以我想要的只是使用主分支,我们可以部署到开发环境,然后自动部署到暂存环境,当对存储库中的主分支进行新提交时,如果一切在暂存中看起来都很好,我想从那里手动部署到生产环境。我的问题是,在这种情况下我还能使用你的代码吗?
      【解决方案4】:

      我会在这里使用git tags

      首先,我会有 Dev 构建作业,它被配置为侦听我的主分支的任何提交并开始构建代码、运行单元测试、将应用程序部署到开发环境等. 如果构建成功,它将用特定的版本号标记 git 存储库。

      现在,Staging 构建作业将被配置为 Dev 构建作业的下游作业,并且只有在 Dev 构建作业成功时才会执行。当它运行时,它将版本号作为来自上游开发构建作业的参数,并检查该特定版本的代码。如果失败,它将从存储库中删除该特定版本标记。

      如果您想在上述两个阶段中的任何一个阶段进行手动测试并将构建标记为“通过/失败”,则可以使用 Fail the build Jenkins 插件。如果您在手动测试后将构建标记为“失败”,那么您还应该删除与构建对应的特定版本标签。

      之后,您可以进行手动 Release 作业,该作业会列出 git 存储库中标记所有成功构建的所有版本标签。您可以选择任何一个版本并启动发布作业,它将与该构建相关的代码部署到生产中。

      【讨论】:

        猜你喜欢
        • 2013-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-02
        • 2016-06-21
        • 1970-01-01
        相关资源
        最近更新 更多