¿Por qué un Mac dedicado para Jenkins?
Jenkins es la plataforma CI/CD más utilizada, ejecutando más del 50% de los pipelines de compilación empresariales. Sin embargo, compilar apps iOS con Jenkins requiere macOS, y macOS solo puede ejecutarse legalmente en hardware Apple. Un Mac Mini M4 dedicado le ofrece:
-
Entorno de compilación consistente
Mismo hardware, mismo SO, mismas herramientas en cada compilación. Sin compilaciones inestables por deriva del entorno.
-
Acceso root completo
Instale cualquier herramienta, configure los ajustes del sistema, gestione keychains para la firma de código.
-
Rendimiento Apple Silicon
El chip M4 ofrece compilaciones Xcode 2-3x más rápidas comparado con Mac Minis Intel.
-
Cachés persistentes
Las cachés de DerivedData, CocoaPods y SPM sobreviven entre compilaciones.
Requisitos previos
- Un servidor de build Mac mini M4 dedicado de My Remote Mac (desde $85/mes, USD, sin impuestos)
- Un controlador Jenkins (puede estar en Linux, Docker o cualquier VM en la nube)
- Acceso SSH a su Mac Mini
- Xcode, preinstalado en todos los servidores de My Remote Mac (nuestra guía de GitHub Actions muestra cómo comprobarlo y añadir otras versiones)
Paso 1: Instalar Java JDK en macOS
Los agentes Jenkins requieren un Java Runtime Environment. Las versiones actuales de Jenkins admiten Java 21 y Java 25 (Java 17 ya no es compatible), así que instalamos JDK 21 (LTS) vía Homebrew para una gestión fácil.
# 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
Paso 2: Configurar el agente Jenkins
Hay dos métodos principales para conectar un agente Jenkins: un agente entrante (el agente se conecta al controlador; antes llamado JNLP) y SSH (el controlador se conecta al agente). Cubrimos ambos.
Método A: Agente SSH (Recomendado)
Este es el enfoque más fiable. Jenkins se conecta al Mac por SSH y gestiona el proceso del agente de forma remota.
# 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
Ahora configure el agente en Jenkins:
- Vaya a Manage Jenkins > Nodes > New Node
- Establezca el nombre como
mac-mini-m4 - Establezca Remote root directory como
/Users/jenkins/workspace - Labels:
mac macos apple-silicon m4 ios - Método de lanzamiento: Launch agents via SSH
- Host: La dirección IP de su Mac Mini
- Credenciales: Añada la clave privada SSH que coincida con las authorized_keys del Mac
- Host Key Verification Strategy: Known hosts file Verification Strategy. Antes del primer arranque, conéctese una vez desde el controlador con el usuario que ejecuta Jenkins (
ssh jenkins@YOUR_MAC_IP) para añadir el Mac a su~/.ssh/known_hosts
Método B: Agente entrante (WebSocket)
Use este método cuando el controlador Jenkins no pueda alcanzar el Mac directamente (p. ej., el Mac está detrás de un firewall). El agente inicia la conexión. Con la opción -webSocket solo usa el puerto web del controlador (HTTP o HTTPS), sin un puerto TCP de agente aparte.
# 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"
Ejecutar el agente entrante como un servicio launchd
El agente se ejecuta como LaunchAgent del usuario jenkins, así que arranca cuando se inicia la sesión de ese usuario, no al encender el Mac. En un Mac headless, active el inicio de sesión automático para el usuario jenkins (Ajustes del Sistema > Usuarios y grupos; no disponible mientras FileVault esté activado) para que el agente vuelva a estar en línea tras un reinicio. Esa sesión iniciada también da a los simuladores, a las pruebas de UI y al llavero de inicio de sesión el entorno de usuario que necesitan.
# 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
Paso 3: Crear un pipeline de compilación iOS
Cree un Jenkinsfile en la raíz de su repositorio. Este pipeline declarativo compila, prueba y opcionalmente archiva su 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'
}
}
}
Paso 4: Integrar Fastlane para el despliegue
Fastlane simplifica la firma de código y el despliegue en TestFlight. Instálelo una vez en el Mac:
# Install Fastlane on the Mac mini (one-time setup)
brew install fastlane
Añada una etapa de despliegue a su 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
'''
}
}
Y cree un fastlane/Fastfile correspondiente:
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
Mejores prácticas de seguridad
-
Usar un usuario dedicado de Jenkins
Nunca ejecute el agente Jenkins como root. Cree un usuario dedicado con permisos mínimos.
-
Almacenar secretos en Jenkins Credentials
Nunca codifique certificados, claves API o contraseñas directamente en los Jenkinsfiles. Use el plugin Jenkins Credentials.
-
Habilitar solo autenticación por clave SSH
Deshabilite la autenticación por contraseña para SSH. Use claves Ed25519 o RSA de 4096 bits.
-
Usar el firewall de macOS
Restrinja las conexiones entrantes solo a la IP del controlador Jenkins. My Remote Mac proporciona un firewall gestionado con acceso API.
-
Mantener macOS y Xcode actualizados
Aplique los parches de seguridad de forma oportuna. Use
softwareupdate -lpara verificar las actualizaciones.
Preguntas frecuentes
¿Puedo ejecutar el controlador Jenkins en el mismo Mac?
¿Cuántas compilaciones concurrentes puede manejar un Mac Mini M4?
¿Necesito una sesión GUI para simuladores iOS?
¿Cómo manejo la firma de código en un servidor headless?
security unlock-keychain.