Saltar al contenido

Cómo configurar un GitHub Actions Self-Hosted Runner en Mac Mini M4

Guía paso a paso para configurar un GitHub Actions self-hosted runner en un Mac Mini M4 dedicado. Compilaciones iOS más rápidas, Apple Silicon nativo y hasta 6,7x más económico que los runners macOS alojados en GitHub.

CI/CD 30 min de lectura Actualizado en octubre de 2026

¿Por qué usar un Self-Hosted Mac Runner?

Los runners macOS alojados en GitHub son convenientes, pero se facturan por minuto, así que el coste crece con su volumen de compilaciones. A $0.062 por minuto (tarifa del runner macOS estándar de GitHub a octubre de 2026), un equipo que ejecuta 75 horas de compilaciones al mes paga alrededor de $279. GitHub no factura los minutos de los runners self-hosted, así que un Mac mini M4 dedicado de My Remote Mac cuesta una tarifa plana de $85/mes (USD, sin impuestos), sin facturación por minuto, y le da el mismo (o mejor) hardware por una fracción del coste.

¿Por qué usar un Self-Hosted Mac Runner?
My Remote Mac Self-Hosted Runner alojado en GitHub
Coste $85/mes (sin facturación por minuto) $0.062/min (~$279/mes por 75h)
Arquitectura Apple M4, Mac físico asignado 1:1 VM Apple M1, 3 núcleos, 7 GB de RAM (runner estándar)
Velocidad de compilación ~4 min (mismo proyecto) ~12 min (proyecto mediano)
Caché persistente Sí (disco persistente) No (efímero)
Software personalizado Acceso root completo Limitado
Jobs concurrentes 1 job por runner; añada runners o Macs para escalar 5 (Free, Pro, Team) / 50 (Enterprise)

Precios de My Remote Mac en USD, sin impuestos. Cifras de GitHub: runner macOS estándar a $0.062 por minuto, según la documentación de precios de GitHub, a octubre de 2026.

Beneficio clave: Debido a que el runner es persistente, DerivedData, las cachés de SPM y CocoaPods se preservan entre compilaciones. Esto por sí solo puede reducir los tiempos de compilación en un 50-70% comparado con los runners efímeros alojados en GitHub que comienzan desde cero cada vez.

Requisitos previos

Antes de comenzar, asegúrese de tener lo siguiente:

  • Un servidor de build Mac mini M4 dedicado de My Remote Mac (desde $85/mes, USD, sin impuestos)
  • Una cuenta de GitHub con acceso de administrador a su repositorio u organización
  • Acceso SSH a su Mac Mini (incluido con su suscripción de My Remote Mac)
  • Una cuenta de Apple Developer (para la firma de código y perfiles de aprovisionamiento)
  • Familiaridad básica con YAML y comandos de terminal

Paso 1: Conectarse por SSH al Mac Mini y comprobar Xcode

Primero, conéctese a su Mac Mini M4 por SSH. Habrá recibido sus credenciales al configurar su servidor My Remote Mac.

Conectarse por SSH

# Connect to your Mac Mini M4
ssh admin@your-server-ip

# Verify you're on Apple Silicon
uname -m
# Expected output: arm64

# Check the macOS version
sw_vers

Comprobar Xcode Command Line Tools

# Xcode and its Command Line Tools come preinstalled
xcode-select -p
# /Applications/Xcode.app/Contents/Developer

# Accept the Xcode license if it asks
sudo xcodebuild -license accept

# Homebrew is preinstalled too (used below to add xcodes):
# put it on your PATH once per account
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
eval "$(/opt/homebrew/bin/brew shellenv)"
brew --version

Comprobar Xcode y añadir otras versiones

Xcode, sus Command Line Tools y Homebrew vienen preinstalados en todos los servidores de My Remote Mac. Compruebe la versión activa e instale otras versiones en paralelo con xcodes si su proyecto las necesita:

# Check the preinstalled Xcode
xcodebuild -version
# Xcode 27.2

