Secret Manager API workflow
Secret Manager exposes a REST API and a gRPC API for using and managing secrets directly or in your applications.
Follow the Google provided instruction to enable the Secret Manager for your project.
Ref: https://cloud.google.com/secret-manager/docs/configuring-secret-manager
Key requirements
Create a project in the Google Cloud account
Verify/enable billing for the project
Enable Secrete Manager API for the project
Install Google Cloud Cli
Initialize Google Cloud Cli
Create a secret
Ref: https://cloud.google.com/secret-manager/docs/creating-and-accessing-secrets
Manage secret access
Ref: https://cloud.google.com/secret-manager/docs/manage-access-to-secrets
Manage Functions access to secrets
Ref: https://cloud.google.com/functions/docs/configuring/secrets
Access secrets from cloud functions
Run the following command to make sure the secret manager package is available in your project:
npm install @google-cloud/secret-manager
Update the functions package.json
with the new dependency.
File: apps\{{project}}\src\package.json
Create utility function to get secrets from secret manager
Create the file get-secret-value.ts
in the utils
folder:
apps\{{project}}\src\utils\get-secret-value.ts
Add the following code:
import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
const secrets = new SecretManagerServiceClient();
export async function getSecretValue (name: string) {
const [version] = await secrets.accessSecretVersion({
name: `projects/{{project resource id}}/secrets/${name}/versions/latest`,
});
const payload = version.payload?.data?.toString();
return payload;
}
Retrieve secret from cloud function
The following example updates the onGetBalance
Web3 function example.
Update apps\{{project}}\src\functions\moralis\index.ts
to the following:
import { EvmChain } from '@moralisweb3/common-evm-utils';
import Moralis from 'moralis';
import { getSecretValue } from '../../utils/get-secret-value';
export async function onGetBalance(data: any, context) {
const mySecret = await getSecretValue('moralis');
Moralis.start({
apiKey: mySecret
});
const result = await Moralis.EvmApi.balance.getNativeBalance({
chain: EvmChain.ETHEREUM,
address: data.address,
});
return {
balance: result.result.balance.ether
};
};
This above function is now ready to build
and deploy
with secure access to the secret.
Last updated