Vai al contenuto

Jenkins Mac Build Agent: guida completa alla configurazione

Configura un agente di build Jenkins su un Mac Mini M4 dedicato. Automatizza le build Xcode, esegui test iOS e distribuisci su TestFlight con il pieno controllo della tua infrastruttura di build.

CI/CD 35 min di lettura Aggiornato a ottobre 2026

Perché un Mac dedicato per Jenkins?

Jenkins è la piattaforma CI/CD più diffusa, e gestisce oltre il 50% delle pipeline di build aziendali. Tuttavia, compilare app iOS con Jenkins richiede macOS, e macOS può legalmente girare solo su hardware Apple. Un Mac Mini M4 dedicato ti offre:

  • Ambiente di build coerente

    Stesso hardware, stesso OS, stessi strumenti a ogni build. Nessuna build instabile dovuta al drift dell'ambiente.

  • Accesso root completo

    Installa qualsiasi strumento, configura le impostazioni di sistema, gestisci i portachiavi per la firma del codice.

  • Prestazioni Apple Silicon

    Il chip M4 offre build Xcode 2-3 volte più veloci rispetto ai Mac Mini Intel.

  • Cache persistenti

    Le cache di DerivedData, CocoaPods e SPM sopravvivono tra una build e l'altra.

Prerequisiti

  • Un build server Mac mini M4 dedicato di My Remote Mac (da 85 $/mese, USD, tasse escluse)
  • Un controller Jenkins (può essere su Linux, Docker o qualsiasi VM cloud)
  • Accesso SSH al tuo Mac Mini
  • Xcode, preinstallato su ogni server My Remote Mac (la nostra guida GitHub Actions mostra come verificarlo e aggiungere altre versioni)

Passo 1: Installa Java JDK su macOS

Gli agenti Jenkins richiedono un Java Runtime Environment. Le versioni attuali di Jenkins supportano Java 21 e Java 25 (Java 17 non è più supportato), quindi installiamo JDK 21 (LTS) tramite Homebrew per una gestione semplice.

# Put the preinstalled Homebrew on your PATH (once per account)
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
eval "$(/opt/homebrew/bin/brew shellenv)"

# Install Java JDK 21 (LTS) with Homebrew
# (current Jenkins releases support Java 21 and 25)
brew install openjdk@21

# Create the symlink for system Java wrappers
sudo ln -sfn /opt/homebrew/opt/openjdk@21/libexec/openjdk.jdk \
  /Library/Java/JavaVirtualMachines/openjdk-21.jdk

# Add to PATH
echo 'export PATH="/opt/homebrew/opt/openjdk@21/bin:$PATH"' >> ~/.zprofile
source ~/.zprofile

# Verify Java installation (should report version 21)
java -version

# Tools used by the pipeline in Step 3 (CocoaPods only if you use a Podfile)
brew install xcbeautify cocoapods

Passo 2: Configura l'agente Jenkins

Esistono due metodi principali per connettere un agente Jenkins: un agente in entrata (l'agente si collega al controller; prima chiamato JNLP) e SSH (il controller si collega all'agente). Trattiamo entrambi.

Metodo A: Agente SSH (consigliato)

Questo è l'approccio più affidabile. Jenkins si connette al Mac via SSH e gestisce il processo dell'agente da remoto.

# On the Mac mini: create a dedicated, non-admin Jenkins user
sudo sysadminctl -addUser jenkins -fullName "Jenkins Agent" -password "STRONG_PASSWORD_HERE"

# Create its home folder from the macOS template (includes ~/Library)
sudo createhomedir -c -u jenkins

# If Remote Login is limited to some users (System Settings > General >
# Sharing > Remote Login), allow the jenkins user to connect over SSH
sudo dseditgroup -o edit -a jenkins -t user com.apple.access_ssh

# Create SSH directory and add the Jenkins controller's public key
sudo mkdir -p /Users/jenkins/.ssh
sudo sh -c 'echo "ssh-rsa YOUR_JENKINS_CONTROLLER_PUBLIC_KEY" > /Users/jenkins/.ssh/authorized_keys'
sudo chmod 700 /Users/jenkins/.ssh
sudo chmod 600 /Users/jenkins/.ssh/authorized_keys
sudo chown -R jenkins:staff /Users/jenkins/.ssh

