Set GCP Service account details in environment variable in .net

83 Views Asked by At

I want to connect from azure web app to google cloud platform project. According to the documentation, I need to set an environment variable - GOOGLE_APPLICATION_CREDENTIALS - to the location of json file containing the private key downloaded from gcp project for service account. I am saving the json file on a blob and setting its location in the environment variable, but it prepends the name of the current working directory to the blob path.

How can I avoid uploading the json file to the repository . I am using .net.

The blob path is changed from "https:/myfirstblob.blob.core.windows.net/mygcp-service-account/creds.json" is changed to "C:\mycurrentworkingdirectory...\..\https:\myfirstblob.blob.core.windows.net\mygcp-service-account\creds.json"

1

There are 1 best solutions below

1
s_v On

I used the following approach to avoid setting the environment variable GOOGLE_APPLICATION_CREDENTIALS - I added the json properties in my configuration file. The values of which I can pick from azure key vault. There is a provision in google clients to set credentials using JsonCredentialParameters. Here I am using PredictionServiceClientBuilder client.

 var parameters = new JsonCredentialParameters
 {
     Type = _gcpServiceAccountConfiguration.Type,
     ProjectId = _gcpServiceAccountConfiguration.ProjectId,
     PrivateKeyId = _gcpServiceAccountConfiguration.PrivateKeyId,
     PrivateKey = _gcpServiceAccountConfiguration.PrivateKey.Replace("\\n", "\n"),
     ClientEmail = _gcpServiceAccountConfiguration.ClientEmail,
     ClientId = _gcpServiceAccountConfiguration.ClientId,
     TokenUrl = _gcpServiceAccountConfiguration.TokenUrl
 };

await new PredictionServiceClientBuilder
            {
                Settings = settings,
                Endpoint = "",
                // Below is the main part          
                GoogleCredential = GoogleCredential.FromJsonParameters(parameters)     
        }.BuildAsync();

Below 2 alternative properties are also provided by google clients for setting credentials -

new PredictionServiceClientBuilder {
    CredentialsPath = "C:\\mypath\\creds.json"
}

AND

string jsonCreds = "{\r\n  \"type\": \"service_account\",\r\n  \"project_id\": \"my-project\",\r\n  \"private_key_id\": ..}";
new PredictionServiceClientBuilder {
    JsonCredentials = jsonCreds
}