100% found this document useful (1 vote)
4 views15 pages

Securing A Cloud SQL For PostgreSQL Instance

This document provides a step-by-step guide for securing a Cloud SQL for PostgreSQL instance using customer-managed encryption keys (CMEK), configuring pgAudit for logging, and setting up IAM database authentication. It details the necessary tasks including creating a Cloud SQL instance, enabling pgAudit, and configuring IAM authentication, aimed primarily at PostgreSQL DBAs. The lab requires specific setup instructions and temporary credentials to access Google Cloud resources for hands-on experience.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
4 views15 pages

Securing A Cloud SQL For PostgreSQL Instance

This document provides a step-by-step guide for securing a Cloud SQL for PostgreSQL instance using customer-managed encryption keys (CMEK), configuring pgAudit for logging, and setting up IAM database authentication. It details the necessary tasks including creating a Cloud SQL instance, enabling pgAudit, and configuring IAM authentication, aimed primarily at PostgreSQL DBAs. The lab requires specific setup instructions and temporary credentials to access Google Cloud resources for hands-on experience.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Securing a Cloud SQL for PostgreSQL Instance

experimentLabschedule1 horauniversal_currency_alt1 créditoshow_chartIntroductorio

infoEs posible que este lab incorpore herramientas de IA para facilitar tu aprendizaje.
GSP920

Overview
Customer-managed encryption keys (CMEK) let you use your own cryptographic keys for data at
rest in Cloud SQL. After adding customer-managed encryption keys, whenever an API call is made,
Cloud SQL uses your key to access data.
This lab provides you with step-by-step guidance on how to secure a Cloud SQL for PostgreSQL
instance. You first deploy a new Cloud SQL instance using a CMEK. Once you have created the
Cloud SQL for PostgreSQL instance, you configure pgAudit to selectively record and track SQL
operations performed against that instance, and finally you configure and test Cloud SQL IAM
database authentication.
What you'll do
 Setup CMEK for Cloud SQL for PostgreSQL.
 Enable and configure pgAudit on a Cloud SQL for PostgreSQL instance.
 Configure Cloud SQL for PostgreSQL IAM database authentication.
Target Audience
The content of this hands-on lab will be most applicable to PostgreSQL DBAs. This lab is designed
to give professionals hands-on experience setting up and configuring Google Cloud resources to
support PostgreSQL.
Setup and requirements
Before you click the Start Lab button
Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when
you click Start Lab, shows how long Google Cloud resources are made available to you.
This hands-on lab lets you do the lab activities in a real cloud environment, not in a simulation or
demo environment. It does so by giving you new, temporary credentials you use to sign in and
access Google Cloud for the duration of the lab.
To complete this lab, you need:
 Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito (recommended) or private browser window to run this lab. This prevents
conflicts between your personal account and the student account, which may cause extra charges
incurred to your personal account.
 Time to complete the lab—remember, once you start, you cannot pause a lab.
Note: Use only the student account for this lab. If you use a different Google Cloud account, you
may incur charges to that account.
How to start your lab and sign in to the Google Cloud console
1. Click the Start Lab button. If you need to pay for the lab, a dialog opens for you to select
your payment method. On the left is the Lab Details pane with the following:
 The Open Google Cloud console button
 Time remaining
 The temporary credentials that you must use for this lab
 Other information, if needed, to step through this lab
2. Click Open Google Cloud console (or right-click and select Open Link in Incognito
Window if you are running the Chrome browser).
The lab spins up resources, and then opens another tab that shows the Sign in page.
Tip: Arrange the tabs in separate windows, side-by-side.
Note: If you see the Choose an account dialog, click Use Another Account.
3. If necessary, copy the Username below and paste it into the Sign in dialog.
student-02-dbfd50d2b9fc@[Link]
Se copió correctamente
content_copy
You can also find the Username in the Lab Details pane.
4. Click Next.
5. Copy the Password below and paste it into the Welcome dialog.
n1YHgdgd53z5
Se copió correctamente
content_copy
You can also find the Password in the Lab Details pane.
6. Click Next.
Important: You must use the credentials the lab provides you. Do not use your Google Cloud
account [Link]: Using your own Google Cloud account for this lab may incur extra
charges.
7. Click through the subsequent pages:
 Accept the terms and conditions.
 Do not add recovery options or two-factor authentication (because this is a temporary
account).
 Do not sign up for free trials.