# Create a workspace directory
sudo mkdir -p /Users/jenkins/workspace
sudo chown jenkins:staff /Users/jenkins/workspace

Ora configura l'agente in Jenkins:

  1. Vai su Manage Jenkins > Nodes > New Node
  2. Imposta il nome su mac-mini-m4
  3. Imposta la Remote root directory su /Users/jenkins/workspace
  4. Label: mac macos apple-silicon m4 ios
  5. Metodo di avvio: Launch agents via SSH
  6. Host: L'indirizzo IP del tuo Mac Mini
  7. Credenziali: Aggiungi la chiave privata SSH corrispondente agli authorized_keys sul Mac
  8. Host Key Verification Strategy: Known hosts file Verification Strategy. Prima del primo avvio, collegati una volta dal controller con l'utente che esegue Jenkins (ssh jenkins@YOUR_MAC_IP) per aggiungere il Mac al suo ~/.ssh/known_hosts

Metodo B: Agente in entrata (WebSocket)

Usa questo metodo quando il controller Jenkins non può raggiungere direttamente il Mac (ad es. il Mac è dietro un firewall). L'agente avvia la connessione. Con l'opzione -webSocket usa solo la porta web del controller (HTTP o HTTPS), senza una porta TCP separata per gli agenti.

# First, create the node in Jenkins UI:
# Manage Jenkins > Nodes > New Node
# Launch method: "Launch agent by connecting it to the controller"
# Note the secret token from the node configuration page

# On the Mac mini, download the agent JAR as the jenkins user
# (download it again after each Jenkins controller upgrade)
sudo -u jenkins mkdir -p /Users/jenkins/jenkins-agent
sudo -u jenkins curl -fsSL -o /Users/jenkins/jenkins-agent/agent.jar \
  https://your-jenkins-url/jnlpJars/agent.jar

# Test the agent connection. -webSocket goes through the controller's
# HTTP(S) port: no separate TCP agent port to open
sudo -u jenkins /opt/homebrew/opt/openjdk@21/bin/java \
  -jar /Users/jenkins/jenkins-agent/agent.jar \
  -url https://your-jenkins-url \
  -secret YOUR_AGENT_SECRET \
  -name "mac-mini-m4" \
  -webSocket \
  -workDir "/Users/jenkins/workspace"

Esegui l'agente in entrata come servizio launchd

L'agente gira come LaunchAgent dell'utente jenkins, quindi si avvia al login di quell'utente, non all'avvio del Mac. Su un Mac headless, abilita il login automatico per l'utente jenkins (Impostazioni di Sistema > Utenti e Gruppi; non disponibile mentre FileVault è attivo) così l'agente torna online dopo un riavvio. Questa sessione aperta dà anche ai simulatori, ai test UI e al portachiavi di login l'ambiente utente di cui hanno bisogno.

# Create the LaunchAgent in the jenkins user's own Library
sudo -u jenkins mkdir -p /Users/jenkins/Library/LaunchAgents
sudo -u jenkins tee /Users/jenkins/Library/LaunchAgents/io.jenkins.agent.plist > /dev/null <<'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>io.jenkins.agent</string>
    <key>ProgramArguments</key>
    <array>
        <string>/opt/homebrew/opt/openjdk@21/bin/java</string>
        <string>-jar</string>
        <string>/Users/jenkins/jenkins-agent/agent.jar</string>
        <string>-url</string>
        <string>https://your-jenkins-url</string>
        <string>-secret</string>
        <string>YOUR_AGENT_SECRET</string>
        <string>-name</string>
        <string>mac-mini-m4</string>
        <string>-webSocket</string>
        <string>-workDir</string>
        <string>/Users/jenkins/workspace</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/Users/jenkins/jenkins-agent/stdout.log</string>
    <key>StandardErrorPath</key>
    <string>/Users/jenkins/jenkins-agent/stderr.log</string>
</dict>
</plist>
EOF

# The agent loads at every login of the jenkins user. On a headless Mac,
# connect over VNC as an admin, open System Settings > Users & Groups and set
# "Automatically log in as" to jenkins (unavailable while FileVault is on),
# then restart:
sudo shutdown -r now

