Auto-Deploy Firebase Security Rules with GitLab CI/CD: A Complete Guide

Auto-Deploy Firebase Security Rules with GitLab

How to Auto-Deploy Firebase Security Rules to Multiple Projects with GitLab


Managing Firebase security rules across development and production environments can be tedious and error-prone when done manually. This guide shows you how to set up automatic deployment of Firestore security rules using GitLab CI/CD pipelines.

Why Auto-Deploy Security Rules?

Whether you’re building with FlutterFlow, Flutter, React, or any Firebase-powered app, you’ve probably experienced:

  • Manual deployment fatigue: Copying rules between Firebase Console environments
  • Environment inconsistencies: Dev and prod rules getting out of sync
  • Deployment errors: Forgetting to update rules after code changes
  • No version control: Rules living only in Firebase Console without proper tracking

This solution eliminates these problems by treating your security rules as code.

What You’ll Build

By the end of this guide, you’ll have:

  • Automatic deployment to development when pushing to develop or feature branches
  • Manual deployment to production when merging to main branch
  • Version-controlled security rules in your Git repository
  • Deployment logs and history in GitLab

Prerequisites

  • Firebase project (development and production)
  • GitLab repository
  • Basic knowledge of Git branches

Step 1: Prepare Your Repository Structure

Create these files in your repository root:

firestore.rules

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Example rules - customize for your needs
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }

    match /public/{document=**} {
      allow read: if true;
      allow write: if request.auth != null;
    }
  }
}

firebase.json

{
  "firestore": {
    "rules": "firestore.rules"
  }
}

Step 2: Create Firebase Service Accounts

You need service accounts to allow GitLab to deploy to Firebase programmatically.

For Development Project:

  1. Go to Google Cloud Console
  2. Select your development Firebase project
  3. Navigate to IAM & AdminService Accounts
  4. Click Create Service Account
  5. Name it gitlab-ci-dev with description GitLab CI/CD development deployments
  6. Grant the Firebase Admin role
  7. Click Done
  8. Click on the service account → KeysAdd KeyCreate New Key
  9. Choose JSON format and download

For Production Project:

Repeat the same process for your production project.

Pro Tip: The Firebase Admin role includes all necessary permissions. For minimal permissions, you can use just Firebase Rules Admin.

Step 3: Configure GitLab Variables

In your GitLab repository:

  1. Go to SettingsCI/CDVariablesExpand
  2. Add these four variables:
KeyValueSettings
DEV_PROJECT_IDYour dev project ID (e.g., myapp-dev-12345)Protected: ✓, Masked: ✗
FIREBASE_DEV_KEYEntire content of dev service account JSONProtected: ✓, Masked: ✗
PROD_PROJECT_IDYour prod project ID (e.g., myapp-prod-67890)Protected: ✓, Masked: ✗
FIREBASE_PROD_KEYEntire content of prod service account JSONProtected: ✓, Masked: ✗

Important: Make sure your develop and main branches are protected in SettingsRepositoryProtected branches.

Step 4: Create GitLab CI/CD Pipeline

Create .gitlab-ci.yml in your repository root:

stages:
  - deploy

# Deploy to development environment
deploy-dev:
  image: node:18
  stage: deploy
  before_script:
    - npm install -g firebase-tools
    - echo "$FIREBASE_DEV_KEY" > service-account.json
    - export GOOGLE_APPLICATION_CREDENTIALS=service-account.json
  script:
    - echo "🚀 Deploying Firestore rules to development..."
    - echo "📋 Project: $DEV_PROJECT_ID"
    - firebase deploy --only firestore:rules --project "$DEV_PROJECT_ID"
    - echo "✅ Development deployment completed successfully!"
  after_script:
    - rm -f service-account.json
  rules:
    - if: $CI_COMMIT_BRANCH == "develop"
      changes:
        - firestore.rules
    - if: $CI_COMMIT_BRANCH =~ /^feature\/.*/
      changes:
        - firestore.rules

# Deploy to production environment  
deploy-prod:
  image: node:18
  stage: deploy
  before_script:
    - npm install -g firebase-tools
    - echo "$FIREBASE_PROD_KEY" > service-account.json
    - export GOOGLE_APPLICATION_CREDENTIALS=service-account.json
  script:
    - echo "🚀 Deploying Firestore rules to production..."
    - echo "📋 Project: $PROD_PROJECT_ID"
    - echo "⚠️  Production deployment - please verify rules are correct"
    - firebase deploy --only firestore:rules --project "$PROD_PROJECT_ID"
    - echo "✅ Production deployment completed successfully!"
  after_script:
    - rm -f service-account.json
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
      changes:
        - firestore.rules
  when: manual

Step 5: Test Your Setup

  1. Create a feature branch: git checkout -b feature/update-security-rules
  2. Modify your rules: # Edit firestore.rules nano firestore.rules
  3. Commit and push: git add . git commit -m "Update Firestore security rules" git push origin feature/update-security-rules
  4. Check the pipeline: Go to CI/CDPipelines in GitLab

Common Issues and Solutions

Issue 1: Variables Not Found

Error: DEV_PROJECT_ID is ''

Solution:

  • Verify variable names are exact: DEV_PROJECT_ID, FIREBASE_DEV_KEY
  • Check that your branch is protected (required for protected variables)
  • Ensure variables are set to Environment scope: All

Issue 2: Authentication Failed

Error: Failed to authenticate, have you run firebase login?

Solution:

  • Verify your service account JSON is complete (should be ~2400 characters)
  • Make sure you copied the entire JSON content including { and }

Issue 3: Permission Denied

Error: The caller does not have permission

Solution:

  1. Go to Google Cloud Console → IAM & Admin → IAM
  2. Find your service account
  3. Add Firebase Admin role (or minimum Firebase Rules Admin)

How It Works

  • Feature branches (feature/*) → Auto-deploy to dev
  • Develop branch → Auto-deploy to dev
  • Main branch → Manual deploy to prod (requires clicking “Play” button)
  • Only triggers when firestore.rules file changes
  • Secure cleanup of service account files after each deployment

Advanced Tips

Environment-Specific Rules

For different rules per environment, create separate files:

firestore.rules.dev
firestore.rules.prod

Then modify your pipeline to copy the appropriate file before deployment.

Add Storage Rules

To include Cloud Storage rules, add storage.rules to your repository and update the deploy command:

- firebase deploy --only firestore:rules,storage --project "$DEV_PROJECT_ID"

Notifications

Add Slack or email notifications by extending the after_script section with webhook calls.

Conclusion

You now have a robust, automated deployment pipeline for Firebase security rules. This setup ensures your rules are version-controlled, consistently deployed, and properly tested across environments.

Benefits achieved:

  • ✅ No more manual copy-paste between environments
  • ✅ Version history of all rule changes
  • ✅ Consistent deployment process
  • ✅ Reduced human error
  • ✅ Clear audit trail of deployments

Whether you’re using FlutterFlow for rapid app development or building custom Firebase applications, this CI/CD pipeline will streamline your security rule management and improve your development workflow.


Have questions or run into issues? The GitLab CI/CD documentation and Firebase CLI reference are excellent resources for troubleshooting and extending this setup.

Contact Us

Give us a call or fill in the form below and we will contact you. We endeavor to answer all inquiries within 24 hours on business days.