After a few moments, the Google Cloud console opens in this tab.
Note: To access Google Cloud products and services, click the Navigation menu or type the
service or product name in
the Search field.

Task 1. Create a Cloud SQL for PostgreSQL instance with CMEK enabled
In this task you will create a Cloud SQL for PostgreSQL instance with CMEK enabled. It is imperative
that you keep the keys safe as you cannot manage your database without them.
Create a per-product, per-project service account for Cloud SQL
You can create the service account you require for Cloud SQL CMEK using the gcloud beta services
identity create command.
1. In Cloud Shell, run:
export PROJECT_ID=$(gcloud config list --format 'value([Link])')
gcloud beta services identity create \
--service=[Link] \
--project=$PROJECT_ID
Se copió correctamente
content_copy
2. Click the Authorize button if prompted.
This creates the service account that you will bind to the CMEK in a later step.
Create a Cloud Key Management Service keyring and key
In this step you will create a Cloud KMS keyring and key to use with CMEK.
1. In Cloud Shell, to create the Cloud KMS keyring, run:
export KMS_KEYRING_ID=cloud-sql-keyring
export ZONE=$(gcloud compute instances list --filter="NAME=bastion-vm" --format=json | jq -r .
[].zone | awk -F "/zones/" '{print $NF}')
export REGION=${ZONE::-2}
gcloud kms keyrings create $KMS_KEYRING_ID \
--location=$REGION
Se copió correctamente
content_copy
2. In Cloud Shell, to create the Cloud KMS key, run:
export KMS_KEY_ID=cloud-sql-key
gcloud kms keys create $KMS_KEY_ID \
--location=$REGION \
--keyring=$KMS_KEYRING_ID \
--purpose=encryption
Se copió correctamente
content_copy
3. In Cloud Shell, to bind the key to the service account, run:
export PROJECT_NUMBER=$(gcloud projects describe ${PROJECT_ID} \
--format 'value(projectNumber)')
gcloud kms keys add-iam-policy-binding $KMS_KEY_ID \
--location=$REGION \
--keyring=$KMS_KEYRING_ID \
--member=serviceAccount:service-${PROJECT_NUMBER}@gcp-sa-cloud-
[Link] \
--role=roles/[Link]
Se copió correctamente
content_copy
The service account name is the same name that was returned by the gcloud beta services identity
create command in the previous sub-task.
Create a Cloud SQL instance with CMEK enabled
In this step you will create a Cloud SQL for PostgreSQL instance with CMEK enabled. It is not
possible to patch an existing instance to enable CMEK, so you should bear this in mind if you plan
to use CMEK to encrypt your data.
In order to access your Cloud SQL instance from external development or application
environments, you can configure the Cloud SQL instance with a public IP address and control
access by allowlisting the IP address of those environments. This limits access to the public
interface to those address ranges that you specify.
You will treat the Compute Engine VM instance in the lab as a development environment and will
therefore need the to allow list the external IP address of that instance. You will also add the
external IP address of the Cloud Shell to the allowlist to make it easier to complete tasks later in
the lab.
1. In Cloud Shell, find the external IP address of the bastion-vm VM instance:
export AUTHORIZED_IP=$(gcloud compute instances describe bastion-vm \
--zone=$ZONE \
--format 'value(networkInterfaces[0].[Link])')
echo Authorized IP: $AUTHORIZED_IP
Se copió correctamente
content_copy
2. In Cloud Shell, find the external IP address of the Cloud Shell:
export CLOUD_SHELL_IP=$(curl [Link])
echo Cloud Shell IP: $CLOUD_SHELL_IP
Se copió correctamente
content_copy
3. In Cloud Shell, create your Cloud SQL for PostgreSQL instance with:
export KEY_NAME=$(gcloud kms keys describe $KMS_KEY_ID \
--keyring=$KMS_KEYRING_ID --location=$REGION \
--format 'value(name)')

