Kubernetes access to Google Cloud SQL C# Connection String

4/20/2020

I have a DOTNET Core C# Console Application and i have a string for my connection string, right now, to connect to a local MySql database i use the following connection string:

Server=127.0.0.1;Database=database;Uid=root;Pwd=123;

I have set up a Google Cloud SQL MySql instance and created a database there and assigned a private IP to it. I have also created a GKE cluster. I was following this documentation on connecting from GKE to Cloud SQL using private IP:

https://cloud.google.com/sql/docs/mysql/connect-kubernetes-engine

In that doc, it says i need 2 kubernetes secrets, 1 for the service account credentials, that i used a key generated in the Cloud SQL instance. The other is supposed to be the database credentials. How is this secret supposed to look like, and what is my connection string supposed to look like in order to use the values indicated in the secret.

I have tried to ignore the database credentials secret and used the connection string as it is, only changing the ip to the given private IP, thinking that, for testing purposes should be enough, but with no success.

-- João Reis
c#
google-cloud-platform
kubernetes
mysql

1 Answer

4/20/2020

This is how i got my connectiong string:

var dbHost     = Environment.GetEnvironmentVariable("DB_HOST");
var dbName     = Environment.GetEnvironmentVariable("DB_NAME");
var dbUser     = Environment.GetEnvironmentVariable("DB_USER");
var dbPassword = Environment.GetEnvironmentVariable("DB_PASSWORD");

string connectionString = 
quot;server
={dbHost};database={dbName};uid={dbUser};pwd={dbPassword};";

And use the env on the container in the deployment yml file like this:

     env:
        - name: DB_HOST
          value: 127.0.0.1
        - name: DB_NAME
          value: name
        - name: DB_USER
          valueFrom:
            secretKeyRef:
              name: cloudsql-db-credentials
              key: username
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: cloudsql-db-credentials
              key: password

And i created a generic secret with this command:

kubectl create secret generic cloudsql-db-credentials --from-literal=username=root --from-literal=password=123
-- João Reis
Source: StackOverflow