センシティブデータを検知、マスキングできるCloud Data Loss Prevention (DLP) APIを、pythonにて試してみた備忘録です。
Cloud DLP APIをおそらく、GCPしかなかったはず
まず、cloud DLP用のサービスアカウント作成します。
サービスアカウント作成
gcloud iam service-accounts create dlp-api --display-name "dlp-api"
サービスアカウント用credentialsを発行
gcloud iam service-accounts keys create ./key.json --iam-account dlp-api@xxxxxxxxxxxxxxxx.iam.gserviceaccount.com
dlp用の権限ロールを付与
gcloud projects add-iam-policy-binding cms-production-1225 --member serviceAccount:dlp-api@xxxxxxxxxxxxxxxx.iam.gserviceaccount.com --role roles/dlp.user
gcloudで権限確認する場合は以下で。(gcloudでRequireされるpythonは2.7なので、DLPで必要なpythonとは差がある)
gcloud auth activate-service-account --key-file key.json
Macとかローカル環境で試す場合は、環境変数にて
export GOOGLE_APPLICATION_CREDENTIALS=../key.json
次に、Cloud DLP用のpyton moduleをインストール
https://googleapis.github.io/google-cloud-python/latest/dlp/index.html
Cloud DLPは、python 3.4以上をサポートしています。自分はpython 3.7.2で確認
https://googleapis.github.io/google-cloud-python/latest/dlp/index.htmlに記載しているサンプルコードそのままで動かなかった。上記サイトに記載しているサンプルは引数がAPIとは異なっているのが原因。ドキュメントのほうも更新してくれるといいのですが。
試したコードは以下になります。
from google.cloud import dlp_v2
client = dlp_v2.DlpServiceClient()
parent = client.project_path('xxxxxxxxxxxxxxxxxxx')
name = 'EMAIL_ADDRESS'
info_types_elements = {'name' : name }
info_types = [info_types_elements]
inspect_config = {'info_types' : info_types}
deidentify_config = {
'info_type_transformations': {
'transformations': [
{
'primitive_transformation': {
'character_mask_config': {
'masking_character': 'x',
'number_to_mask': 20
}
}
}
]
}
}
value = 'My email is not example@example.com , aaa@bbb.com , xxxx@xxxxx.co.jp '
items = {'value' : value }
response = client.deidentify_content(parent, deidentify_config,inspect_config, items)
print(response)
下記のようにメールアドレスをマスキングして出力してくれる。
My email is not xxxxxxxxxxxxxxxxxxx , xxxxxxxxxxx , xxxxxxxxxxxxxxxx
取り込み時、Cloud Functions、Google dataflow等のロード処理で使ったりすると、マスキングしたデータができるので、本番そのまま検証に
もっていけないとかの場合に有益かと思います。