# Optional: add other Xcode releases side by side with the xcodes CLI
brew install xcodes

# List available Xcode versions
xcodes list

# Install an older release next to the preinstalled one (asks for your Apple Account)
xcodes install 26.6

# Show the installed versions and their paths
xcodes installed
# e.g. /Applications/Xcode.app and /Applications/Xcode-26.6.0.app

# Set the active Xcode (interactive SSH session: sudo asks for your password)
# preinstalled Xcode; for another version, use the path from xcodes installed
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer

Instalar simuladores iOS

# Install the iOS simulator runtime that matches your Xcode
xcodebuild -downloadPlatform iOS

# Verify simulator availability
xcrun simctl list runtimes
xcrun simctl list devices available

Paso 2: Instalar el GitHub Actions Runner

Ahora vamos a descargar y configurar el agente GitHub Actions runner. Navegue a su repositorio en GitHub, vaya a Settings > Actions > Runners > New self-hosted runner y seleccione macOS + ARM64.

Descargar y configurar

# Create a directory for the runner
mkdir -p ~/actions-runner && cd ~/actions-runner

# Download the latest runner package (macOS ARM64). The same commands, with the
# current version and its checksum, are shown on Settings > Actions > Runners >
# New self-hosted runner
RUNNER_VERSION=$(curl -fsSL https://api.github.com/repos/actions/runner/releases/latest \
  | sed -n 's/.*"tag_name": *"v\([^"]*\)".*/\1/p')
curl -o "actions-runner-osx-arm64-${RUNNER_VERSION}.tar.gz" -L \
  "https://github.com/actions/runner/releases/download/v${RUNNER_VERSION}/actions-runner-osx-arm64-${RUNNER_VERSION}.tar.gz"

# Extract the package
tar xzf "actions-runner-osx-arm64-${RUNNER_VERSION}.tar.gz"

# Configure the runner
# Replace YOUR_TOKEN with the token from GitHub Settings
./config.sh --url https://github.com/YOUR_ORG/YOUR_REPO \
  --token YOUR_TOKEN \
  --name "mac-mini-m4-runner" \
  --labels "self-hosted,macOS,ARM64,M4" \
  --work "_work"

# Test the runner interactively first
./run.sh

Instalar como un servicio launchd persistente

Ejecutar el agente de forma interactiva está bien para pruebas, pero para producción necesita que se inicie automáticamente y se reinicie si falla. GitHub proporciona un script de instalación de servicio integrado para macOS:

# Install as a launchd service (a LaunchAgent; no sudo on macOS)
cd ~/actions-runner
./svc.sh install

# Start the service
./svc.sh start

# Check the service status
./svc.sh status

# View the launchd plist (for reference)
cat ~/Library/LaunchAgents/actions.runner.*.plist

Ahora el servicio se inicia cada vez que se abre la sesión del usuario del runner y reinicia el runner si el proceso muere. Un LaunchAgent no arranca por sí solo al encender el Mac: en un Mac headless, active el inicio de sesión automático para ese usuario (Ajustes del Sistema > Usuarios y grupos; no disponible mientras FileVault esté activado) para que el runner vuelva a estar en línea tras un reinicio. Puede verificar que el runner aparezca como "Idle" en la página Settings > Actions > Runners de su repositorio de GitHub.

Configurar el Runner para múltiples repositorios (nivel de organización)

# For an organization-level runner, use the organization URL:
./config.sh --url https://github.com/YOUR_ORG \
  --token YOUR_ORG_TOKEN \
  --name "mac-mini-m4-org-runner" \
  --labels "self-hosted,macOS,ARM64,M4" \
  --runnergroup "Default" \
  --work "_work"

# This allows ALL repositories in your organization to use this runner

Paso 3: Crear su workflow de compilación iOS

Cree un archivo de workflow en su repositorio en .github/workflows/ios-build.yml. Este workflow se ejecutará en su Mac Mini M4 self-hosted runner.