export CLOUDSQL_INSTANCE=postgres-orders
gcloud sql instances create $CLOUDSQL_INSTANCE \
--project=$PROJECT_ID \
--authorized-networks=${AUTHORIZED_IP}/32,$CLOUD_SHELL_IP/32 \
--disk-encryption-key=$KEY_NAME \
--database-version=POSTGRES_13 \
--cpu=1 \
--memory=3840MB \
--region=$REGION \
--root-password=supersecret!
Se copió correctamente
content_copy
4. Enter 'y' if asked after entering the command.
Create a Cloud SQL instance with CMEK enabled
Revisar mi progreso
Task 2. Enable and configure pgAudit on a Cloud SQL for PostgreSQL database
In this task you will enable and configure the pgAudit database extension which enables fine-
grained control of logging of all types of database activity.
1. In Cloud Shell enter the following to add the pgAudit database flags to your Cloud SQL
instance:
gcloud sql instances patch $CLOUDSQL_INSTANCE \
--database-flags cloudsql.enable_pgaudit=on,[Link]=all
Se copió correctamente
content_copy
2. Hit enter to confirm and continue. Wait a minute for the patch command to complete before
continuing.
3. In Cloud Console, on the Navigation menu ( ), click Databases > SQL and click on the
Cloud SQL instance named postgres-orders.
4. In the Cloud SQL Overview panel, top menu, click Restart and Restart again in the pop-up
dialog.
It will take a minute to restart your Cloud SQL for PostgreSQL instance, then continue below.
5. In Cloud Console, in the Connect to this instance section, click Open Cloud Shell. A
command will be auto-populated to the Cloud Shell.
6. Run that command and enter the password supersecret! when prompted. A psql session will
start in Cloud Shell.
7. In psql, to create the orders database and enable the pgAudit extension to log all reads and
writes, run:
CREATE DATABASE orders;
\c orders;
Se copió correctamente
content_copy
8. Enter the password supersecret! again.
9. In psql, to create and configure the database extension, run:
CREATE EXTENSION pgaudit;
ALTER DATABASE orders SET [Link] = 'read,write';
Se copió correctamente
content_copy
Enable Audit Logging in Cloud Console
In this step you will enable Audit Logging in Cloud Console.
1. In Cloud Console, on the Navigation menu ( ), click IAM & Admin > Audit Logs.
2. In the Filter box, type Cloud SQL and select the entry in the drop-down list.
3. Check the checkbox for Cloud SQL on the left and all the checkboxes in the Info Panel on
the right.
4. Click the Save button in the Info Panel.
Populate a database on Cloud SQL for PostgreSQL
In this step you will populate the orders database with data provided to you.
1. Click the + icon on the Cloud Shell title bar to open a new tab in the Cloud Shell, and in that
tab, to download the data and database population scripts, run:
export SOURCE_BUCKET=gs://cloud-training/gsp920
gsutil -m cp ${SOURCE_BUCKET}/create_orders_db.sql .
gsutil -m cp ${SOURCE_BUCKET}/DDL/distribution_centers_data.csv .
gsutil -m cp ${SOURCE_BUCKET}/DDL/inventory_items_data.csv .
gsutil -m cp ${SOURCE_BUCKET}/DDL/order_items_data.csv .
gsutil -m cp ${SOURCE_BUCKET}/DDL/products_data.csv .
gsutil -m cp ${SOURCE_BUCKET}/DDL/users_data.csv .
Se copió correctamente
content_copy
2. In the same Cloud Shell session, create and populate the database as follows:
export CLOUDSQL_INSTANCE=postgres-orders
export POSTGRESQL_IP=$(gcloud sql instances describe $CLOUDSQL_INSTANCE --
format="value(ipAddresses[0].ipAddress)")
export PGPASSWORD=supersecret!
psql "sslmode=disable user=postgres hostaddr=${POSTGRESQL_IP}" \
-c "\i create_orders_db.sql"
Se copió correctamente
content_copy
It will take a minute for the orders database to be populated.
3. Exit the terminal session in the new tab:
exit
Se copió correctamente
content_copy
4. In your psql session in the remaining Cloud Shell tab, to further log all SELECT operations on
a particular relation, for example the order_items table, run the following commands:
CREATE ROLE auditor WITH NOLOGIN;
ALTER DATABASE orders SET [Link] = 'auditor';
GRANT SELECT ON order_items TO auditor;
Se copió correctamente
content_copy
5. Run the first SELECT query below :
Summary of orders by usersSummary by individual productOrders by distribution center
SELECT
[Link] AS users_id,
users.first_name AS users_first_name,
users.last_name AS users_last_name,
COUNT(DISTINCT order_items.order_id ) AS order_items_order_count,
COALESCE(SUM(order_items.sale_price ), 0) AS order_items_total_revenue
FROM order_items
LEFT JOIN users ON order_items.user_id = [Link]
GROUP BY 1, 2, 3
ORDER BY 4 DESC
LIMIT 500;
Se copió correctamente
content_copy
6. The output is 500 rows long, so hit q and the colon prompt to return to the orders=> prompt.
7. Repeat the last two steps for the other two queries tabs in the code block.
8. Exit psql:
\q
Se copió correctamente
content_copy
View pgAudit logs
In this step you will view the logging of your database updates and queries in the pgAudit logs.
1. In Cloud Console, on the Navigation menu ( ), click Observablity > Logging > Logs
Explorer.
2. In the Query tab of the Logs Explorer, paste the following and click the Run query button:
[Link]="cloudsql_database"
logName="projects/qwiklabs-gcp-02-175f45bc5113/logs/[Link]
%2Fdata_access"
[Link].@type="[Link]/[Link]"
Se copió correctamente
content_copy
3. In the histogram displayed, you can see the audit activity associated with your DDL inserts
and the SELECT queries you ran earlier.

