How to Pass Firebase Service Account Key to Kubernetes Deployment

(Jess Cherry, CC BY-SA 4.0)

(Jess Cherry, CC BY-SA 4.0)

This article assumes you’re somewhat familiar with Kubernetes and know the building blocks for deploying applications to Kubernetes.

So you’ve been deploying to K8s for a while and are familiar with resources like Deployment, Secret, ConfigMap, and Service. As usual, in the deployment resource configuration file, you’ll reference a secret resource and use it as an environment variable in your pod.

Basic Secret Configuration

Suppose you have a Secret configuration file named secret.yaml:

apiVersion: v1
kind: Secret
metadata:
  name: mysecret
  namespace: node-application
type: Opaque
data:
  username: YWRtaW4=
  password: MWYyZDFlMmU2N2Rm

Apply the secret using:

kubectl apply -f ./secret.yaml

Using Secrets in Deployment

You can specify the secret as an environment variable in a Deployment configuration file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: node-application-deployment
  namespace: node-application
spec:
  replicas: 1
  selector:
    matchLabels:
      app: node-backend
  template:
    metadata:
      labels:
        app: node-backend
    spec:
      containers:
        - name: node-backend
          image: {{ .Values.image.repository }}:{{ .Values.image.tag }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          env:
          - name: USER_NAME
            valueFrom:
              secretKeyRef:
                name: mysecret
                key: username

Handling Firebase Service Account Key

Sometimes you need to store a secret as a JSON file that your application can import, such as a Firebase service account file:

const admin = require('firebase-admin');

const serviceAccount = require('../secret/service_account_key.json');
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: `https://${serviceAccount.project_id}.firebaseio.com`,
});

Converting Service Account Key to Base64

First, convert the JSON content of service_account_key.json to base64:

echo -n '<CONTENT_service_account_key_file>' | base64

Updating the Secret Configuration

Add the base64-encoded service account key to the secret file:

data:
  SERVICE_ACCOUNT_KEY: eyJhdXRoX3Byb3..

Mounting the Secret as a Volume

In the deployment file, mount the secret as a JSON file in a volume:

containers:
  ...
  ports:
    - containerPort: {{ .Values.service.port }}
  volumeMounts:
    - mountPath: /usr/src/app/secret/
      name: firebase-sa-key
      readOnly: true
volumes:
  - name: firebase-sa-key
    secret:
      secretName: mysecret
      items:
        - key: SERVICE_ACCOUNT_KEY
          path: service_account_key.json

Final Result

Your application code will now have access to the Firebase service account key JSON file at the path /usr/src/app/secret/service_account_key.json.