Search code examples
pythonpostgresqlpsycopg2

Where to put ssl certificates when trying to connect to a remote database using psycopg2?


I have created a Google PostgreSQL instance and I'm trying to operate it from a remote webserver, I have whitelisted the IP and turned on SSL-only mode. I created client certificates, but I'm clueless as to where to put them or how to reference them. I can't find anything about it online.

Any help would be appreciated

My psycopg2 connect statement looks like this and gives me an error saying it needs client certificates:

conn = psycopg2.connect(
            user="postgres",
            password="password",
            host="{IP_ADDRESS}",
            port="5432",
            database="testdb",
            sslmode="require",
}

Solution

  • I figured it out myself, I got some instructions on how to connect with psql and that also applied to psycopg2.

    Google instructed me I could connect through psql with this terminal command:

      psql "sslmode=verify-ca sslrootcert=server-ca.pem \
          sslcert=client-cert.pem sslkey=client-key.pem \
          hostaddr={IP_ADDRESS} \
          port=5432 \
          user=postgres dbname=postgres"
    

    So I edited my connect function to add these keys:

    sslrootcert=server-ca.pem
    sslcert=client-cert.pem
    sslkey=client-key.pem
    

    Make sure to run

    $ chmod 0600 client-key.pem
    

    Or it won't work