mcpField
J
jenkins

jenkins

github.com/bagelholeクラウド・DevOps1.2k340 回インストール23 週間前に更新
リポジトリ

jenkins について

CI/CD に取り組む Jenkins 管理者や開発チーム向けのスキルです。宣言型・スクリプト型の例を通じて、パイプライン、ビルドエージェント、認証情報、プラグイン、共有ライブラリを扱います。

主な機能

  1. 01宣言型・スクリプト型パイプライン
  2. 02Docker、Kubernetes、ラベル指定エージェント
  3. 03パラメーターと認証情報の設定
  4. 04並列ステージとマルチブランチパイプライン
  5. 05共有ライブラリによるコード再利用
  6. 06プラグインと Configuration as Code の管理

活用シーン

  1. 01アプリケーションリポジトリ用の Jenkinsfile 作成
  2. 02Docker または Kubernetes ビルドエージェントの設定
  3. 03共有ライブラリを使ったビルド・デプロイ手順の再利用
  4. 04Jenkins プラグインとサーバー設定の管理

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/bagelhole/devops-security-agent-skills --skill jenkins

インストール後、Claude Code で/jenkinsを入力して読み込まれたか確認します。

同梱ファイルreferences/pipeline-syntax.md

詳細

Jenkins

主要なオープンソースの自動化サーバーである Jenkins を使用して、アプリケーションをビルド、テスト、デプロイします。

このスキルを使用する場面

次の場合にこのスキルを使用します:

  • Jenkins パイプライン(宣言型またはスクリプト型)を設定する
  • Jenkins エージェントとエグゼキューターを設定する
  • Jenkins プラグインとセキュリティを管理する
  • パイプラインを再利用するための共有ライブラリを作成する
  • Jenkins を外部ツールと連携する

前提条件

  • Jenkins サーバー(2.x 以降)
  • Jenkins の管理者アクセス権
  • Jenkins サーバー上の Java 11 以降
  • パイプラインに関する基本的な Groovy の知識

宣言型パイプライン

リポジトリのルートに Jenkinsfile を作成します:

pipeline {
    agent any
    
    environment {
        DOCKER_REGISTRY = 'registry.example.com'
        APP_NAME = 'myapp'
    }
    
    stages {
        stage('Build') {
            steps {
                sh 'npm ci'
                sh 'npm run build'
            }
        }
        
        stage('Test') {
            steps {
                sh 'npm test'
            }
            post {
                always {
                    junit 'test-results/*.xml'
                }
            }
        }
        
        stage('Deploy') {
            when {
                branch 'main'
            }
            steps {
                sh './deploy.sh'
            }
        }
    }
    
    post {
        failure {
            mail to: '[email protected]',
                 subject: "Pipeline Failed: ${env.JOB_NAME}",
                 body: "Check console output at ${env.BUILD_URL}"
        }
    }
}

エージェントの設定

Docker エージェント
pipeline {
    agent {
        docker {
            image 'node:20'
            args '-v /tmp:/tmp'
        }
    }
    stages {
        stage('Build') {
            steps {
                sh 'npm ci && npm run build'
            }
        }
    }
}
Kubernetes エージェント
pipeline {
    agent {
        kubernetes {
            yaml '''
                apiVersion: v1
                kind: Pod
                spec:
                  containers:
                  - name: node
                    image: node:20
                    command:
                    - sleep
                    args:
                    - infinity
                  - name: docker
                    image: docker:24-dind
                    securityContext:
                      privileged: true
            '''
        }
    }
    stages {
        stage('Build') {
            steps {
                container('node') {
                    sh 'npm ci && npm run build'
                }
            }
        }
    }
}
ラベル付きエージェント
pipeline {
    agent { label 'linux && docker' }
    stages {
        stage('Build') {
            steps {
                sh 'make build'
            }
        }
    }
}

パラメーター

pipeline {
    agent any
    
    parameters {
        string(name: 'BRANCH', defaultValue: 'main', description: 'Branch to build')
        choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'prod'], description: 'Target environment')
        booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run tests?')
    }
    
    stages {
        stage('Deploy') {
            when {
                expression { params.ENVIRONMENT == 'prod' }
            }
            steps {
                sh "deploy.sh ${params.ENVIRONMENT}"
            }
        }
    }
}

認証情報

認証情報の使用
pipeline {
    agent any
    
    environment {
        AWS_CREDS = credentials('aws-credentials')
        DOCKER_CREDS = credentials('docker-hub')
    }
    
    stages {
        stage('Deploy') {
            steps {
                withCredentials([
                    usernamePassword(
                        credentialsId: 'github-token',
                        usernameVariable: 'GH_USER',
                        passwordVariable: 'GH_TOKEN'
                    )
                ]) {
                    sh 'git push https://${GH_USER}:${GH_TOKEN}@github.com/repo.git'
                }
            }
        }
    }
}