name: iOS Build & Test

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

jobs:
  build:
    runs-on: [self-hosted, macOS, ARM64, M4]

    # bash -eo pipefail: a failing xcodebuild fails the step even when piped to xcbeautify
    defaults:
      run:
        shell: bash

    env:
      SCHEME: "MyApp"
      # Any device listed by: xcrun simctl list devices available
      DESTINATION: "platform=iOS Simulator,name=iPhone 17,OS=latest"
      # Pick the Xcode for this job without sudo
      # (preinstalled Xcode; for another version, use the path from xcodes installed)
      DEVELOPER_DIR: /Applications/Xcode.app/Contents/Developer
      # Caches sit next to the checkout: actions/checkout cleans the checkout
      # (git clean -ffdx) on every run, but not its parent folder
      DERIVED_DATA: ${{ github.workspace }}/../DerivedData
      SPM_CACHE: ${{ github.workspace }}/../SourcePackages

    steps:
      - name: Checkout code
        uses: actions/checkout@v7

      - name: Show the selected Xcode
        run: xcodebuild -version

      - name: Resolve Swift Package Dependencies
        run: |
          xcodebuild -resolvePackageDependencies \
            -scheme "$SCHEME" \
            -clonedSourcePackagesDirPath "$SPM_CACHE"

      - name: Install xcbeautify
        run: command -v xcbeautify >/dev/null || brew install xcbeautify

      - name: Build the app
        run: |
          xcodebuild build \
            -scheme "$SCHEME" \
            -destination "$DESTINATION" \
            -clonedSourcePackagesDirPath "$SPM_CACHE" \
            -derivedDataPath "$DERIVED_DATA" \
            | xcbeautify

      - name: Run unit tests
        run: |
          xcodebuild test \
            -scheme "$SCHEME" \
            -destination "$DESTINATION" \
            -clonedSourcePackagesDirPath "$SPM_CACHE" \
            -derivedDataPath "$DERIVED_DATA" \
            -resultBundlePath TestResults.xcresult \
            | xcbeautify

      - name: Upload test results
        if: always()
        uses: actions/upload-artifact@v7
        with:
          name: test-results
          path: TestResults.xcresult

Añadir firma de código para compilaciones de release

