Debian Codegraph @

examples/disaster-recovery/README.md

raw
1 # Coordinate disaster recovery with Secret Manager
2
3 ## Background
4
5 This document assumes you are already using the following strategy for
6 detecting and triggering failovers:
7 1. Using an independent service to detect when the primary is down
8 2. Trigger a promotion of an existing read replica to become a primary
9 3. Update a Secret Manager secret with the name of the current primary
10
11 ## Restart Auth proxy when secret changes
12
13 This option uses a wrapper script around the Cloud SQL Auth proxy to detect
14 when the secret has changed, and restart the proxy with the new value. This
15 could be done in many languages, but here’s an example using bash:
16
17 > [failover.sh](examples/disaster-recovery/failover.sh)
18 ```sh
19 #!/bin/bash
20
21 SECRET_ID="my-secret-id" # TODO(developer): replace this value
22 REFRESH_INTERVAL=5
23 PORT=5432 # TODO(developer): change this port as needed
24
25 # Get the latest version of the secret and start the proxy
26 INSTANCE=$(gcloud secrets versions access "latest" --secret="$SECRET_ID")
27 cloud_sql_proxy -instances="$INSTANCE"=tcp:"$PORT" &
28 PID=$!
29
30 # Every 5s, get the latest version of the secret. If it's changed, restart the
31 # proxy with the new value.
32 while true; do
33 sleep $REFRESH_INTERVAL
34 NEW=$(gcloud secrets versions access "latest" --secret="$SECRET_ID")
35 if [ "$INSTANCE" != "$NEW" ]; then
36 INSTANCE=$NEW
37 kill $PID
38 wait $PID
39 cloud_sql_proxy -instances="$INSTANCE"=tcp:"$PORT" &
40 PID=$!
41 fi
42 done
43 ```
44
45 ## Benefits of this approach
46
47 Using this approach will help assist with failovers without needing to
48 reconfigure your application. Instead, by changing the proxy the application
49 will always connect to 127.0.0.1 and won’t need to restart to apply
50 configuration changes. Additionally, it will prevent split brain syndrome by
51 ensuring that your application can only connect to the current “primary”.