jenkins
Operate Jenkins CI/CD: pipelines as code, agents, shared libraries, credentials, and plugins. Use for build and release automation.
Jenkins
CI/CD automation with Jenkins.
Quick Start
docker run -p 8080:8080 -p 50000:50000 -d jenkins/jenkins:lts
# http://localhost:8080, unlock with initial admin passwordWhen to Use
- Build/test/deploy pipelines
- Complex multi-stage workflows
- Legacy or on-prem CI needs
- Plugin-rich automation
Best Practices
Pipelines as Code
- Use Declarative pipelines in a Jenkinsfile
- Store Jenkinsfiles in the repo with the app
- Keep stages small and named
- Use parameters for reusability
Agents & Concurrency
- Use labels to route jobs to agents
- Limit concurrent builds per job
- Use ephemeral agents/containers
- Keep agent images preloaded
Credentials & Security
- Store secrets in Credentials (never inline)
- Bind with `withCredentials`
- Scope credentials to projects
- Enable RBAC and restrict admin
Maintenance
- Version shared libraries (pipelines)
- Pin plugin versions and update deliberately
- Clean workspaces and artifacts
- Monitor disk and build times
Dependencies
docker run -p 8080:8080 -p 50000:50000 -d jenkins/jenkins:ltsExamples
// Declarative Jenkinsfile
pipeline {
agent { label 'linux' }
parameters {
string(name: 'BRANCH', defaultValue: 'main', description: 'Branch to build')
}
stages {
stage('Checkout') {
steps { git branch: "${params.BRANCH}", url: 'https://github.com/org/app.git' }
}
stage('Test') {
steps { sh 'pytest tests/' }
}
stage('Deploy') {
steps { sh './deploy.sh' }
}
}
post {
always { junit 'reports/**/*.xml' }
failure { emailext subject: 'Build failed', to: 'dev@example.com' }
}
}// Using credentials safely
pipeline {
stages {
stage('Push') {
steps {
withCredentials([string(credentialsId: 'dockerhub', variable: 'TOKEN')]) {
sh 'docker login -u user -p "$TOKEN"'
}
}
}
}
}// Shared library reference
@Library('my-lib@1.2') _
def result = myDeploy(stage: 'prod')Step-by-Step
1. Install Jenkins and configure the master.
2. Add agents or use cloud agents.
3. Create a pipeline job referencing the Jenkinsfile.
4. Write declarative stages for build/test/deploy.
5. Store secrets in Credentials.
6. Add post-build actions and notifications.
7. Version shared libraries.
8. Monitor disk, plugins, and build times.
Validation
1. Pipelines run green on the target branches
2. Secrets never appear in logs
3. Builds route to correct agents
4. Failures notify and clean up
5. Plugin versions are pinned
Troubleshooting
- Pipeline syntax errors: validate via the Snippet Generator.
- Agent offline: check agent connectivity and labels.
- Secret leaks: rotate and fix the step that printed it.
Jenkins (Дженкинс)
CI/CD автоматизация через Jenkins.
Быстрый старт
docker run -p 8080:8080 -p 50000:50000 -d jenkins/jenkins:lts
# http://localhost:8080, разблокировка initial admin passwordКогда использовать
- Build/test/deploy пайплайны
- Сложные multi-stage workflow
- Легаси или on-prem CI
- Богатая плагинами автоматизация
Лучшие практики
Pipelines as code
- Declarative пайплайны в Jenkinsfile
- Jenkinsfile в репо с приложением
- Стадии небольшие и именованные
- Параметры для переиспользования
Агенты и конкурентность
- Labels для роутинга задач по агентам
- Лимиты параллельных сборок на задачу
- Эфемерные агенты/контейнеры
- Предзагруженные образы агентов
Креды и безопасность
- Секреты в Credentials (не inline)
- Привязка через `withCredentials`
- Скоуп кредов по проектам
- RBAC и ограничение админов
Поддержка
- Версионируйте shared libraries (pipelines)
- Пините версии плагинов и обновляйте осознанно
- Чистите workspaces и артефакты
- Мониторьте диск и время сборок
Зависимости
docker run -p 8080:8080 -p 50000:50000 -d jenkins/jenkins:ltsПримеры
// Declarative Jenkinsfile
pipeline {
agent { label 'linux' }
parameters {
string(name: 'BRANCH', defaultValue: 'main', description: 'Branch to build')
}
stages {
stage('Checkout') {
steps { git branch: "${params.BRANCH}", url: 'https://github.com/org/app.git' }
}
stage('Test') {
steps { sh 'pytest tests/' }
}
stage('Deploy') {
steps { sh './deploy.sh' }
}
}
post {
always { junit 'reports/**/*.xml' }
failure { emailext subject: 'Build failed', to: 'dev@example.com' }
}
}// Безопасное использование кредов
pipeline {
stages {
stage('Push') {
steps {
withCredentials([string(credentialsId: 'dockerhub', variable: 'TOKEN')]) {
sh 'docker login -u user -p "$TOKEN"'
}
}
}
}
}// Ссылка на shared library
@Library('my-lib@1.2') _
def result = myDeploy(stage: 'prod')Пошаговое руководство
1. Установите Jenkins и настройте master.
2. Добавьте агенты или cloud-агенты.
3. Создайте pipeline job со ссылкой на Jenkinsfile.
4. Напишите declarative стадии build/test/deploy.
5. Храните секреты в Credentials.
6. Добавьте post-build действия и уведомления.
7. Версионируйте shared libraries.
8. Мониторьте диск, плагины и время сборок.
Валидация
1. Пайплайны зелёные на целевых ветках
2. Секреты не появляются в логах
3. Сборки идут на корректные агенты
4. Фейлы уведомляют и чистят за собой
5. Версии плагинов пинованы
Устранение неполадок
- Синтаксис пайплайна: валидируйте через Snippet Generator.
- Агент offline: проверьте связь и labels.
- Утечки секретов: ротируйте и исправьте шаг, который напечатал.