跪拜 Guibai
← Back to the summary

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:

  1. When develop branch gets a push, auto-package within 1 minute (ipa lands in a specified directory)
  2. 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:

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:

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:

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):

  1. Script console confirms trigger registered, job not disabled
  2. Reflection to see static java.util.Timer of Trigger — scheduled queue size = 0, i.e., never scheduled
  3. Decompile Jenkins core (extract Trigger.class from war, javap -c) reveals new version start() only does field assignment, doesn't schedule; real scheduling driver is Trigger$Cron (a 60-second periodic work extension point)
  4. Manually new CronTab to 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

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
            '''
        }
    }
}

9.2 Pitfalls when creating Multi-branch via REST

Using POST /createItem to directly create Multibranch:

  1. New git plugin no longer accepts <includes>/<excludes> fields in XML (silently discarded), branch filtering must use trait: WildcardSCMHeadFilterTrait (in scm-api plugin, package jenkins.scm.impl.trait, not git plugin)
  2. PeriodicFolderTrigger (periodic scan) class is in cloudbees-folder plugin, package com.cloudbees.hudson.plugins.folder.computed (easy to mistakenly write jenkins.branch), spec supports 1min format
  3. 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()
  1. 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


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

  1. Pgyer console → App details → API to get api_key (and user_key)
  2. Install fastlane plugin:
fastlane add_plugin pgyer
  1. 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
  1. Jenkins side: don't put keys in code, store PGYER_API_KEY as Jenkins credential (Secret text), inject in Jenkinsfile with withCredentials:
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'
        }
    }
}
  1. Note: development packages installed on real devices need test device UDIDs added to developer account device list. During Jenkins build, -allowProvisioningUpdates automatically adds devices and regenerates profiles.

12.2 TestFlight Upload

Prerequisites: paid developer account + App created in App Store Connect.

  1. In App Store Connect → Users and Access → Integration → App Store Connect API create API key, get Key ID, Issuer ID, download .p8 private key
  2. 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

  1. 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
  1. Jenkinsfile adds an "Upload TestFlight" stage (reuse same withCredentials, add three ASC credentials)
  2. Common pitfalls:
    • After pilot upload, Apple processing takes 10–30 minutes; with skip_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.

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

  1. Buy an entry-level Linux cloud server (1C2G is enough, scheduler doesn't consume many resources), security group/firewall open 8080 (page) and 50000 (agent inbound)
  2. 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
  1. 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
  1. 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

  1. Cloud Jenkins page: System Management → Node Management → New Node → name like mac-build, type permanent, Remote root directory fill ~/jenkins-agent, Labels fill mac-build, usage "only assign tasks to this node"
  2. After save, page gives two things: agent.jar download URL and a -secret command
  3. 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

13.5 Connect Gitee Webhook (Replace Polling)

  1. Install Gitee plugin on cloud Jenkins, System Management → Gitee configuration: fill "Gitee domain https://gitee.com + personal token", test connectivity
  2. In job, change trigger to Gitee Webhook (packaging job check push event, PR-Check check MR event)
  3. Page shows Webhook URL like https://jenkins.yourdomain.com/gitee-project/<jobName>
  4. Gitee repo → Management → WebHooks → add that URL, password optional, check Push, Merge Request events
  5. 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)

13.6 Migration Checklist


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.