並列ステージ

pipeline {
    agent any
    
    stages {
        stage('Tests') {
            parallel {
                stage('Unit Tests') {
                    steps {
                        sh 'npm run test:unit'
                    }
                }
                stage('Integration Tests') {
                    steps {
                        sh 'npm run test:integration'
                    }
                }
                stage('E2E Tests') {
                    steps {
                        sh 'npm run test:e2e'
                    }
                }
            }
        }
    }
}

共有ライブラリ

ライブラリの構造
vars/
├── buildApp.groovy
├── deployApp.groovy
└── notifySlack.groovy
src/
└── com/example/
    └── Pipeline.groovy
resources/
└── templates/
    └── deployment.yaml
共有ステップの定義
// vars/buildApp.groovy
def call(Map config = [:]) {
    def nodeVersion = config.nodeVersion ?: '20'
    
    docker.image("node:${nodeVersion}").inside {
        sh 'npm ci'
        sh 'npm run build'
    }
}
共有ライブラリの使用
@Library('my-shared-library') _

pipeline {
    agent any
    
    stages {
        stage('Build') {
            steps {
                buildApp(nodeVersion: '20')
            }
        }
        stage('Deploy') {
            steps {
                deployApp(environment: 'staging')
            }
        }
    }
    
    post {
        failure {
            notifySlack(channel: '#builds', status: 'FAILED')
        }
    }
}

スクリプト型パイプライン

node('linux') {
    try {
        stage('Checkout') {
            checkout scm
        }
        
        stage('Build') {
            docker.image('node:20').inside {
                sh 'npm ci'
                sh 'npm run build'
            }
        }
        
        stage('Test') {
            sh 'npm test'
        }
        
        if (env.BRANCH_NAME == 'main') {
            stage('Deploy') {
                sh './deploy.sh'
            }
        }
    } catch (e) {
        currentBuild.result = 'FAILURE'
        throw e
    } finally {
        cleanWs()
    }
}

プラグイン管理

必須プラグイン
// Install via Jenkins CLI or init.groovy.d
def plugins = [
    'workflow-aggregator',      // Pipeline
    'git',                      // Git integration
    'docker-workflow',          // Docker Pipeline
    'kubernetes',               // Kubernetes agent
    'credentials-binding',      // Credentials
    'blueocean',               // Blue Ocean UI
    'job-dsl',                 // Job DSL
    'configuration-as-code'    // JCasC
]
Configuration as Code
# jenkins.yaml
jenkins:
  systemMessage: "Jenkins configured via JCasC"
  numExecutors: 2
  
  securityRealm:
    local:
      users:
        - id: admin
          password: ${ADMIN_PASSWORD}
  
  authorizationStrategy:
    globalMatrix:
      permissions:
        - "Overall/Administer:admin"
        - "Overall/Read:authenticated"

credentials:
  system:
    domainCredentials:
      - credentials:
          - usernamePassword:
              id: "docker-hub"
              username: "user"
              password: ${DOCKER_PASSWORD}

マルチブランチパイプライン

// Automatically discovers branches with Jenkinsfile
// Configure in Jenkins UI: New Item > Multibranch Pipeline

// Branch-specific behavior in Jenkinsfile
pipeline {
    agent any
    
    stages {
        stage('Deploy') {
            when {
                anyOf {
                    branch 'main'
                    branch 'release/*'
                }
            }
            steps {
                sh './deploy.sh'
            }
        }
    }
}

よくある問題

問題:パイプラインの構文エラー

問題:Jenkinsfile の解析に失敗する 解決策:Jenkins UI の Pipeline Syntax ジェネレーターを使用し、jenkins-cli で検証します

問題:エージェントが接続できない

問題:ビルドエージェントが切断される 解決策:エージェントのログを確認し、ネットワーク接続を検証して、タイムアウト設定を増やします

問題:メモリ不足

問題:Jenkins がクラッシュするか、OOM によってビルドが失敗する 解決策:JAVA_OPTS でヒープサイズを増やし、古いビルドを削除します

ベストプラクティス

  • ほとんどのユースケースでは宣言型パイプラインを使用します
  • コードを再利用できるよう、共有ライブラリを実装します
  • Jenkinsfile をソース管理に保存します
  • シークレット管理には credentials プラグインを使用します
  • post ブロックで適切なクリーンアップを実装します
  • ビルドの保持ポリシーを設定します
  • モダンな UI を利用するには Blue Ocean を使用します

関連スキル

コメント