# After the restart, verify it's running
sudo launchctl print gui/$(id -u jenkins)/io.jenkins.agent | grep state

Passo 3: Crea la pipeline di build iOS

Crea un Jenkinsfile nella radice del tuo repository. Questa pipeline dichiarativa compila, testa e, facoltativamente, archivia la tua app iOS.

pipeline {
    agent { label 'mac && m4' }

    environment {
        // Pick the Xcode for every stage without sudo
        // (preinstalled Xcode; for another version, use the path from xcodes installed)
        DEVELOPER_DIR = '/Applications/Xcode.app/Contents/Developer'
        SCHEME        = 'MyApp'
        // Not WORKSPACE: Jenkins already uses it for the job's workspace path
        XC_WORKSPACE  = 'MyApp.xcworkspace'
        // Any device listed by: xcrun simctl list devices available
        DESTINATION   = 'platform=iOS Simulator,name=iPhone 17,OS=latest'
        // Relative to the job workspace, kept between builds
        DERIVED_DATA  = 'DerivedData'
    }

    options {
        timeout(time: 30, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '20'))
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }

        stage('Install Dependencies') {
            steps {
                sh '''
                    # Homebrew tools are not on the PATH of a non-interactive SSH session
                    export PATH="/opt/homebrew/bin:$PATH"

                    # Xcode comes from DEVELOPER_DIR: no sudo xcode-select in a pipeline
                    xcodebuild -version

                    # Install CocoaPods dependencies
                    if [ -f "Podfile" ]; then
                        pod install --repo-update
                    fi
                '''
            }
        }

        stage('Build') {
            steps {
                sh '''
                    # Jenkins runs sh -xe: without pipefail, xcbeautify's exit status would hide a failed build
                    set -o pipefail
                    export PATH="/opt/homebrew/bin:$PATH"
                    xcodebuild build \
                        -workspace "${XC_WORKSPACE}" \
                        -scheme "${SCHEME}" \
                        -destination "${DESTINATION}" \
                        -derivedDataPath "${DERIVED_DATA}" \
                        CODE_SIGNING_ALLOWED=NO \
                        | xcbeautify
                '''
            }
        }

        stage('Test') {
            steps {
                sh '''
                    set -o pipefail
                    export PATH="/opt/homebrew/bin:$PATH"
                    rm -rf TestResults.xcresult
                    xcodebuild test \
                        -workspace "${XC_WORKSPACE}" \
                        -scheme "${SCHEME}" \
                        -destination "${DESTINATION}" \
                        -derivedDataPath "${DERIVED_DATA}" \
                        -resultBundlePath "TestResults.xcresult" \
                        -parallel-testing-enabled YES \
                        | xcbeautify --report junit --report-path build/reports
                '''
            }
            post {
                always {
                    junit allowEmptyResults: true, testResults: 'build/reports/junit.xml'
                    archiveArtifacts artifacts: 'TestResults.xcresult/**', allowEmptyArchive: true
                }
            }
        }

        stage('Archive') {
            when {
                branch 'main'
            }
            steps {
                sh '''
                    set -o pipefail
                    export PATH="/opt/homebrew/bin:$PATH"
                    # Unsigned archive: checks that the Release build compiles.
                    # Fastlane signs and uploads the real build in Step 4.
                    xcodebuild archive \
                        -workspace "${XC_WORKSPACE}" \
                        -scheme "${SCHEME}" \
                        -archivePath "${DERIVED_DATA}/MyApp.xcarchive" \
                        -destination "generic/platform=iOS" \
                        CODE_SIGNING_ALLOWED=NO \
                        | xcbeautify
                '''
            }
        }
    }

    post {
        success {
            echo 'Build and tests passed!'
        }
        failure {
            echo 'Build or tests failed.'
        }
        cleanup {
            sh 'xcrun simctl shutdown all 2>/dev/null || true'
        }
    }
}

Passo 4: Integra Fastlane per il deployment

Fastlane semplifica la firma del codice e il deployment su TestFlight. Installalo una volta sul Mac:

# Install Fastlane on the Mac mini (one-time setup)
brew install fastlane