Para despliegues en TestFlight o App Store, añada pasos de firma de código. Almacene sus certificados y perfiles de aprovisionamiento como GitHub Secrets:

  deploy:
    needs: build
    runs-on: [self-hosted, macOS, ARM64, M4]
    if: github.ref == 'refs/heads/main'

    env:
      # Same Xcode as the build job (App Store Connect requires Xcode 26 or later)
      DEVELOPER_DIR: /Applications/Xcode.app/Contents/Developer

    steps:
      - name: Checkout code
        uses: actions/checkout@v7

      - name: Install certificate and provisioning profile
        env:
          BUILD_CERTIFICATE_BASE64: ${{ secrets.BUILD_CERTIFICATE_BASE64 }}
          P12_PASSWORD: ${{ secrets.P12_PASSWORD }}
          BUILD_PROVISION_PROFILE_BASE64: ${{ secrets.BUILD_PROVISION_PROFILE_BASE64 }}
          KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
        run: |
          # Create a temporary keychain
          KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db
          security create-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
          security set-keychain-settings -lut 21600 $KEYCHAIN_PATH
          security unlock-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH

          # Import certificate
          CERTIFICATE_PATH=$RUNNER_TEMP/build_certificate.p12
          echo -n "$BUILD_CERTIFICATE_BASE64" | base64 --decode -o $CERTIFICATE_PATH
          security import $CERTIFICATE_PATH -P "$P12_PASSWORD" \
            -A -t cert -f pkcs12 -k $KEYCHAIN_PATH
          security list-keychain -d user -s $KEYCHAIN_PATH

          # Install provisioning profile (the folder Xcode 16 and later read)
          PP_PATH=$RUNNER_TEMP/build_pp.mobileprovision
          echo -n "$BUILD_PROVISION_PROFILE_BASE64" | base64 --decode -o $PP_PATH
          mkdir -p ~/Library/Developer/Xcode/UserData/Provisioning\ Profiles
          cp $PP_PATH ~/Library/Developer/Xcode/UserData/Provisioning\ Profiles

      - name: Build for distribution
        run: |
          xcodebuild archive \
            -scheme "MyApp" \
            -archivePath DerivedData/MyApp.xcarchive \
            -destination "generic/platform=iOS" \
            CODE_SIGN_STYLE=Manual

      - name: Export IPA
        run: |
          xcodebuild -exportArchive \
            -archivePath DerivedData/MyApp.xcarchive \
            -exportOptionsPlist ExportOptions.plist \
            -exportPath DerivedData/Export

      - name: Upload to TestFlight
        env:
          APP_STORE_CONNECT_API_KEY: ${{ secrets.APP_STORE_CONNECT_API_KEY }}
          APP_STORE_CONNECT_ISSUER_ID: ${{ secrets.APP_STORE_CONNECT_ISSUER_ID }}
        run: |
          # altool reads the key from ~/.appstoreconnect/private_keys/AuthKey_<KEY_ID>.p8
          xcrun altool --upload-app \
            -f DerivedData/Export/MyApp.ipa \
            -t ios \
            --apiKey $APP_STORE_CONNECT_API_KEY \
            --apiIssuer $APP_STORE_CONNECT_ISSUER_ID

      # The runner is persistent: remove the signing files at the end of every job
      - name: Clean up keychain and provisioning profile
        if: ${{ always() }}
        run: |
          security delete-keychain $RUNNER_TEMP/app-signing.keychain-db || true
          rm -f ~/Library/Developer/Xcode/UserData/Provisioning\ Profiles/build_pp.mobileprovision

Paso 4: Optimizar el rendimiento

Una de las mayores ventajas de un self-hosted runner es la caché persistente. Aquí tiene las optimizaciones clave para sacar el máximo provecho de su Mac Mini M4.

Habilitar caché de DerivedData

Como el runner es persistente, DerivedData se preserva entre compilaciones. Use una ruta de DerivedData consistente:

# In your workflow, keep DerivedData next to the checkout (job env, as above):
#   DERIVED_DATA: ${{ github.workspace }}/../DerivedData
#   ... -derivedDataPath "$DERIVED_DATA"
# Each repository then gets ~/actions-runner/_work/<repo>/DerivedData

# On the runner, remove the DerivedData of repositories not built for 7 days
# (cron job every Sunday at 03:00, keeps your existing crontab entries)
(crontab -l 2>/dev/null; echo '0 3 * * 0 find "$HOME"/actions-runner/_work/*/DerivedData -maxdepth 0 -type d -mtime +7 -exec rm -rf {} +') \
  | crontab -

Cachear paquetes SPM

# Use clonedSourcePackagesDirPath to keep SPM packages on disk
# (SPM_CACHE points outside the checkout, as in the workflow above)
xcodebuild build \
  -scheme "MyApp" \
  -clonedSourcePackagesDirPath "$SPM_CACHE" \
  -derivedDataPath "$DERIVED_DATA"

# This avoids re-downloading packages on every build

Ejecución paralela de pruebas

# Run tests in parallel across multiple simulators
# (devices from: xcrun simctl list devices available)
set -o pipefail
xcodebuild test \
  -scheme "MyApp" \
  -destination "platform=iOS Simulator,name=iPhone 17,OS=latest" \
  -destination "platform=iOS Simulator,name=iPhone 18 Pro,OS=latest" \
  -parallel-testing-enabled YES \
  -maximum-parallel-testing-workers 4 \
  -derivedDataPath "$DERIVED_DATA" \
  | xcbeautify

Instalar xcbeautify para mejores logs

# xcbeautify formats Xcode output for CI environments
brew install xcbeautify

