|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2022 Google LLC |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +""" |
| 16 | +command line application and sample code for creating a new secret with |
| 17 | +user managed replication. |
| 18 | +""" |
| 19 | + |
| 20 | +import argparse |
| 21 | + |
| 22 | + |
| 23 | +def create_ummr_secret(project_id, secret_id, locations): |
| 24 | + """ |
| 25 | + Create a new secret with the given name. A secret is a logical wrapper |
| 26 | + around a collection of secret versions. Secret versions hold the actual |
| 27 | + secret material. |
| 28 | + """ |
| 29 | + |
| 30 | + # Import the Secret Manager client library. |
| 31 | + from google.cloud import secretmanager |
| 32 | + |
| 33 | + # Create the Secret Manager client. |
| 34 | + client = secretmanager.SecretManagerServiceClient() |
| 35 | + |
| 36 | + # Build the resource name of the parent project. |
| 37 | + parent = f"projects/{project_id}" |
| 38 | + |
| 39 | + # Create the secret. |
| 40 | + response = client.create_secret( |
| 41 | + request={ |
| 42 | + "parent": parent, |
| 43 | + "secret_id": secret_id, |
| 44 | + "secret": { |
| 45 | + "replication": { |
| 46 | + "user_managed": {"replicas": [{"location": x} for x in locations]} |
| 47 | + } |
| 48 | + }, |
| 49 | + } |
| 50 | + ) |
| 51 | + |
| 52 | + # Print the new secret name. |
| 53 | + print("Created secret: {}".format(response.name)) |
| 54 | + |
| 55 | + return response |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + parser = argparse.ArgumentParser( |
| 60 | + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter |
| 61 | + ) |
| 62 | + parser.add_argument("project_id", help="id of the GCP project") |
| 63 | + parser.add_argument("secret_id", help="id of the secret to create") |
| 64 | + parser.add_argument( |
| 65 | + "--locations", nargs="+", help="list of locations for secret replication" |
| 66 | + ) |
| 67 | + args = parser.parse_args() |
| 68 | + |
| 69 | + create_ummr_secret(args.project_id, args.secret_id, args.locations) |
0 commit comments