4. Click on the last bar on the histogram - this corresponds to the SELECT queries you ran.
In the Query results panel below the histogram, the log entries are listed.
5. Expand a log entry, and under [Link] you will see the SELECT query.
Enable and configure pgAudit on a Cloud SQL for PostgreSQL database
Revisar mi progreso
Task 3. Configure Cloud SQL IAM database authentication
In this task you will configure Cloud SQL IAM database authentication. All of the database access
and update tasks you have performed so far have used built-in PostgreSQL user accounts. You can
also create Cloud SQL for PostgreSQL users using Cloud IAM accounts. Database users can
authenticate to Cloud SQL using Cloud IAM instead of using built-in database accounts and fine-
grained permissions at the database level can be granted to those users.
In this task you will configure the lab user account as a Cloud SQL IAM user, grant that user access
to the orders.order_items database table using the postgres administrator account, and then test
access to the orders.order_items database table from the command line using the psql command
line utility.
The authentication process that is used in this task is explained in detail in the IAM authentication
documentation for Cloud SQL for PostgreSQL.
Test database access using a Cloud IAM user before Cloud SQL IAM authentication is configured.
You will attempt to access the database using a Cloud IAM user before Cloud SQL IAM
authentication haas been enabled in order to establish that the Cloud IAM user cannot initially
access the data.
 Test access to the orders database using the lab student account as the username:
