Apple Silicon iOS CI with Jenkins and Fastlane: The PollSCM 'H/1' Trap That Silently Stalls Builds
Building iOS CI on Apple Silicon Mac with Jenkins + Fastlane: From Auto-Packaging to MR Check Pipeline
A complete record of setting up iOS CI: local Jenkins + Fastlane for automatic packaging after push, multi-branch pipelines for SwiftLint checks on feature branches. Along the way I hit many pitfalls, including the
pollSCM('H/1')semantics trap, broken brew bottles, and missing plugin dependencies. The whole setup requires no public server, is purely polling-driven, and is suitable for individuals/small teams.Environment: Apple Silicon Mac (macOS 26/27), Xcode 27, CocoaPods project, code hosted on Gitee (private repo)
1. Goals and Overall Architecture
Goals:
- When
developbranch gets a push, auto-package within 1 minute (ipa lands in a specified directory) - Before merging a feature branch MR, automatically run SwiftLint + compile validation, only allow merge when green
Final architecture (no public callback, all polling):
feature/* branch push ──▶ Jenkins multi-branch pipeline (scans every minute)
│ auto generates a separate job for each feature/* branch
▼
SwiftLint check → pod install → simulator compile validation
(no ipa, no code signing certificates, ~1 minute)
│
Check branch job green before MR, only merge when green
│ merge
▼
develop packaging pipeline (pollSCM polls every minute) → Fastlane builds
▼
ipa auto-copied to project directory / archive dSYM
2. Dependency Installation (Most Pitfalls Here)
2.1 JDK: jenkins-lts depends on 21, not 17
brew install openjdk@21 jenkins-lts
New Jenkins LTS requires JDK 21, no need to install 17 separately. openjdk@21 is keg-only, remember to write JAVA_HOME into shell config.
2.2 macOS 26.x: All brew bottles fail to extract
Homebrew 7's bottle extraction depends on sandbox-exec, which has been disabled on macOS 26.x. Symptoms: every package that uses bottles fails directly. Verify with:
/usr/bin/sandbox-exec -p '(version 1)(allow default)' echo
# no output = affected
Self-heals after system upgrade. Temporary workaround: use pkg installers (e.g., brew install --cask temurin@21).
2.3 brew's fastlane bottle is broken
The fastlane installed via brew is missing gems like digest-crc, bigdecimal, and the ruby rbs extension isn't compiled. Patching gems one by one is hard due to GEM_PATH issues; give up brew fastlane and install via gem:
brew uninstall fastlane
/opt/homebrew/opt/ruby/bin/gem install fastlane
# binstubs at /opt/homebrew/lib/ruby/gems/4.0.0/bin/, symlink all to /opt/homebrew/bin/
ln -sf /opt/homebrew/lib/ruby/gems/4.0.0/bin/* /opt/homebrew/bin/
Note: symlink the whole bin directory (fastlane depends on a bunch of binstubs like xcpretty). Symlinking only fastlane one will cause xcpretty: command not found (Exit 127) in Jenkins.
3. Fastlane Packaging Configuration
3.1 Manually create scaffold (skip fastlane init interaction)
For CI, recommend writing three files by hand:
fastlane/Appfile: app_identifierfastlane/Fastfile: beta lane (packaging) / release lane (App Store, commented out for now)fastlane/.env.example: environment variable description
Core beta lane logic:
lane :beta do
cocoapods
increment_build_number(build_number: Time.now.strftime("%Y%m%d%H%M"))
gym(
scheme: "YourScheme",
export_method: "development",
output_directory: "./build/buildIpa",
xcargs: "DEVELOPMENT_TEAM=YOUR_TEAM_ID -allowProvisioningUpdates"
)
# Pgyer distribution: skip if API key empty
if ENV["PGYER_API_KEY"].to_s.empty?
UI.important "PGYER_API_KEY not configured, skipping distribution"
else
pgyer(api_key: ENV["PGYER_API_KEY"])
end
end
3.2 Signing with free personal account
After signing into Xcode with a personal Apple account, the development certificate appears in the keychain. Extract Team ID from certificate:
security find-certificate -a -p login.keychain-db | openssl x509 -noout -subject
# OU field is Team ID
Then add DEVELOPMENT_TEAM to all CODE_SIGN_STYLE = Automatic entries in the project (batch sed project.pbxproj), and inject again via xcargs in gym plus -allowProvisioningUpdates so Jenkins auto-generates/updates profiles at build time.
Free personal account builds have a 7-day validity, only for device debugging validation, not a substitute for TestFlight.
3.3 Unlock keychain in Jenkins
Jenkins runs in a background session, can't access the login session's keychain. Two approaches:
- Store the Mac login password as a Jenkins credential (Secret text), before packaging run
security unlock-keychain -p "$KEYCHAIN_PASSWORD" ~/Library/Keychains/login.keychain-db - Or make a dedicated packaging keychain (more standard)
4. Hidden Pit in Gitee SSH Authentication
Jenkins fetches code with a "SSH Username with private key" credential (username git, private key content + passphrase together), not affected by local ssh-agent.
The pit on local push: new OpenSSH private key files lack the ENCRYPTED header, grep can't detect passphrase, but ssh non-interactive auth still fails (ssh -v shows Server accepts key yet Permission denied). Fix:
ssh-add --apple-use-keychain ~/.ssh/id_ed25519
5. Jenkins Installation and Startup
5.1 Manual fix for missing plugin dependencies
When a fresh Jenkins starts and batch-installs plugins, network timeouts cause a bunch of "root cause" plugins fail (commons-lang3-api, snakeyaml-api, branch-api, git-client, font-awesome-api, etc.), page only shows downstream plugin failures. Reliable fix is offline installation:
# Huawei cloud mirror, download directly by <name>/<version>/<name>.hpi
curl -LO https://mirrors.huaweicloud.com/jenkins/plugins/<plugin>/<ver>/<plugin>.hpi
mv <plugin>.hpi ~/.jenkins/plugins/
launchctl kickstart -k gui/$(id -u)/sh.brew.jenkins-lts # restart to take effect
5.2 Bypass brew services, handwrite launchd plist
brew services stop deletes plist, restart regenerates plist wiping manual changes, and default stdout goes to /dev/null (logs lost when debugging). Handwriting a full plist gives more control:
<!-- ~/Library/LaunchAgents/sh.brew.jenkins-lts.plist -->
<plist version="1.0">
<dict>
<key>Label</key><string>sh.brew.jenkins-lts</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/opt/openjdk@21/bin/java</string>
<string>-jar</string><string>/opt/homebrew/opt/jenkins-lts/libexec/jenkins.war</string>
<string>--httpListenAddress=127.0.0.1</string>
<string>--httpPort=8080</string>
</array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>StandardOutPath</key><string>/opt/homebrew/var/log/jenkins-lts.log</string>
<key>StandardErrorPath</key><string>/opt/homebrew/var/log/jenkins-lts.log</string>
</dict>
</plist>
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/sh.brew.jenkins-lts.plist
KeepAlive ensures self-restart on crash, RunAtLoad ensures auto-start after login (note: with FileVault on, manual login needed once after reboot).
6. Packaging Pipeline (Pipeline script from SCM)
Jenkinsfile at repo root, Jenkins job uses "Pipeline script from SCM", branch */develop:
pipeline {
agent any
environment {
PATH = "/opt/homebrew/bin:...:$PATH"
DEVELOPER_DIR = "/Applications/Xcode.app/Contents/Developer"
HOME = "/Users/yourname"
}
options { timestamps(); disableConcurrentBuilds() }
triggers {
// poll every minute, push triggers build within 1 minute (see pitfalls in chapter 8!)
pollSCM('* * * * *')
}
stages {
stage('Fetch code') { steps { checkout([...GitSCM...]) } }
stage('Package & distribute') {
steps {
withCredentials([string(credentialsId: 'KEYCHAIN_PASSWORD',
variable: 'KEYCHAIN_PASSWORD')]) {
sh 'fastlane beta'
}
}
}
stage('Copy to project dir') { steps { sh 'cp build/buildIpa/*.ipa "$DEST"/' } }
stage('Archive artifacts') { steps { archiveArtifacts artifacts: 'build/buildIpa/*.ipa, ...' } }
}
}
Experience points:
disableConcurrentBuildsprevents concurrent packaging during dense pollingcleanWsexclude pattern for ipa to avoid build artifacts being accidentally deleted by workspace cleanup- PATH environment variable must be explicitly set (launchd session PATH differs from terminal)
7. REST API Trigger and Diagnosis
Create admin API Token (avatar → Security → API Token), then many things don't need UI:
# manually trigger build
curl -X POST -u "admin:$TOKEN" "http://127.0.0.1:8080/job/YourJob/build"
# read job status
curl -u "admin:$TOKEN" "http://127.0.0.1:8080/job/YourJob/6/api/json?tree=building,result"
# script console (diagnosis wonder tool, see runtime state)
curl -u "admin:$TOKEN" --data-urlencode "script=$GROOVY" http://127.0.0.1:8080/scriptText
8. pollSCM('H/1 * * * *') Is Once Per Hour, Not Every Minute (Core Pit)
Symptom: changed polling from H/5 to H/1 to achieve every-minute polling, but it went completely silent—no error, restart no effect, polling log stopped updating, master log clean, trigger registered correctly in config.xml and runtime.
Diagnosis path (a reusable methodology):
- Script console confirms trigger registered, job not disabled
- Reflection to see static
java.util.TimerofTrigger— scheduled queue size = 0, i.e., never scheduled - Decompile Jenkins core (extract
Trigger.classfrom war,javap -c) reveals new versionstart()only does field assignment, doesn't schedule; real scheduling driver isTrigger$Cron(a 60-second periodic work extension point) - Manually
new CronTabto compare parse results, evidence:
spec='H/1 * * * *' -> minuteBits popCount=1 (only hits 1 hash minute per hour!)
spec='* * * * *' -> minuteBits popCount=60 (every minute ✓)
spec='H/5 * * * *' -> minuteBits popCount=12 (every 5 minutes ✓)
Conclusion: H/step slices time interval by step and takes a hash offset based on job name; H/1 means "runs at a fixed minute per hour". The symptom looks like "polling completely silent", but actually the next trigger is 1 hour later.
Correct way: every-minute polling must use pollSCM('* * * * *').
9. MR Check: Multi-branch Pipeline + SwiftLint
9.1 Components
- SwiftLint:
brew install swiftlint, repo root has a lenient.swiftlint.yml(first round only errors block build, style rules all warning, avoid CI all red at start) Jenkinsfile-PRCheck:
stages {
stage('SwiftLint check') {
steps {
sh '''
swiftlint --reporter emoji
ERRORS=$(swiftlint lint --quiet | grep -c "error: " || true)
[ "$ERRORS" -gt 0 ] && exit 1
'''
}
}
stage('Compile validation') {
steps {
sh '''
pod install --repo-update
xcodebuild -workspace App.xcworkspace \
-scheme App \
-destination 'generic/platform=iOS Simulator' \
-configuration Debug \
build CODE_SIGNING_ALLOWED=NO | xcpretty
'''
}
}
}
- Jenkins creates WorkflowMultiBranchProject (multi-branch pipeline):
- Branch source: git repo + SSH credentials
- Each
feature/*branch automatically gets a separate job, using its ownJenkinsfile-PRCheck - Deleted branches auto-cleanup (orphan policy pruneDeadBranches)
- Branch job build history
buildDiscarder(numToKeepStr: '10')
9.2 Pitfalls when creating Multi-branch via REST
Using POST /createItem to directly create Multibranch:
- New git plugin no longer accepts
<includes>/<excludes>fields in XML (silently discarded), branch filtering must use trait:WildcardSCMHeadFilterTrait(in scm-api plugin, packagejenkins.scm.impl.trait, not git plugin) PeriodicFolderTrigger(periodic scan) class is in cloudbees-folder plugin, packagecom.cloudbees.hudson.plugins.folder.computed(easy to mistakenly writejenkins.branch), spec supports1minformat- If POST config.xml returns 500 and hard to locate, switch to script console programmatic configuration for stability:
import jenkins.scm.impl.trait.WildcardSCMHeadFilterTrait
import com.cloudbees.hudson.plugins.folder.computed.PeriodicFolderTrigger
def proj = Jenkins.instance.getItemByFullName('PlanList-PR-Check')
def src = proj.sources[0].source
src.traits = [ new WildcardSCMHeadFilterTrait('feature/*', 'master develop') ]
proj.addTrigger(new PeriodicFolderTrigger('1min'))
proj.save()
- First scan manual trigger:
POST /job/<folder>/indexing
9.3 Why It Works Without Webhook
True MR event triggering requires Gitee Webhook callback to Jenkins, but local 127.0.0.1 is unreachable by Gitee. Polling approach's equivalent logic: "feature branch green" ≈ "MR check passed"—because MR merge content is the feature branch tip, if branch tip compiles/lints green, it's equivalent. Upgrade path: later buy cloud server or use frp to expose intranet, then connect Gitee Webhook to replace polling trigger with event trigger, Jenkinsfile unchanged; writing build results back to MR comments via Jenkins actively calling Gitee API (no public callback needed, can add anytime).
10. Diagnosis Toolbox (Summary from This Practice)
| Scenario | Tool/Method |
|---|---|
| Jenkins runtime state diagnosis | Script console /scriptText (needs admin API Token), reflection to see triggers, threads, queues |
| "Config on disk, not in memory" problems | Decompile: extract class from war/plugin jar → javap -c to see real logic |
| Trigger parsing problems | new CronTabList(spec, Hash) verify parse results in script console |
| Batch plugin install failure | Huawei cloud mirror offline hpi install to ~/.jenkins/plugins/ |
| Lost logs | Replace brew services with handwritten launchd plist, specify StandardOut/ErrPath |
| Whether polling is running | Check mtime of scm-polling.log under job directory |
11. Remaining Items and Upgrade Suggestions
- Free personal signing account: 7-day validity, proper distribution needs developer account + TestFlight
- Pgyer distribution: Fastfile already supports, enable by configuring
PGYER_API_KEYcredential - Cloud migration: local Mac pain points are "must be on", "public access difficult", for scale recommend "cloud Jenkins scheduler + local Mac as inbound agent"—agent actively connects out to cloud, naturally passes NAT, local Jenkins can retire
- Gitee Webhook (MR event trigger) + MR status write-back is the natural next step
12. Build Artifact Distribution: Pgyer (Internal Test) / TestFlight (Production)
After packaging pipeline produces artifacts, next step is distribution. Two routes by account type:
| Pgyer | TestFlight | |
|---|---|---|
| Account requirement | No developer account needed | Needs Apple Developer Program (¥688/year) |
| Package type | development / ad hoc | App Store distribution |
| Test devices | Need to add device UDID to profile | No, scan QR to install |
| Validity | With profile/certificate | 90 days after upload |
| Use case | Small-scale device debugging | More formal internal testing, can share link |
12.1 Pgyer Upload
- Pgyer console → App details → API to get
api_key(anduser_key) - Install fastlane plugin:
fastlane add_plugin pgyer
- In Fastfile, replace "skip logic" with real upload:
lane :beta do
cocoapods
increment_build_number(build_number: Time.now.strftime("%Y%m%d%H%M"))
gym(
scheme: "YourScheme",
export_method: "development",
output_directory: "./build/buildIpa",
xcargs: "DEVELOPMENT_TEAM=YOUR_TEAM_ID -allowProvisioningUpdates"
)
pgyer(
api_key: ENV["PGYER_API_KEY"],
user_key: ENV["PGYER_USER_KEY"],
update_description: true
)
end
- Jenkins side: don't put keys in code, store
PGYER_API_KEYas Jenkins credential (Secret text), inject in Jenkinsfile withwithCredentials:
stage('Package & distribute') {
steps {
withCredentials([
string(credentialsId: 'KEYCHAIN_PASSWORD', variable: 'KEYCHAIN_PASSWORD'),
string(credentialsId: 'PGYER_API_KEY', variable: 'PGYER_API_KEY'),
string(credentialsId: 'PGYER_USER_KEY', variable: 'PGYER_USER_KEY')
]) {
sh 'fastlane beta'
}
}
}
- Note: development packages installed on real devices need test device UDIDs added to developer account device list. During Jenkins build,
-allowProvisioningUpdatesautomatically adds devices and regenerates profiles.
12.2 TestFlight Upload
Prerequisites: paid developer account + App created in App Store Connect.
- In App Store Connect → Users and Access → Integration → App Store Connect API create API key, get
Key ID,Issuer ID, download.p8private key - Credential management (CI recommends storing content base64 to avoid file path management):
base64 -i AuthKey_XXXXXX.p8 | pbcopy
Store three Secret texts in Jenkins: ASC_KEY_ID, ASC_ISSUER_ID, ASC_P8_BASE64
- Add release lane to Fastfile:
lane :release do
app_store_connect_api_key(
key_id: ENV["ASC_KEY_ID"],
issuer_id: ENV["ASC_ISSUER_ID"],
key_content: ENV["ASC_P8_BASE64"],
is_key_content_base64: true
)
setup_ci # prevent interaction in CI
cocoapods
increment_build_number(build_number: Time.now.strftime("%Y%m%d%H%M"))
gym(
scheme: "YourScheme",
export_method: "app-store",
output_directory: "./build/buildIpa"
)
pilot(
skip_waiting_for_build_processing: false, # wait for processing so failures are noticed
distribute_external: false
)
end
- Jenkinsfile adds an "Upload TestFlight" stage (reuse same withCredentials, add three ASC credentials)
- Common pitfalls:
- After
pilotupload, Apple processing takes 10–30 minutes; withskip_waiting_for_build_processing: false, the pipeline hangs waiting. Recommend separating packaging and upload, or accept long builds. - app-store packages need distribution certificate + App Store profile; development packages signed with free personal account can't be uploaded
- Repeated upload with same build number is rejected; timestamp-based build number inherently avoids this.
- After
13. Jenkins Cloud Migration: Cloud Scheduler + Mac as Inbound Agent
Local Mac setup has two pain points: must be on and Gitee Webhook callbacks can't reach. Standard solution isn't moving builds to cloud (iOS builds require macOS, cloud Macs are expensive and risk violating agreements), instead—
Jenkins on cloud Linux server (scheduler), Mac only a "build node (agent)" that actively connects (inbound mode, naturally passes NAT), local Jenkins retires.
13.1 Architecture
Gitee (push / MR events)
│ Webhook (https callback, cloud has public IP, no more polling)
▼
Cloud Jenkins (Linux, publicly reachable) ← control plane: job config/queue/page/credentials
│ ▲
│ │ JNLP: Mac agent active long-connect to cloud (Mac no public IP needed)
▼ │
Local Mac agent (label: mac-build) ← execution plane: Xcode/fastlane/certificates all here
13.2 Install Jenkins on Cloud
- Buy an entry-level Linux cloud server (1C2G is enough, scheduler doesn't consume many resources), security group/firewall open
8080(page) and50000(agent inbound) - Install JDK 21 + Jenkins LTS:
# apt example
sudo apt update && sudo apt install -y openjdk-21-jdk
curl -fsSL https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key | sudo tee /usr/share/keyrings/jenkins-keyring.asc > /dev/null
echo "deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] https://pkg.jenkins.io/debian-stable binary/" | sudo tee /etc/apt/sources.list.d/jenkins.list
sudo apt install -y jenkins
- Recommend nginx reverse proxy + domain + HTTPS in front (Webhook can be https or http, https more standard):
server {
listen 443 ssl;
server_name jenkins.yourdomain.com;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
# agent inbound port 50000 stays TCP direct
- Plugins and domestic mirror: plugin update source can be changed to domestic mirror (System Management → Plugins → Advanced → Update Site URL), failed plugins can also use Huawei cloud mirror offline hpi.
13.3 Configure Mac as Inbound Agent
- Cloud Jenkins page: System Management → Node Management → New Node → name like
mac-build, type permanent, Remote root directory fill~/jenkins-agent, Labels fillmac-build, usage "only assign tasks to this node" - After save, page gives two things:
agent.jardownload URL and a-secretcommand - On Mac side, run agent as launchd service (auto-start on boot + self-restart on crash, same treatment as local Jenkins):
<!-- ~/Library/LaunchAgents/com.yourname.jenkins-agent.plist -->
<plist version="1.0">
<dict>
<key>Label</key><string>com.yourname.jenkins-agent</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/opt/openjdk@21/bin/java</string>
<string>-jar</string><string>/Users/yourname/jenkins-agent/agent.jar</string>
<string>-url</string><string>https://jenkins.yourdomain.com/</string>
<string>-secret</string><string>AGENT_SECRET_FROM_PAGE</string>
<string>-name</string><string>mac-build</string>
<string>-workDir</string><string>/Users/yourname/jenkins-agent</string>
</array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>StandardOutPath</key><string>/Users/yourname/jenkins-agent/agent.log</string>
<key>StandardErrorPath</key><string>/Users/yourname/jenkins-agent/agent.log</string>
</dict>
</plist>
curl -sO https://jenkins.yourdomain.com/jnlpJars/agent.jar
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.yourname.jenkins-agent.plist
Node page showing "online" means success. In inbound mode, Mac behind NAT/internal network doesn't matter because Mac initiates the connection.
13.4 Job and Credential Migration
- Jobs: because using "Pipeline script from SCM", Jenkinsfile lives in repo, cloud only needs to rebuild jobs per config (fetch code credential, KEYCHAIN_PASSWORD, PGYER/ASC credentials)—this is the biggest benefit of keeping pipeline entirely in repo
- Packaging pipeline: change
agent anytoagent { label 'mac-build' }(same for PR-Check) - Batch credential migration: copy local
~/.jenkins/secrets/master.keyand~/.jenkins/secrets/jenkins.model.Jenkins.crumbCipher+credentials.xml(with secrets directory) to cloud corresponding location, credentials usable as is - Toolchain on Mac agent must stay equivalent: Xcode, CocoaPods, fastlane (gem method), swiftlint, JDK, and keychain/signing environment stays on Mac, unaffected by Jenkins migration
13.5 Connect Gitee Webhook (Replace Polling)
- Install Gitee plugin on cloud Jenkins, System Management → Gitee configuration: fill "Gitee domain https://gitee.com + personal token", test connectivity
- In job, change trigger to Gitee Webhook (packaging job check push event, PR-Check check MR event)
- Page shows Webhook URL like
https://jenkins.yourdomain.com/gitee-project/<jobName> - Gitee repo → Management → WebHooks → add that URL, password optional, check
Push,Merge Requestevents - From now on:
- push develop → second-level triggering of packaging (replaces
* * * * *polling) - MR submitted → second-level triggering of PR-Check, and can write back comments via Gitee API (then even MR status auto-fills)
- push develop → second-level triggering of packaging (replaces
13.6 Migration Checklist
- Mac agent online, labels correct
- Packaging/PR-Check jobs first build all green (after local Jenkins stops, workspace rebuilds, first build a bit slower, normal)
- Keychain unlock stage works (credentials migrated with job)
- Gitee Webhook push event test connectivity (Gitee shows response code 200/201)
- Uninstall local Jenkins service via
launchctl bootoutfrom local launchd, only keep agent
The above scheme ran end-to-end on this machine (Apple Silicon Mac + Xcode 27 + Gitee private repo): push develop auto-packages (#6, #7 verified), feature branch auto-lint + compile check (multi-branch first build all green). Pgyer/TestFlight distribution and cloud migration are direct extensions of the same Fastlane/Jenkinsfile, no code restructure needed.