GCP Key Management Service + Python for secret information management

background

I want to manage secret information with a python application. This time, secret information is managed in yaml. For encryption and decryption, use GCP's Key Management Service. Decrypt it with a python app so that it can be used.

encryption

Create a key link and key by referring to Quick Start.

First, create a yaml file with secret information

sample_secret.yaml



HOGE_SECRET: HOGEHOGE
FUGA_SECRET: FUGAFUGA

Encrypt this as follows and create sample_secret.yml.encrypted


gcloud kms encrypt --location global --keyring test --key quickstart 
      --plaintext-file sample_secret.yml 
      --ciphertext-file sample_secret.yml.encrypted

Decrypt with python

When using it in a python application, do as follows.


f = open("/path/to/sample_secret.yml.encrypted", "rb")
client = kms_v1.KeyManagementServiceClient()
name = client.crypto_key_path_path(
    'YOUR_PROJECT',
    'global',
    'test',
    'quickstart'
)

res = client.decrypt(name, f.read())
data = yaml.load(res.plaintext, Loader=yaml.BaseLoader)
print(data)

Encrypted secret files should be managed by git, and unencrypted files should be targeted by .gitignore.

Recommended Posts

GCP Key Management Service + Python for secret information management
Python service
[50 counts] Key transmission using Python for Windows
Python learning plan for AI learning Progress management
Get note information using Evernote SDK for Python 3
python [for myself]
Authentication information used by Boto3 (AWS SDK for Python)
Key input that does not wait for key input in Python
Information for controlling the motor with Python on RaspberryPi