export USERNAME=$(gcloud config list --format="value([Link])")
export CLOUDSQL_INSTANCE=postgres-orders
export POSTGRESQL_IP=$(gcloud sql instances describe $CLOUDSQL_INSTANCE --
format="value(ipAddresses[0].ipAddress)")
export PGPASSWORD=$(gcloud auth print-access-token)
psql --host=$POSTGRESQL_IP $USERNAME --dbname=orders
Se copió correctamente
content_copy
This connection attempt will fail and you will see an authentication failed message similar to the
following because the Cloud SQL IAM user has not been created yet:
psql --host=$POSTGRESQL_IP $USERNAME --dbname=orders
psql: error: connection to server at "[Link]", port 5432 failed: FATAL: password
authentication failed for user "student-01-22fa974575e4@[Link]"
connection to server at "[Link]", port 5432 failed: FATAL: password authentication failed
for user "student-01-22fa974575e4@[Link]"
Cloud SQL IAM database authentication uses OAuth 2.0 access tokens is the Cloud IAM user
password, which are short-lived and only valid for one hour so you should regenerate the token
every time you need to authenticate. The access token should always be passed into
the psql command using the PGPASSWORD environment variable as the buffer for
the psql password parameter is too small to hold the OAuth 2.0 token string.
Create a Cloud SQL IAM user
You will now create a Cloud SQL IAM user and confirm that Cloud SQL IAM user authentication has
been enabled.
1. In Cloud Console, on the Navigation menu ( ), click Databases > SQL and click on the
Cloud SQL instance named postgres-orders.
2. In the Cloud SQL Overview panel, in the Configuration panel note that the Database
flags list includes [Link] and cloudsql.enable_pgaudit only.
3. Click Users to open the Users panel.
4. Click Add user account.
5. Select Cloud IAM.
6. In the Principal box enter the lab student name.
7. Click Add.
8. Wait for the new user to be added.
9. Click Overview and now note that cloudsql.iam_authentication has been added to the
list of database flags.
Grant the Cloud IAM user access to a Cloud SQL database table
You will now connect to the postgres-orders instance using the built in postgres administrator
account and grant access to the orders.order_items table to the Cloud IAM user.
1. In the Cloud Shell connect to the postgres-orders Cloud SQL instance as
the postgres administrative user:
gcloud sql connect postgres-orders --user=postgres --quiet
Se copió correctamente
content_copy
2. When prompted enter the password: supersecret!.
3. Enter the following SQL command to switch to the orders database:
\c orders
Se copió correctamente
content_copy
When prompted for a password enter supersecret! again.
4. Enter the following SQL command to grant the lab user all permissions on
the order_items table. The Cloud IAM username for the lab has been inserted into this query
for you.
GRANT ALL PRIVILEGES ON TABLE order_items TO "student-02-dbfd50d2b9fc@[Link]";
\q
Se copió correctamente
content_copy
Test database access using a Cloud IAM user after Cloud SQL IAM authentication is configured.
You will repeat the attempt to access the database using a Cloud IAM user after Cloud SQL IAM
authentication has been enabled in order to establish that the Cloud IAM user can now access the
data.
You can now test access to the database again using the Cloud IAM user instead of the built-
in postgres user:
1. In the Cloud Shell enter the following command to connect to the database using the Cloud
IAM database user:
export PGPASSWORD=$(gcloud auth print-access-token)
psql --host=$POSTGRESQL_IP $USERNAME --dbname=orders
Se copió correctamente
content_copy
This connection succeeds and you are now connected the instance using Cloud IAM user
authentication.
2. Test your access permission by running this query:
SELECT COUNT(*) FROM order_items;
Se copió correctamente
content_copy
This will now return a successful result:
orders=> SELECT COUNT(*) FROM order_items;
count
--------
198553
(1 row)
3. Confirm that you do not have access to one of the other tables by running this query:
SELECT COUNT(*) FROM users;
Se copió correctamente
content_copy
This will now return a successful result:
orders=> SELECT COUNT(*) FROM users;
ERROR: permission denied for table users
Configure Cloud SQL IAM database authentication
Revisar mi progreso
Congratulations!
In this lab, you secured data at rest in Cloud SQL for PostgreSQL using a customer managed
encryption key, enabled pgAudit, and configured Cloud SQL IAM database user authentication.
Google Cloud training and certification
...helps you make the most of Google Cloud technologies. Our classes include technical skills and
best practices to help you get up to speed quickly and continue your learning journey. We offer
fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy
schedule. Certifications help you validate and prove your skill and expertise in Google Cloud
technologies.
Manual Last Updated April 23, 2024
Lab Last Tested April 15, 2024
Copyright 2025 Google LLC. All rights reserved. Google and the Google logo are trademarks of
Google LLC. All other company and product names may be trademarks of the respective
companies with which they are associated.
navigate_beforeAnterior
Siguientenavigate_next
close

Antes de comenzar
1. Los labs crean un proyecto de Google Cloud y recursos por un tiempo determinado
.
2. Los labs tienen un límite de tiempo y no tienen la función de pausa. Si finalizas el lab,
deberás reiniciarlo desde el principio.
3. En la parte superior izquierda de la pantalla, haz clic en Comenzar lab para empezar
Skip
Finish
closetask_alt
Detalles de puntuación
Aceptar
close

Este contenido no está disponible en este momento


Te enviaremos una notificación por correo electrónico cuando esté disponible
No, gracias
Sí, notificarme
close

¡Genial!
Nos comunicaremos contigo por correo electrónico si está disponible
Volver a la pantalla
close

Entendido
close

Un lab a la vez
Confirma para finalizar todos los labs existentes y comenzar este
Cancelar
Confirmar
close
Cancelar
close
¿Cuál es su grado de satisfacción con este lab?*
Cancelar
Enviar
closeerror_outline
¿Confirmas la acción? Es posible que no puedas reiniciar el lab y, si lo haces, deberás comenzar
desde el principio.
Cancelar
Finalizar lab
closeerror
Hay una nueva versión disponible de este curso. Se transferirá el progreso si decides actualizar. Sin
embargo, tu porcentaje de finalización puede cambiar si la nueva versión agrega o quita
actividades de aprendizaje. Haz clic en el botón de vista previa para ver los cambios del curso
antes de actualizar.
Cancelar
Vista previa

You might also like