Pourquoi des runners GitLab auto-hébergés sur Mac ?
GitLab propose des runners partagés sur Linux, mais compiler des applications iOS nécessite macOS sur du matériel Apple. Les runners macOS partagés de GitLab sont limités et coûteux. Un runner Mac Mini M4 auto-hébergé vous offre :
-
Minutes CI/CD illimitées
L'offre gratuite de GitLab inclut 400 minutes CI/CD sur les runners partagés. En auto-hébergé, il n'y a aucune limite.
-
Apple Silicon natif
Compilez sur la même puce M4 que celle des appareils de vos utilisateurs. Aucune surcharge de traduction Rosetta.
-
Contrôle total de l'environnement
Installez n'importe quelle version de Xcode, des simulateurs, des outils et des dépendances dont vous avez besoin.
-
Caches persistants
DerivedData, les paquets SPM et les caches CocoaPods survivent entre les exécutions de pipeline.
Installer le runner GitLab
Connectez-vous en SSH à votre serveur de build Mac mini M4 dédié et installez le runner GitLab, ainsi que xcbeautify pour des journaux de build lisibles, avec Homebrew :
# Connect to your Mac Mini M4
ssh admin@your-server-ip
# 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 GitLab Runner with Homebrew, plus xcbeautify for the pipeline's build logs
brew install gitlab-runner xcbeautify
# Verify installation (prints the version and OS/Arch: darwin/arm64)
gitlab-runner --version
Installer en tant que service macOS
# Run the runner as a launchd service. It is a LaunchAgent: it starts when
# your user session starts, so on a headless Mac enable automatic login for
# this user (System Settings > Users & Groups) to bring it back after a reboot
brew services start gitlab-runner
# Verify the service is running
brew services list | grep gitlab-runner
# gitlab-runner started admin ~/Library/LaunchAgents/homebrew.mxcl.gitlab-runner.plist
Enregistrer le runner
Ouvrez votre projet GitLab, allez dans Settings > CI/CD > Runners, puis sélectionnez Create project runner (pour un groupe : Build > Runners > Create group runner). Dans Tags, saisissez macos et m4 (le pipeline ci-dessous cible ces tags), créez le runner, puis copiez son jeton d'authentification, qui commence par glrt-. Avec un jeton d'authentification, la commande register n'accepte ni les tags ni les autres options du runner : vous les réglez ici, dans GitLab. Pour automatiser cette étape, créez le runner par l'API (exemple ci-dessous).
Enregistrer avec un jeton d'authentification de runner
# Optional: create the runner with the API instead of the GitLab UI.
# Needs an access token with the create_runner scope; the "token"
# field of the response is the runner authentication token (glrt-...)
curl --request POST \
--header "PRIVATE-TOKEN: YOUR_ACCESS_TOKEN" \
--url "https://gitlab.com/api/v4/user/runners" \
--data "runner_type=project_type" \
--data "project_id=YOUR_PROJECT_ID" \
--data "tag_list=macos,m4" \
--data "run_untagged=false"
# Register the runner with its authentication token (starts with glrt-).
# Tags, untagged jobs and locking come from the runner you created in GitLab:
# do not pass --tag-list or --run-untagged with an authentication token
gitlab-runner register \
--non-interactive \
--url "https://gitlab.com/" \
--token "YOUR_RUNNER_AUTHENTICATION_TOKEN" \
--executor "shell" \
--name "mac-mini-m4-runner"
# Confirm the runner can reach GitLab
gitlab-runner verify
Ancienne méthode : enregistrer avec un jeton d'enregistrement
Les jetons d'enregistrement sont obsolètes depuis GitLab 15.6, et GitLab prévoit de les supprimer dans GitLab 20.0. Depuis GitLab 17.0, ils ne fonctionnent que si un administrateur (ou, sur GitLab.com, le propriétaire du groupe de premier niveau) les a réactivés. N'utilisez cette méthode que sur une instance qui l'exige encore.
# Legacy: registration token (deprecated since GitLab 15.6,
# removal scheduled for GitLab 20.0). On GitLab 17.0 and later,
# it works only where registration tokens were enabled again.
gitlab-runner register \
--non-interactive \
--url "https://gitlab.example.com/" \
--registration-token "YOUR_REGISTRATION_TOKEN" \
--executor "shell" \
--description "mac-mini-m4-runner" \
--tag-list "macos,apple-silicon,m4,ios,xcode" \
--run-untagged="false"
Vérifier la configuration du runner
# View the runner config file
cat ~/.gitlab-runner/config.toml
# Expected output:
# concurrent = 2
# check_interval = 0
#
# [session_server]
# session_timeout = 1800
#
# [[runners]]
# name = "mac-mini-m4-runner"
# url = "https://gitlab.com/"
# token = "..."
# executor = "shell"
# [runners.cache]
# MaxUploadedArchiveSize = 0
# Adjust concurrency based on your hardware:
# Mac Mini M4 (16GB): concurrent = 2
# Mac Mini M4 Pro (24GB): concurrent = 3
# Mac Mini M4 Pro (48GB): concurrent = 4
Éditez ~/.gitlab-runner/config.toml pour ajuster la concurrence :
# Edit the config
nano ~/.gitlab-runner/config.toml
# Set concurrent to match your hardware capacity
concurrent = 2
# Restart the service to apply changes
brew services restart gitlab-runner
Le runner devrait maintenant apparaître comme En ligne dans votre projet GitLab sous Settings > CI/CD > Runners.
Créer un .gitlab-ci.yml pour iOS
Créez un fichier .gitlab-ci.yml à la racine de votre dépôt. Ce pipeline complet compile, teste et déploie votre application iOS :
# .gitlab-ci.yml
stages:
- build
- test
- deploy
variables:
SCHEME: "MyApp"
WORKSPACE: "MyApp.xcworkspace"
# Any device listed by: xcrun simctl list devices available
DESTINATION: "platform=iOS Simulator,name=iPhone 17,OS=latest"
# Pick the Xcode for every job without sudo
# (preinstalled Xcode; for another version, use the path from xcodes installed)
DEVELOPER_DIR: "/Applications/Xcode.app/Contents/Developer"
# Only run on our Mac runner
default:
tags:
- macos
- m4
before_script:
# The runner cleans the checkout (git clean -ffdx) before each job, so keep
# DerivedData outside it: one warm folder per project and concurrent job slot
- export DERIVED_DATA="${CI_BUILDS_DIR}/DerivedData/${CI_PROJECT_PATH_SLUG}-${CI_CONCURRENT_PROJECT_ID}"
- xcodebuild -version
# Pods/ is removed with the rest of the checkout's untracked files: reinstall it
- |
if [ -f "Podfile" ]; then
pod install
fi
# ---- BUILD ----
build:
stage: build
script:
- |
xcodebuild build \
-workspace "${WORKSPACE}" \
-scheme "${SCHEME}" \
-destination "${DESTINATION}" \
-derivedDataPath "${DERIVED_DATA}" \
CODE_SIGNING_ALLOWED=NO \
| xcbeautify
# ---- TEST ----
unit_tests:
stage: test
needs: ["build"]
script:
- |
xcodebuild test \
-workspace "${WORKSPACE}" \
-scheme "${SCHEME}" \
-destination "${DESTINATION}" \
-derivedDataPath "${DERIVED_DATA}" \
-resultBundlePath "TestResults.xcresult" \
-parallel-testing-enabled YES \
| xcbeautify --report junit --report-path build/reports
artifacts:
when: always
paths:
- TestResults.xcresult/
reports:
junit: build/reports/junit.xml
expire_in: 7 days
after_script:
- xcrun simctl shutdown all 2>/dev/null || true
# ---- DEPLOY ----
deploy_testflight:
stage: deploy
needs: ["unit_tests"]
rules:
- if: $CI_COMMIT_BRANCH == "main"
script:
- |
# Install or update Fastlane
which fastlane || brew install fastlane
# Run Fastlane beta lane
fastlane beta
environment:
name: testflight
variables:
MATCH_PASSWORD: ${MATCH_PASSWORD}
# Names read by fastlane's app_store_connect_api_key action (call it in your lane)
APP_STORE_CONNECT_API_KEY_KEY_ID: ${APP_STORE_KEY_ID}
APP_STORE_CONNECT_API_KEY_ISSUER_ID: ${APP_STORE_ISSUER_ID}
APP_STORE_CONNECT_API_KEY_KEY: ${APP_STORE_KEY_CONTENT}
Ajouter des variables CI/CD dans GitLab
Naviguez vers Settings > CI/CD > Variables dans votre projet GitLab et ajoutez ces variables en tant que "Masquées" et "Protégées" :
MATCH_PASSWORD: Mot de passe pour le chiffrement Fastlane MatchAPP_STORE_KEY_ID: ID de clé API App Store ConnectAPP_STORE_ISSUER_ID: Issuer ID App Store ConnectAPP_STORE_KEY_CONTENT: Contenu du fichier de clé .p8
Optimiser les performances
Configuration du cache GitLab
Sur un Mac persistant, le cache le plus rapide est celui que GitLab n'a pas à déplacer : le pipeline ci-dessus garde DerivedData hors du checkout, il reste donc chaud d'un job à l'autre. Avec l'exécuteur shell, le cache de GitLab est compressé puis décompressé à chaque job : réservez-le aux petits dossiers comme Pods/ :
# DerivedData already stays on disk outside the checkout (DERIVED_DATA above).
# Use GitLab's cache for small folders, keyed on the lockfile:
build:
cache:
key:
files:
- Podfile.lock
paths:
- Pods/
policy: pull-push
# For test jobs that don't modify the cache, use pull-only:
unit_tests:
cache:
key:
files:
- Podfile.lock
paths:
- Pods/
policy: pull
Utiliser les artefacts pour les données inter-stages
# Useful when the build and test jobs can run on different Macs.
# build-for-testing compiles the app and its test bundles once; artifacts must
# sit inside the project folder, so this job builds there
build:
script:
- |
xcodebuild build-for-testing \
-workspace "${WORKSPACE}" \
-scheme "${SCHEME}" \
-destination "${DESTINATION}" \
-derivedDataPath build/DerivedData \
| xcbeautify
artifacts:
paths:
- build/DerivedData/Build/Products/
expire_in: 2 hours
# The test stage receives the built products and runs them without rebuilding
unit_tests:
needs: ["build"] # downloads the build job's artifacts
script:
- |
xcodebuild test-without-building \
-xctestrun build/DerivedData/Build/Products/*.xctestrun \
-destination "${DESTINATION}" \
| xcbeautify
Exécution parallèle des tests
# On one Mac, let xcodebuild split the test classes across simulator clones.
# (GitLab's parallel: keyword only helps if each copy runs a different part of
# the suite, using CI_NODE_INDEX and CI_NODE_TOTAL; otherwise it repeats it.)
unit_tests:
stage: test
script:
- |
xcodebuild test \
-workspace "${WORKSPACE}" \
-scheme "${SCHEME}" \
-destination "${DESTINATION}" \
-derivedDataPath "${DERIVED_DATA}" \
-parallel-testing-enabled YES \
-maximum-parallel-testing-workers 4 \
| xcbeautify
Nettoyage planifié du cache
# On the Mac Mini, set up a weekly cleanup cron job
crontab -e
# Add these lines:
# Every Sunday at 3 AM, remove DerivedData folders not used for 7 days
# (the pipeline keeps them in ~/builds/DerivedData, one per project and slot)
0 3 * * 0 find ~/builds/DerivedData -mindepth 1 -maxdepth 1 -type d -mtime +7 -exec rm -rf {} + 2>/dev/null
# Checkouts in ~/builds are reused by the next job (git fetch): no need to delete them
# Clean Homebrew cache monthly
0 5 1 * * /opt/homebrew/bin/brew cleanup --prune=30 2>/dev/null
Résolution des problèmes
Le runner apparaît "hors ligne" dans GitLab
Le runner tourne en tant que LaunchAgent : il démarre à l'ouverture de votre session et reste hors ligne après un redémarrage tant que cet utilisateur ne s'est pas connecté. Sur un Mac sans écran, activez l'ouverture de session automatique pour cet utilisateur (Réglages Système > Utilisateurs et groupes ; indisponible tant que FileVault est activé). Vérifiez ensuite l'état du service du runner et les journaux :
# Check service status
brew services list | grep gitlab-runner
# View logs
cat /opt/homebrew/var/log/gitlab-runner.log
# Restart the service
brew services restart gitlab-runner
# Verify connectivity to GitLab
gitlab-runner verify
Erreurs de permission refusée pendant les builds
Le runner peut avoir besoin d'accéder au répertoire développeur Xcode :
# Ensure the runner user has Xcode access (run once, in your SSH session)
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
sudo xcodebuild -license accept
# If using simulators, ensure the user can access them
xcrun simctl list devices
Le cache n'est pas restauré
Assurez-vous que les clés de cache sont cohérentes et que les chemins existent :
# Check cache directory permissions
ls -la ~/builds/
# The shell executor stores caches locally by default
# Verify the cache directory in config.toml:
cat ~/.gitlab-runner/config.toml
# Ensure [runners.cache] section has the right settings
# For local caching (most efficient for persistent runners):
# [runners.cache]
# Type = "" # empty = local cache
Le build Xcode se bloque ou expire
C'est souvent causé par des invites d'accès au trousseau ou des problèmes de simulateur :
# Unlock the keychain before builds
security unlock-keychain -p "YOUR_PASSWORD" ~/Library/Keychains/login.keychain-db
# Kill stuck simulators
xcrun simctl shutdown all
killall -9 com.apple.CoreSimulator.CoreSimulatorService 2>/dev/null || true
# Set a build timeout in .gitlab-ci.yml
build:
timeout: 30 minutes
FAQ
Puis-je utiliser un exécuteur Docker sur macOS ?
Comment enregistrer le runner pour un groupe GitLab ?
Dois-je utiliser l'exécuteur shell ou l'exécuteur SSH ?
Puis-je exécuter les runners GitLab et GitHub Actions sur le même Mac ?
Comment mettre à jour le runner GitLab ?
# Update via Homebrew
brew upgrade gitlab-runner
# Restart the service
brew services restart gitlab-runner
# Verify the new version
gitlab-runner --version