TExcelTAD
Home › Mobile Build Pipelines: Gradle/AGP, Xcode, SwiftPM & Fastlane › Fastlane for Android: gradle & supply

Fastlane for Android: gradle & supply

On Android, Fastlane mostly drives two things: Gradle (through the gradle action) and the Google Play Developer API (through upload_to_play_store, a.k.a. supply). Signing and versioning stay in the Gradle build, where the previous lessons put them.

Note: non-run (Fastlane isn't in the course container). Actions and parameters are from Fastlane's documentation.

Access to Google Play

Fastlane talks to Play with a service account: create it in Google Cloud, enable the Google Play Android Developer API, invite the service account's e-mail in Play Console (Users and permissions) with release permissions for the app, and download its JSON key. That JSON key is a secret with the power to publish your app: store it in the CI secret store, never in the repository.

bash
bundle exec fastlane run validate_play_store_json_key json_key:"$PLAY_JSON_KEY_PATH"
bundle exec fastlane supply init        # download the current store listing into fastlane/metadata/android

Play requires the first upload of a new app to be done manually in Play Console; the API can only update an existing app.

The Fastfile

ruby
# fastlane/Fastfile
default_platform(:android)

platform :android do
  before_all do
    ENV["GRADLE_OPTS"] = "-Dorg.gradle.daemon=false"   # CI: no daemon to clean up afterwards
  end

  desc "Unit tests (free flavor), as on every pull request"
  lane :test do
    gradle(task: "test", flavor: "free", build_type: "Debug")
  end

  desc "Build the signed free bundle and send it to internal testers"
  lane :internal do
    build_number = ENV.fetch("BUILD_NUMBER")             # from CI, e.g. github.run_number
    gradle(
      task: "bundle",
      flavor: "free",
      build_type: "Release",
      properties: {
        "buildNumber" => build_number,
        # signing values arrive as ORG_GRADLE_PROJECT_* environment variables (see Signing)
      }
    )
    upload_to_play_store(
      track: "internal",
      aab: lane_context[SharedValues::GRADLE_AAB_OUTPUT_PATH],
      json_key_data: ENV.fetch("PLAY_JSON_KEY"),
      release_status: "completed",
      skip_upload_metadata: true,
      skip_upload_images: true,
      skip_upload_screenshots: true
    )
  end

  desc "Promote the build on internal to 10% of production"
  lane :promote do
    upload_to_play_store(
      track: "internal",
      track_promote_to: "production",
      rollout: "0.1",                                      # staged rollout: 10% of users
      json_key_data: ENV.fetch("PLAY_JSON_KEY"),
      skip_upload_aab: true, skip_upload_apk: true,
      skip_upload_metadata: true, skip_upload_images: true, skip_upload_screenshots: true
    )
  end

  desc "Raise the production rollout"
  lane :rollout do |options|
    upload_to_play_store(track: "production", rollout: options.fetch(:fraction),
                         json_key_data: ENV.fetch("PLAY_JSON_KEY"),
                         skip_upload_aab: true, skip_upload_apk: true,
                         skip_upload_metadata: true, skip_upload_images: true, skip_upload_screenshots: true)
  end
end
bash
bundle exec fastlane android internal
bundle exec fastlane android promote
bundle exec fastlane android rollout fraction:0.5

Typical output of internal (trimmed):

text
+-----------------+---------------------------------------------------------------+
|                                  Lane Context                                   |
+-----------------+---------------------------------------------------------------+
| PLATFORM_NAME   | android                                                       |
| LANE_NAME       | android internal                                              |
+-----------------+---------------------------------------------------------------+
[10:02:14]: ------------------
[10:02:14]: --- Step: gradle ---
[10:02:14]: ------------------
[10:02:14]: $ ./gradlew bundleFreeRelease -p . -PbuildNumber=187
…
[10:03:40]: ---------------------------------
[10:03:40]: --- Step: upload_to_play_store ---
[10:03:40]: ---------------------------------
[10:03:41]: Preparing aab at path 'app/build/outputs/bundle/freeRelease/app-free-release.aab' for upload...
[10:03:52]: Updating track 'internal'...
[10:03:54]: Successfully finished the upload to Google Play

Tracks, statuses and rollouts

Track Audience
internal up to 100 testers, available within minutes, no review
alpha (closed testing) / beta (open testing) tester lists or anyone who opts in
production everyone, optionally a staged rollout fraction

A release on a track also has a status (draft, inProgress for staged rollouts, halted, completed). The "build once, promote" pattern above is the important habit: the same bundle that internal testers approved goes to production, instead of a rebuild that might differ.

Version codes and Play

Play rejects an upload whose versionCode was already used for the app, on any track. Two useful actions guard against that:

ruby
codes = google_play_track_version_codes(track: "internal", json_key_data: ENV.fetch("PLAY_JSON_KEY"))
UI.user_error!("versionCode #{code} already used") if codes.include?(code)

Better still, derive the code from CI as in versionCode & versionName Strategy, so a collision can't happen in the first place.

A runnable model of staged rollouts

A staged rollout gives the new version to a fraction of users; Play assigns users to buckets, so raising the fraction only adds users. A model of that assignment with a stable hash:

python · try it yourself
import hashlib

def bucket(user_id):
    # a stable number in [0, 1) per user, the same every day
    return int(hashlib.sha256(user_id.encode()).hexdigest()[:8], 16) / 16**8

users = [f"user-{i:03d}" for i in range(1000)]
previous = set()
for fraction in [0.01, 0.1, 0.5, 1.0]:
    updated = {u for u in users if bucket(u) < fraction}
    assert previous <= updated            # raising the rollout never takes the update away
    print(f"rollout {fraction:>4}: {len(updated):>4} of {len(users)} users")
    previous = updated
rollout 0.01:   12 of 1000 users
rollout  0.1:  118 of 1000 users
rollout  0.5:  501 of 1000 users
rollout  1.0: 1000 of 1000 users

Halting a rollout (release_status: "halted") stops new users from getting the update but doesn't uninstall it from those who have it, so the fix for a bad release is always a new build with a higher versionCode.

Test yourself

What does Fastlane need to upload to Google Play?

  1. Your Google account password
  2. A service account JSON key with release permission for the app
  3. The upload keystore
  4. An App Store Connect API key

Why promote the internal build to production instead of building again?

  1. Rebuilding is not allowed
  2. The exact artifact that testers approved is the one users get
  3. Promotion is cheaper on Play
  4. Production requires a debug build

A production release has a bug at a 10% rollout. What fixes it for affected users?

  1. Halting the rollout
  2. Deleting the release
  3. Shipping a new build with a higher versionCode
  4. Lowering versionCode