Aggiungi una fase di deploy al tuo Jenkinsfile:

        stage('Deploy to TestFlight') {
            when {
                branch 'main'
            }
            environment {
                APP_STORE_CONNECT_API_KEY_ID     = credentials('app-store-key-id')
                APP_STORE_CONNECT_API_ISSUER_ID  = credentials('app-store-issuer-id')
                APP_STORE_CONNECT_API_KEY_CONTENT = credentials('app-store-key-content')
                MATCH_PASSWORD                   = credentials('match-password')
            }
            steps {
                sh '''
                    export PATH="/opt/homebrew/bin:$PATH"
                    fastlane beta
                '''
            }
        }

E crea un fastlane/Fastfile corrispondente:

default_platform(:ios)

platform :ios do
  desc "Push a new beta build to TestFlight"
  lane :beta do
    setup_ci

    # Fetch code signing certificates via match
    match(type: "appstore", readonly: true)

    # Increment build number
    increment_build_number(
      build_number: ENV["BUILD_NUMBER"]
    )

    # Build the app
    build_app(
      workspace: "MyApp.xcworkspace",
      scheme: "MyApp",
      export_method: "app-store",
      derived_data_path: "DerivedData"
    )

    # Upload to TestFlight
    upload_to_testflight(
      skip_waiting_for_build_processing: true,
      api_key: app_store_connect_api_key(
        key_id: ENV["APP_STORE_CONNECT_API_KEY_ID"],
        issuer_id: ENV["APP_STORE_CONNECT_API_ISSUER_ID"],
        key_content: ENV["APP_STORE_CONNECT_API_KEY_CONTENT"]
      )
    )
  end
end

Best practice di sicurezza

  • Usa un utente Jenkins dedicato

    Non eseguire mai l'agente Jenkins come root. Crea un utente dedicato con permessi minimi.

  • Conserva i segreti in Jenkins Credentials

    Non scrivere mai certificati, chiavi API o password direttamente nei Jenkinsfile. Usa il plugin Jenkins Credentials.

  • Abilita solo l'autenticazione basata su chiave SSH

    Disabilita l'autenticazione con password per SSH. Usa chiavi Ed25519 o RSA a 4096 bit.

  • Usa il firewall di macOS

    Limita le connessioni in entrata solo all'IP del controller Jenkins. My Remote Mac fornisce un firewall gestito con accesso API.

  • Mantieni macOS e Xcode aggiornati

    Applica tempestivamente le patch di sicurezza. Usa softwareupdate -l per verificare gli aggiornamenti.

FAQ

Posso eseguire il controller Jenkins sullo stesso Mac?
Sì, ma consigliamo di separarli. Esegui il controller su una VM Linux o un container Docker e usa il Mac esclusivamente come agente di build. In questo modo eviti conflitti di risorse durante le build più pesanti.
Quante build simultanee può gestire un Mac Mini M4?
Un Mac Mini M4 con 16 GB di RAM può gestire comodamente 2 build Xcode simultanee. Con 24 GB puoi arrivare a 3. L'M4 Pro con 48 GB gestisce facilmente 4+ build simultanee. Configura di conseguenza il "Number of executors" nelle impostazioni del tuo nodo Jenkins.
Ho bisogno di una sessione GUI per i simulatori iOS?
No. I simulatori iOS funzionano in modalità headless via SSH. Tuttavia, se ti serve una GUI (ad es. per gli screenshot dei test UI), usa VNC per accedere al Mac e assicurati che una sessione GUI sia attiva.
Come gestisco la firma del codice su un server headless?
Usa Fastlane Match per sincronizzare i certificati da un repo Git o dallo storage cloud. In alternativa, importa i certificati nel portachiavi di macOS e sbloccalo nella tua pipeline usando security unlock-keychain.

Pronto a potenziare le tue build Jenkins?

Ottieni un Mac Mini M4 dedicato per la tua pipeline Jenkins CI/CD. A partire da 85 $/mese.

Prezzi My Remote Mac in USD, tasse escluse.

Cerchi maggiori dettagli?

Consulta la documentazione completa per guide passo passo, riferimenti di configurazione e risoluzione dei problemi.

Apri la documentazione →