Home > Software engineering >  Connecting to Cloud SQL postgres instance with SSL in python
Connecting to Cloud SQL postgres instance with SSL in python

Time:08-24

I am trying to connect to a postgres instance I have in cloud sql. I have everything set up and am able to connect to it if ssl encryption is turned off. But now that I have it on I am trying to connect but running into some error.

  def run():
    connector = Connector()
    def getconn():
        conn = connector.connect(
            os.getenv("CONNECTION_NAME"),
            "pg8000",
            user = os.getenv('DB_USERNAME'),
            password = os.getenv("DB_PASSWORD"),
            db=os.getenv('DB_NAME'),
            ip_type= IPTypes.PRIVATE
        )
        return conn
    pool = sqlalchemy.create_engine(
        "postgresql pg8000://",
        creator=getconn,
   pool.execute("CREATE TABLE........;")

All the certs are stored in secret manager as strings so I am using env variables to grab them, which is why I used cadata for example. But running into this error cadata does not contain a certificate why is this error coming up?

CodePudding user response:

I'd recommend using the Cloud SQL Python Connector to connect to Cloud SQL from Python as it will generate the SSL context for you, meaning no need to manage SSL certificates! It also has additional benefits of not needing to authorize networks etc.

You can find a code sample for the Python Connector similar to the one you are using for establishing a TCP connection.

There is also an interactive getting started Colab Notebook that will walk you through using the Python Connector without you needing to change a single line of code!

It makes connecting to Cloud SQL both easy and secure.

  • Related