# Use it by piping xcodebuild output (pipefail keeps xcodebuild's exit status):
set -o pipefail && xcodebuild build -scheme "MyApp" | xcbeautify

Solución de problemas comunes

El Runner aparece como "Offline" en GitHub

Esto generalmente significa que el servicio launchd no está ejecutándose. Verifique el estado del servicio y los logs:

# Check service status
./svc.sh status

# View logs
cat ~/actions-runner/_diag/Runner_*.log | tail -50

# Restart the service
./svc.sh stop
./svc.sh start

La firma de código falla con "No signing certificate"

El servicio launchd se ejecuta bajo un contexto de usuario diferente. Asegúrese de que el keychain sea accesible:

# Ensure the login keychain is unlocked for the runner user
security unlock-keychain -p "YOUR_PASSWORD" ~/Library/Keychains/login.keychain-db

# Or use a dedicated keychain in your workflow (recommended)
security create-keychain -p "$KEYCHAIN_PASSWORD" build.keychain
security default-keychain -s build.keychain
security unlock-keychain -p "$KEYCHAIN_PASSWORD" build.keychain

El simulador no arranca

Los simuladores a veces se atascan. Reinícielos entre compilaciones:

# Shutdown all running simulators
xcrun simctl shutdown all

# Erase all simulator data (nuclear option)
xcrun simctl erase all

# Boot a specific simulator
xcrun simctl boot "iPhone 17"

Espacio en disco insuficiente

Las compilaciones de Xcode generan muchos datos. Configure una limpieza automática:

# Clean old DerivedData
rm -rf ~/Library/Developer/Xcode/DerivedData/*

# Remove simulators whose runtime is no longer installed
xcrun simctl delete unavailable

# Clean Homebrew cache
brew cleanup --prune=7

# Remove old Xcode archives
rm -rf ~/Library/Developer/Xcode/Archives/*

Análisis de costes

Aquí tiene una comparación detallada de costes para diferentes tamaños de equipo y volúmenes de compilación:

Análisis de costes
Tamaño del equipo Coste My Remote Mac Compilaciones/Mes Coste alojado en GitHub Ahorro mensual
Desarrollador individual $85/mes 100 compilaciones (10 min promedio) $62/mes Ninguno (cuesta $23/mes más)
Equipo pequeño (5) $85/mes 500 compilaciones (10 min promedio) $310/mes $225/mes
Equipo mediano (15) $229/mes (M4 Pro) 1500 compilaciones (10 min promedio) $930/mes $701/mes
Empresa (50+) $458/mes (2x M4 Pro) 5000+ compilaciones $3,100+/mes $2,642+/mes

Precios de My Remote Mac en USD, sin impuestos. Cifras de GitHub: runner macOS estándar a $0.062 por minuto, según la documentación de precios de GitHub, a octubre de 2026.

Conclusión: Para equipos que ejecutan más de ~140 compilaciones por mes, un Mac Mini M4 self-hosted se amortiza de inmediato. Y como las compilaciones son más rápidas en hardware persistente con cachés precargadas, su equipo también ahorra tiempo de desarrollo. Con 100 compilaciones al mes, como en la fila Desarrollador individual, los runners alojados en GitHub cuestan $23/mes menos; aun así, un desarrollador individual puede preferir un Mac dedicado por sus cachés persistentes, sus compilaciones más rápidas y la ausencia de facturación por minuto. Si solo publica de vez en cuando, el plan diario le da un Mac para el día del lanzamiento desde $14 por 24 horas (USD, sin impuestos): desactive la renovación automática al desplegar y se detendrá a las 24 horas, o pásese al plan mensual en el mismo Mac.

¿Listo para acelerar sus compilaciones iOS?

Despliegue un Mac Mini M4 dedicado como su GitHub Actions runner. Desde $85/mes.

Precios de My Remote Mac en USD, sin impuestos.

¿Buscas más detalles?

Explora la documentación completa: guías paso a paso, referencias de configuración y resolución de problemas.

Abrir la documentación →