متقدم
البحث فيالمعامل
طريقة البحث
  • ابحث عن مهمة أو أداة (lvm، selinux، ‎@podman)؛ وصفِّ حسب المستوى والكتاب أو الدورة.
  • مع مربع بحث فارغ، الفلتر وحده يعرض المعامل — مثلًا كل المعامل الصعبة لدورة واحدة.
  • "كلمتان" تجد العبارة بالضبط.
  • الكلمات العادية تجد الأسماء والنصوص والأمثلة.
  • ↑ ↓ للتنقل · Enter للفتح · Esc للإغلاق · / للبحث
جرّب:

معمل 4.1DevOps on Manara, الفصل 4

A Jenkins pipeline as code: build, test, scan, approve and deploy

المستوى
متوسط
60 دقيقة
الأجهزة
Linux or macOS with Docker, a Git repository (local or GitHub)
الحالة
لم يبدأ

هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.

الهدف

Run Jenkins in a container and write a declarative Jenkinsfile that follows the CI/CD best practices from the course: every stage in code, fast feedback first, tests with reports, a security scan that can stop the build, an artifact with a version, a manual approval before production, and clean-up in post. The same ideas map 1:1 to GitHub Actions and GitLab CI.

قبل أن تبدأ

  • Docker works. Start Jenkins LTS with a named volume:
    docker run -d --name jenkins -p 8080:8080 -v jenkins_home:/var/jenkins_home jenkins/jenkins:lts-jdk17
    docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword
  • Open http://localhost:8080, paste the password, install the suggested plugins, make an admin user.
  • Use the small Python app from the TDD lab (alerts.py + test_alerts.py) in a Git repository.

المهام

  1. Write a Jenkinsfile with the stages Checkout, Lint, Test, Security scan, Package, Deploy to staging, Approve, Deploy to production.
  2. Run the Python steps inside a python:3.12-slim container agent or install Python in a sh step with a virtual environment (keep the job self-contained).
  3. Publish the test results (pytest --junitxml) so Jenkins shows the test trend.
  4. Fail the build when Bandit finds a high-severity issue.
  5. Package a versioned artifact (app-${BUILD_NUMBER}.tar.gz) and archive it with a SHA-256 checksum.
  6. Add an input step before production that only the group release-managers (or your admin) may approve, with a 30-minute timeout.
  7. Add options (timeout of the whole job, keep the last 10 builds, no concurrent builds) and a post section (always clean the workspace; on failure, print a clear message).
  8. Create a Pipeline job that reads the Jenkinsfile from your repository (Pipeline script from SCM) and run it twice: once green, once with a broken test.

تحقّق من عملك

  • The stage view shows all 8 stages; the run waits at Approve until you click Proceed.
  • Test Result shows the number of tests; the broken run is red at Test and never reaches Package.
  • The artifacts of a green build are app-N.tar.gz and app-N.tar.gz.sha256.
  • Changing the pipeline means a Git commit — nobody edits the job in the UI.

تلميحات

اعرض التلميحات
  • agent { docker { image 'python:3.12-slim' } } needs the Docker Pipeline plugin and Docker inside Jenkins; the simpler way for the lab is a virtual environment in sh steps (install python3-venv in the container once: docker exec -u root jenkins apt-get update && docker exec -u root jenkins apt-get install -y python3-venv).
  • junit 'reports/*.xml' publishes test results; archiveArtifacts artifacts: 'dist/*', fingerprint: true keeps files.
  • input message: 'Deploy to production?', submitter: 'release-managers' inside timeout(time: 30, unit: 'MINUTES') { ... }.
  • Never put passwords in the Jenkinsfile: use Credentials and withCredentials.

الحل

اعرض الحل
Jenkinsfile
pipeline {
  agent any
  options {
    timeout(time: 45, unit: 'MINUTES')
    buildDiscarder(logRotator(numToKeepStr: '10'))
    disableConcurrentBuilds()
  }
  environment {
    VENV = "${WORKSPACE}/.venv"
  }
  stages {
    stage('Checkout') { steps { checkout scm } }
    stage('Lint') {
      steps {
        sh 'python3 -m venv $VENV && . $VENV/bin/activate && pip install -q pytest bandit ruff'
        sh '. $VENV/bin/activate && ruff check .'
      }
    }
    stage('Test') {
      steps { sh '. $VENV/bin/activate && mkdir -p reports && pytest -q --junitxml=reports/tests.xml' }
      post { always { junit 'reports/*.xml' } }
    }
    stage('Security scan') {
      steps { sh '. $VENV/bin/activate && bandit -r . -x ./.venv,./test_alerts.py --severity-level high' }
    }
    stage('Package') {
      steps {
        sh 'mkdir -p dist && tar czf dist/app-${BUILD_NUMBER}.tar.gz alerts.py && cd dist && sha256sum app-${BUILD_NUMBER}.tar.gz > app-${BUILD_NUMBER}.tar.gz.sha256'
        archiveArtifacts artifacts: 'dist/*', fingerprint: true
      }
    }
    stage('Deploy to staging') {
      steps { sh 'echo "deploy app-${BUILD_NUMBER} to staging" && mkdir -p /tmp/staging && cp dist/app-${BUILD_NUMBER}.tar.gz /tmp/staging/' }
    }
    stage('Approve') {
      steps {
        timeout(time: 30, unit: 'MINUTES') {
          input message: "Deploy app-${env.BUILD_NUMBER} to production?", submitter: 'admin,release-managers'
        }
      }
    }
    stage('Deploy to production') {
      steps { sh 'echo "deploy app-${BUILD_NUMBER} to production" && mkdir -p /tmp/prod && cp dist/app-${BUILD_NUMBER}.tar.gz /tmp/prod/' }
    }
  }
  post {
    failure { echo "Build ${env.BUILD_NUMBER} failed in a quality gate. Fix it before you merge." }
    always { cleanWs() }
  }
}
  1. Commit the Jenkinsfile, then in Jenkins: New Item → Pipeline → Pipeline script from SCM → Git → your repository URL → Script Path Jenkinsfile → Save → Build Now.
  2. Click Proceed at Approve and check the artifacts and Test Result.
  3. Break a test (return a - b), commit, build again: red at Test, no artifact, no deploy. Revert the commit.
  4. Clean up: docker rm -f jenkins && docker volume rm jenkins_home.

ملاحظاتي

لا توجد ملاحظات بعد.

دروس هذا المعمل

الأوامر في هذا المعمل