How to use Secret Manager with 2nd gen Cloud Firestore Triggers?
Asked Answered
T

1

5

I am migrating a 1st generation Cloud Firestore Trigger to the second generation.

However, I cannot figure out how to access Google's Secret Manager from within the second generation Cloud Trigger.

Documentation exists for accessing secrets within second generation cloud functions by making use of a defineSecret utility which is passed into the function's dependency array. However, this approach does not work with the second generation cloud trigger as there is no options parameter to pass the dependency array.

To explain with a snippet what I am trying to do:

import { onDocumentCreated } from 'firebase-functions/v2/firestore';
import { defineSecret } from 'firebase-functions/params';

const apiKey = defineSecret('API_KEY');

const onUserCreated = onDocumentCreated(
  'users/{userId}',
  async (event) => {
    // ๐Ÿ‘‰ access apiKey secret ๐Ÿ‘ˆ
  }
);

Any help would be greatly appreciated. Thank you.

Toomay answered 12/7, 2023 at 4:34 Comment(0)
S
8

You can pass a DocumentOptions object as the first parameter, which is basically an extension of EventHandlerOptions to set the secrets with the below code:

import * as admin from "firebase-admin";
admin.initializeApp();
import { onDocumentWritten } from "firebase-functions/v2/firestore";
import { defineSecret } from "firebase-functions/params";

const discordApiKey = defineSecret("DISCORD_API_KEY");

export const writetofirestore = onDocumentWritten({
  document: "users/{userId}",
  secrets: [discordApiKey] // you can provide secrets like this 
}, (event) => { 
  const apiKey = discordApiKey.value(); // use secret like this
});

Reference : firestore.onDocumentWritten()

Scandic answered 12/7, 2023 at 11:41 Comment(1)
Perfect, thank you @Sandeep Vokkareni. For anyone else, the EventHandlerOptions mentioned in the answer extends GlobalOptions which contains a "secrets" property: firebase.google.com/docs/reference/functions/2nd-gen/node/… โ€“ Toomay

© 2022 - 2024 โ€” McMap. All rights reserved.