diff --git a/secretmanager/AUTHORING_GUIDE.md b/secretmanager/AUTHORING_GUIDE.md new file mode 100644 index 000000000000..55c97b32f4c1 --- /dev/null +++ b/secretmanager/AUTHORING_GUIDE.md @@ -0,0 +1 @@ +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/AUTHORING_GUIDE.md \ No newline at end of file diff --git a/secretmanager/CONTRIBUTING.md b/secretmanager/CONTRIBUTING.md new file mode 100644 index 000000000000..34c882b6f1a3 --- /dev/null +++ b/secretmanager/CONTRIBUTING.md @@ -0,0 +1 @@ +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/CONTRIBUTING.md \ No newline at end of file diff --git a/secretmanager/snippets/README.rst b/secretmanager/snippets/README.rst new file mode 100644 index 000000000000..141855b12b94 --- /dev/null +++ b/secretmanager/snippets/README.rst @@ -0,0 +1,508 @@ + +.. This file is automatically generated. Do not edit this file directly. + +Google Secret Manager Python Samples +=============================================================================== + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/README.rst + + +This directory contains samples for Google Secret Manager. `Google Secret Manager` is a service that allows you to store, manage, and secure access to application secrets. + + + + +.. _Google Secret Manager: https://cloud.google.com/secret-manager + + +Setup +------------------------------------------------------------------------------- + + + +Authentication +++++++++++++++ + +This sample requires you to have authentication setup. Refer to the +`Authentication Getting Started Guide`_ for instructions on setting up +credentials for applications. + +.. _Authentication Getting Started Guide: + https://cloud.google.com/docs/authentication/getting-started + + + + +Install Dependencies +++++++++++++++++++++ + +#. Clone python-docs-samples and change directory to the sample directory you want to use. + + .. code-block:: bash + + $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git + +#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. + + .. _Python Development Environment Setup Guide: + https://cloud.google.com/python/setup + +#. Create a virtualenv. Samples are compatible with Python 3.6+. + + .. code-block:: bash + + $ virtualenv env + $ source env/bin/activate + +#. Install the dependencies needed to run the samples. + + .. code-block:: bash + + $ pip install -r requirements.txt + +.. _pip: https://pip.pypa.io/ +.. _virtualenv: https://virtualenv.pypa.io/ + + + + + + +Samples +------------------------------------------------------------------------------- + + +Quickstart ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/quickstart.py,secretmanager/api-client/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python quickstart.py + + + + +Access Secret Version ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/access_secret_version.py,secretmanager/api-client/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python access_secret_version.py + + + usage: access_secret_version.py [-h] project_id secret_id version_id + + command line application and sample code for accessing a secret version. + + positional arguments: + project_id id of the GCP project + secret_id id of the secret to access + version_id version to access + + optional arguments: + -h, --help show this help message and exit + + + + + +Add Secret Version ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/add_secret_version.py,secretmanager/api-client/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python add_secret_version.py + + + usage: add_secret_version.py [-h] project_id secret_id payload + + command line application and sample code for adding a secret version with the + specified payload to an existing secret. + + positional arguments: + project_id id of the GCP project + secret_id id of the secret in which to add + payload secret material payload + + optional arguments: + -h, --help show this help message and exit + + + + + +Create Secret ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/create_secret.py,secretmanager/api-client/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python create_secret.py + + + usage: create_secret.py [-h] project_id secret_id + + command line application and sample code for creating a new secret. + + positional arguments: + project_id id of the GCP project + secret_id id of the secret to create + + optional arguments: + -h, --help show this help message and exit + + + + + +Delete Secret ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/delete_secret.py,secretmanager/api-client/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python delete_secret.py + + + usage: delete_secret.py [-h] project_id secret_id + + command line application and sample code for deleting an existing secret. + + positional arguments: + project_id id of the GCP project + secret_id id of the secret to delete + + optional arguments: + -h, --help show this help message and exit + + + + + +Destroy Secret Version ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/destroy_secret_version.py,secretmanager/api-client/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python destroy_secret_version.py + + + usage: destroy_secret_version.py [-h] project_id secret_id version_id + + command line application and sample code for destroying a secret verison. + + positional arguments: + project_id id of the GCP project + secret_id id of the secret from which to act + version_id id of the version to destroy + + optional arguments: + -h, --help show this help message and exit + + + + + +Enable Secret Version ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/enable_secret_version.py,secretmanager/api-client/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python enable_secret_version.py + + + usage: enable_secret_version.py [-h] project_id secret_id version_id + + command line application and sample code for enabling a secret version. + + positional arguments: + project_id id of the GCP project + secret_id id of the secret from which to act + version_id id of the version to enable + + optional arguments: + -h, --help show this help message and exit + + + + + +Get Secret Version ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/get_secret_version.py,secretmanager/api-client/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python get_secret_version.py + + + usage: get_secret_version.py [-h] project_id secret_id version_id + + command line application and sample code for getting metdata about a secret + version, but not the secret payload. + + positional arguments: + project_id id of the GCP project + secret_id id of the secret from which to act + version_id id of the version to get + + optional arguments: + -h, --help show this help message and exit + + + + + +IAM Grant Access ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/iam_grant_access.py,secretmanager/api-client/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python iam_grant_access.py + + + usage: iam_grant_access.py [-h] project_id secret_id member + + command line application and sample code for granting access to a secret. + + positional arguments: + project_id id of the GCP project + secret_id id of the secret to get + member member to grant access + + optional arguments: + -h, --help show this help message and exit + + + + + +IAM Revoke Access ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/iam_revoke_access.py,secretmanager/api-client/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python iam_revoke_access.py + + + usage: iam_revoke_access.py [-h] project_id secret_id member + + command line application and sample code for revoking access to a secret. + + positional arguments: + project_id id of the GCP project + secret_id id of the secret to get + member member to revoke access + + optional arguments: + -h, --help show this help message and exit + + + + + +Get Secret ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/get_secret.py,secretmanager/api-client/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python get_secret.py + + + usage: get_secret.py [-h] project_id secret_id + + command line application and sample code for getting metadata about a secret. + + positional arguments: + project_id id of the GCP project + secret_id id of the secret to get + + optional arguments: + -h, --help show this help message and exit + + + + + +List Secret Versions ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/list_secret_versions.py,secretmanager/api-client/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python list_secret_versions.py + + + usage: list_secret_versions.py [-h] project_id secret_id + + command line application and sample code for listing secret versions of a + secret. + + positional arguments: + project_id id of the GCP project + secret_id id of the secret in which to list + + optional arguments: + -h, --help show this help message and exit + + + + + +List Secrets ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/list_secrets.py,secretmanager/api-client/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python list_secrets.py + + + usage: list_secrets.py [-h] project_id + + command line application and sample code for listing secrets in a project. + + positional arguments: + project_id id of the GCP project + + optional arguments: + -h, --help show this help message and exit + + + + + +Update Secret ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +.. image:: https://gstatic.com/cloudssh/images/open-btn.png + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=secretmanager/api-client/update_secret.py,secretmanager/api-client/README.rst + + + + +To run this sample: + +.. code-block:: bash + + $ python update_secret.py + + + usage: update_secret.py [-h] --secret-id SECRET_ID project_id + + positional arguments: + project_id id of the GCP project + + optional arguments: + -h, --help show this help message and exit + --secret-id SECRET_ID + + + + + + + + + +.. _Google Cloud SDK: https://cloud.google.com/sdk/ diff --git a/secretmanager/snippets/README.rst.in b/secretmanager/snippets/README.rst.in new file mode 100644 index 000000000000..ddd46a40ed47 --- /dev/null +++ b/secretmanager/snippets/README.rst.in @@ -0,0 +1,58 @@ +# This file is used to generate README.rst + +product: + name: Google Secret Manager + short_name: Secret Manager + url: https://cloud.google.com/secret-manager + description: > + `Google Secret Manager` is a service that allows you to store, manage, + and secure access to application secrets. + +setup: +- auth +- install_deps + +samples: +- name: Quickstart + file: quickstart.py +- name: Access Secret Version + file: access_secret_version.py + show_help: True +- name: Add Secret Version + file: add_secret_version.py + show_help: True +- name: Create Secret + file: create_secret.py + show_help: True +- name: Delete Secret + file: delete_secret.py + show_help: True +- name: Destroy Secret Version + file: destroy_secret_version.py + show_help: True +- name: Enable Secret Version + file: enable_secret_version.py + show_help: True +- name: Get Secret Version + file: get_secret_version.py + show_help: True +- name: IAM Grant Access + file: iam_grant_access.py + show_help: True +- name: IAM Revoke Access + file: iam_revoke_access.py + show_help: True +- name: Get Secret + file: get_secret.py + show_help: True +- name: List Secret Versions + file: list_secret_versions.py + show_help: True +- name: List Secrets + file: list_secrets.py + show_help: True +- name: Update Secret + file: update_secret.py + show_help: True + +folder: secretmanager/api-client diff --git a/secretmanager/snippets/access_secret_version.py b/secretmanager/snippets/access_secret_version.py new file mode 100644 index 000000000000..c620ea32f84b --- /dev/null +++ b/secretmanager/snippets/access_secret_version.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python + +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +""" +command line application and sample code for accessing a secret version. +""" + +import argparse + + +# [START secretmanager_access_secret_version] +def access_secret_version(project_id, secret_id, version_id): + """ + Access the payload for the given secret version if one exists. The version + can be a version number as a string (e.g. "5") or an alias (e.g. "latest"). + """ + + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the resource name of the secret version. + name = client.secret_version_path(project_id, secret_id, version_id) + + # Access the secret version. + response = client.access_secret_version(name) + + # Print the secret payload. + # + # WARNING: Do not print the secret in a production environment - this + # snippet is showing how to access the secret material. + payload = response.payload.data.decode('UTF-8') + print('Plaintext: {}'.format(payload)) +# [END secretmanager_access_secret_version] + + return response + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='id of the GCP project') + parser.add_argument('secret_id', help='id of the secret to access') + parser.add_argument('version_id', help='version to access') + args = parser.parse_args() + + access_secret_version(args.project_id, args.secret_id, args.version_id) diff --git a/secretmanager/snippets/add_secret_version.py b/secretmanager/snippets/add_secret_version.py new file mode 100644 index 000000000000..51be8716f975 --- /dev/null +++ b/secretmanager/snippets/add_secret_version.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python + +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +""" +command line application and sample code for adding a secret version with the +specified payload to an existing secret. +""" + +import argparse + + +# [START secretmanager_add_secret_version] +def add_secret_version(project_id, secret_id, payload): + """ + Add a new secret version to the given secret with the provided payload. + """ + + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the resource name of the parent secret. + parent = client.secret_path(project_id, secret_id) + + # Convert the string payload into a bytes. This step can be omitted if you + # pass in bytes instead of a str for the payload argument. + payload = payload.encode('UTF-8') + + # Add the secret version. + response = client.add_secret_version(parent, {'data': payload}) + + # Print the new secret version name. + print('Added secret version: {}'.format(response.name)) +# [END secretmanager_add_secret_version] + + return response + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='id of the GCP project') + parser.add_argument('secret_id', help='id of the secret in which to add') + parser.add_argument('payload', help='secret material payload') + args = parser.parse_args() + + add_secret_version(args.project_id, args.secret_id, args.payload) diff --git a/secretmanager/snippets/create_secret.py b/secretmanager/snippets/create_secret.py new file mode 100644 index 000000000000..23d9347a8c1b --- /dev/null +++ b/secretmanager/snippets/create_secret.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python + +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +""" +command line application and sample code for creating a new secret. +""" + +import argparse + + +# [START secretmanager_create_secret] +def create_secret(project_id, secret_id): + """ + Create a new secret with the given name. A secret is a logical wrapper + around a collection of secret versions. Secret versions hold the actual + secret material. + """ + + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the resource name of the parent project. + parent = client.project_path(project_id) + + # Create the secret. + response = client.create_secret(parent, secret_id, { + 'replication': { + 'automatic': {}, + }, + }) + + # Print the new secret name. + print('Created secret: {}'.format(response.name)) +# [END secretmanager_create_secret] + + return response + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='id of the GCP project') + parser.add_argument('secret_id', help='id of the secret to create') + args = parser.parse_args() + + create_secret(args.project_id, args.secret_id) diff --git a/secretmanager/snippets/delete_secret.py b/secretmanager/snippets/delete_secret.py new file mode 100644 index 000000000000..3ee5a2bb1253 --- /dev/null +++ b/secretmanager/snippets/delete_secret.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python + +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +""" +command line application and sample code for deleting an existing secret. +""" + +import argparse + + +# [START secretmanager_delete_secret] +def delete_secret(project_id, secret_id): + """ + Delete the secret with the given name and all of its versions. + """ + + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the resource name of the secret. + name = client.secret_path(project_id, secret_id) + + # Delete the secret. + client.delete_secret(name) +# [END secretmanager_delete_secret] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='id of the GCP project') + parser.add_argument('secret_id', help='id of the secret to delete') + args = parser.parse_args() + + delete_secret(args.project_id, args.secret_id) diff --git a/secretmanager/snippets/destroy_secret_version.py b/secretmanager/snippets/destroy_secret_version.py new file mode 100644 index 000000000000..1d0331811abb --- /dev/null +++ b/secretmanager/snippets/destroy_secret_version.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python + +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +""" +command line application and sample code for destroying a secret verison. +""" + +import argparse + + +# [START secretmanager_destroy_secret_version] +def destroy_secret_version(project_id, secret_id, version_id): + """ + Destroy the given secret version, making the payload irrecoverable. Other + secrets versions are unaffected. + """ + + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the resource name of the secret version + name = client.secret_version_path(project_id, secret_id, version_id) + + # Destroy the secret version. + response = client.destroy_secret_version(name) + + print('Destroyed secret version: {}'.format(response.name)) +# [END secretmanager_destroy_secret_version] + + return response + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='id of the GCP project') + parser.add_argument('secret_id', help='id of the secret from which to act') + parser.add_argument('version_id', help='id of the version to destroy') + args = parser.parse_args() + + destroy_secret_version(args.project_id, args.secret_id, args.version_id) diff --git a/secretmanager/snippets/disable_secret_version.py b/secretmanager/snippets/disable_secret_version.py new file mode 100644 index 000000000000..a88f1a76215e --- /dev/null +++ b/secretmanager/snippets/disable_secret_version.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python + +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +""" +command line application and sample code for disabling a secret version. +""" + +import argparse + + +# [START secretmanager_disable_secret_version] +def disable_secret_version(project_id, secret_id, version_id): + """ + Disable the given secret version. Future requests will throw an error until + the secret version is enabled. Other secrets versions are unaffected. + """ + + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the resource name of the secret version + name = client.secret_version_path(project_id, secret_id, version_id) + + # Disable the secret version. + response = client.disable_secret_version(name) + + print('Disabled secret version: {}'.format(response.name)) +# [END secretmanager_disable_secret_version] + + return response + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='id of the GCP project') + parser.add_argument('secret_id', help='id of the secret from which to act') + parser.add_argument('version_id', help='id of the version to disable') + args = parser.parse_args() + + disable_secret_version(args.project_id, args.secret_id, args.version_id) diff --git a/secretmanager/snippets/enable_secret_version.py b/secretmanager/snippets/enable_secret_version.py new file mode 100644 index 000000000000..c14e2bb0558c --- /dev/null +++ b/secretmanager/snippets/enable_secret_version.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python + +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +""" +command line application and sample code for enabling a secret version. +""" + +import argparse + + +# [START secretmanager_enable_secret_version] +def enable_secret_version(project_id, secret_id, version_id): + """ + Enable the given secret version, enabling it to be accessed after + previously being disabled. Other secrets versions are unaffected. + """ + + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the resource name of the secret version + name = client.secret_version_path(project_id, secret_id, version_id) + + # Disable the secret version. + response = client.enable_secret_version(name) + + print('Enabled secret version: {}'.format(response.name)) +# [END secretmanager_enable_secret_version] + + return response + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='id of the GCP project') + parser.add_argument('secret_id', help='id of the secret from which to act') + parser.add_argument('version_id', help='id of the version to enable') + args = parser.parse_args() + + enable_secret_version(args.project_id, args.secret_id, args.version_id) diff --git a/secretmanager/snippets/get_secret.py b/secretmanager/snippets/get_secret.py new file mode 100644 index 000000000000..5eea886dd5f0 --- /dev/null +++ b/secretmanager/snippets/get_secret.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python + +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +""" +command line application and sample code for getting metadata about a secret. +""" + +import argparse + + +# [START secretmanager_get_secret] +def get_secret(project_id, secret_id): + """ + Get information about the given secret. This only returns metadata about + the secret container, not any secret material. + """ + + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the resource name of the secret. + name = client.secret_path(project_id, secret_id) + + # Get the secret. + response = client.get_secret(name) + + # Get the replication policy. + if response.replication.automatic: + replication = 'AUTOMATIC' + elif response.replication.user_managed: + replication = 'MANAGED' + else: + raise 'Unknown replication {}'.format(response.replication) + + # Print data about the secret. + print('Got secret {} with replication policy {}'.format( + response.name, replication)) +# [END secretmanager_get_secret] + + return response + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='id of the GCP project') + parser.add_argument('secret_id', help='id of the secret to get') + args = parser.parse_args() + + get_secret(args.project_id, args.secret_id) diff --git a/secretmanager/snippets/get_secret_version.py b/secretmanager/snippets/get_secret_version.py new file mode 100644 index 000000000000..7ddb8a56d472 --- /dev/null +++ b/secretmanager/snippets/get_secret_version.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python + +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +""" +command line application and sample code for getting metdata about a secret +version, but not the secret payload. +""" + +import argparse + + +# [START secretmanager_get_secret_version] +def get_secret_version(project_id, secret_id, version_id): + """ + Get information about the given secret version. It does not include the + payload data. + """ + + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the resource name of the secret version. + name = client.secret_version_path(project_id, secret_id, version_id) + + # Get the secret version. + response = client.get_secret_version(name) + + # Print information about the secret version. + state = response.State.Name(response.state) + print('Got secret version {} with state {}'.format(response.name, state)) +# [END secretmanager_get_secret_version] + + return response + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='id of the GCP project') + parser.add_argument('secret_id', help='id of the secret from which to act') + parser.add_argument('version_id', help='id of the version to get') + args = parser.parse_args() + + get_secret_version(args.project_id, args.secret_id, args.version_id) diff --git a/secretmanager/snippets/iam_grant_access.py b/secretmanager/snippets/iam_grant_access.py new file mode 100644 index 000000000000..3c3a7e780e50 --- /dev/null +++ b/secretmanager/snippets/iam_grant_access.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +""" +command line application and sample code for granting access to a secret. +""" + +import argparse + + +# [START secretmanager_iam_grant_access] +def iam_grant_access(project_id, secret_id, member): + """ + Grant the given member access to a secret. + """ + + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the resource name of the secret. + name = client.secret_path(project_id, secret_id) + + # Get the current IAM policy. + policy = client.get_iam_policy(name) + + # Add the given member with access permissions. + policy.bindings.add( + role='roles/secretmanager.secretAccessor', + members=[member]) + + # Update the IAM Policy. + new_policy = client.set_iam_policy(name, policy) + + # Print data about the secret. + print('Updated IAM policy on {}'.format(secret_id)) +# [END secretmanager_iam_grant_access] + + return new_policy + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='id of the GCP project') + parser.add_argument('secret_id', help='id of the secret to get') + parser.add_argument('member', help='member to grant access') + args = parser.parse_args() + + iam_grant_access(args.project_id, args.secret_id, args.member) diff --git a/secretmanager/snippets/iam_revoke_access.py b/secretmanager/snippets/iam_revoke_access.py new file mode 100644 index 000000000000..385a52a52a90 --- /dev/null +++ b/secretmanager/snippets/iam_revoke_access.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +""" +command line application and sample code for revoking access to a secret. +""" + +import argparse + + +# [START secretmanager_iam_revoke_access] +def iam_revoke_access(project_id, secret_id, member): + """ + Revoke the given member access to a secret. + """ + + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the resource name of the secret. + name = client.secret_path(project_id, secret_id) + + # Get the current IAM policy. + policy = client.get_iam_policy(name) + + # Remove the given member's access permissions. + accessRole = 'roles/secretmanager.secretAccessor' + for b in list(policy.bindings): + if b.role == accessRole and member in b.members: + b.members.remove(member) + + # Update the IAM Policy. + new_policy = client.set_iam_policy(name, policy) + + # Print data about the secret. + print('Updated IAM policy on {}'.format(secret_id)) +# [END secretmanager_iam_revoke_access] + + return new_policy + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='id of the GCP project') + parser.add_argument('secret_id', help='id of the secret to get') + parser.add_argument('member', help='member to revoke access') + args = parser.parse_args() + + iam_revoke_access(args.project_id, args.secret_id, args.member) diff --git a/secretmanager/snippets/list_secret_versions.py b/secretmanager/snippets/list_secret_versions.py new file mode 100644 index 000000000000..2ff4434520f8 --- /dev/null +++ b/secretmanager/snippets/list_secret_versions.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python + +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +""" +command line application and sample code for listing secret versions of a +secret. +""" + +import argparse + + +# [START secretmanager_list_secret_versions] +def list_secret_versions(project_id, secret_id): + """ + List all secret versions in the given secret and their metadata. + """ + + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the resource name of the parent secret. + parent = client.secret_path(project_id, secret_id) + + # List all secret versions. + for version in client.list_secret_versions(parent): + print('Found secret version: {}'.format(version.name)) +# [END secretmanager_list_secret_versions] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='id of the GCP project') + parser.add_argument('secret_id', help='id of the secret in which to list') + args = parser.parse_args() + + list_secret_versions(args.project_id, args.secret_id) diff --git a/secretmanager/snippets/list_secrets.py b/secretmanager/snippets/list_secrets.py new file mode 100644 index 000000000000..0d0e798355ec --- /dev/null +++ b/secretmanager/snippets/list_secrets.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python + +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +""" +command line application and sample code for listing secrets in a project. +""" + +import argparse + + +# [START secretmanager_list_secrets] +def list_secrets(project_id): + """ + List all secrets in the given project. + """ + + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the resource name of the parent project. + parent = client.project_path(project_id) + + # List all secrets. + for secret in client.list_secrets(parent): + print('Found secret: {}'.format(secret.name)) +# [END secretmanager_list_secrets] + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='id of the GCP project') + args = parser.parse_args() + + list_secrets(args.project_id) diff --git a/secretmanager/snippets/noxfile.py b/secretmanager/snippets/noxfile.py new file mode 100644 index 000000000000..ba55d7ce53ca --- /dev/null +++ b/secretmanager/snippets/noxfile.py @@ -0,0 +1,224 @@ +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import print_function + +import os +from pathlib import Path +import sys + +import nox + + +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING +# DO NOT EDIT THIS FILE EVER! +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING + +# Copy `noxfile_config.py` to your directory and modify it instead. + + +# `TEST_CONFIG` dict is a configuration hook that allows users to +# modify the test configurations. The values here should be in sync +# with `noxfile_config.py`. Users will copy `noxfile_config.py` into +# their directory and modify it. + +TEST_CONFIG = { + # You can opt out from the test for specific Python versions. + 'ignored_versions': ["2.7"], + + # An envvar key for determining the project id to use. Change it + # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a + # build specific Cloud project. You can also use your own string + # to use your own Cloud project. + 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', + # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + + # A dictionary you want to inject into your test. Don't put any + # secrets here. These values will override predefined values. + 'envs': {}, +} + + +try: + # Ensure we can import noxfile_config in the project's directory. + sys.path.append('.') + from noxfile_config import TEST_CONFIG_OVERRIDE +except ImportError as e: + print("No user noxfile_config found: detail: {}".format(e)) + TEST_CONFIG_OVERRIDE = {} + +# Update the TEST_CONFIG with the user supplied values. +TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) + + +def get_pytest_env_vars(): + """Returns a dict for pytest invocation.""" + ret = {} + + # Override the GCLOUD_PROJECT and the alias. + env_key = TEST_CONFIG['gcloud_project_env'] + # This should error out if not set. + ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key] + + # Apply user supplied envs. + ret.update(TEST_CONFIG['envs']) + return ret + + +# DO NOT EDIT - automatically generated. +# All versions used to tested samples. +ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"] + +# Any default versions that should be ignored. +IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] + +TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) + +INSTALL_LIBRARY_FROM_SOURCE = bool(os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False)) +# +# Style Checks +# + + +def _determine_local_import_names(start_dir): + """Determines all import names that should be considered "local". + + This is used when running the linter to insure that import order is + properly checked. + """ + file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] + return [ + basename + for basename, extension in file_ext_pairs + if extension == ".py" + or os.path.isdir(os.path.join(start_dir, basename)) + and basename not in ("__pycache__") + ] + + +# Linting with flake8. +# +# We ignore the following rules: +# E203: whitespace before ‘:’ +# E266: too many leading ‘#’ for block comment +# E501: line too long +# I202: Additional newline in a section of imports +# +# We also need to specify the rules which are ignored by default: +# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] +FLAKE8_COMMON_ARGS = [ + "--show-source", + "--builtin=gettext", + "--max-complexity=20", + "--import-order-style=google", + "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", + "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", + "--max-line-length=88", +] + + +@nox.session +def lint(session): + session.install("flake8", "flake8-import-order") + + local_names = _determine_local_import_names(".") + args = FLAKE8_COMMON_ARGS + [ + "--application-import-names", + ",".join(local_names), + "." + ] + session.run("flake8", *args) + + +# +# Sample Tests +# + + +PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] + + +def _session_tests(session, post_install=None): + """Runs py.test for a particular project.""" + if os.path.exists("requirements.txt"): + session.install("-r", "requirements.txt") + + if os.path.exists("requirements-test.txt"): + session.install("-r", "requirements-test.txt") + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars() + ) + + +@nox.session(python=ALL_VERSIONS) +def py(session): + """Runs py.test for a sample using the specified version of Python.""" + if session.python in TESTED_VERSIONS: + _session_tests(session) + else: + session.skip("SKIPPED: {} tests are disabled for this sample.".format( + session.python + )) + + +# +# Readmegen +# + + +def _get_repo_root(): + """ Returns the root folder of the project. """ + # Get root of this repository. Assume we don't have directories nested deeper than 10 items. + p = Path(os.getcwd()) + for i in range(10): + if p is None: + break + if Path(p / ".git").exists(): + return str(p) + p = p.parent + raise Exception("Unable to detect repository root.") + + +GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) + + +@nox.session +@nox.parametrize("path", GENERATED_READMES) +def readmegen(session, path): + """(Re-)generates the readme for a sample.""" + session.install("jinja2", "pyyaml") + dir_ = os.path.dirname(path) + + if os.path.exists(os.path.join(dir_, "requirements.txt")): + session.install("-r", os.path.join(dir_, "requirements.txt")) + + in_file = os.path.join(dir_, "README.rst.in") + session.run( + "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file + ) diff --git a/secretmanager/snippets/quickstart.py b/secretmanager/snippets/quickstart.py new file mode 100644 index 000000000000..68b1b0414e99 --- /dev/null +++ b/secretmanager/snippets/quickstart.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python + +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +""" +command line application and sample code for creating an accessing a secret. +""" + + +def quickstart(_project_id=None, _secret_id=None): + # [START secretmanager_quickstart] + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # GCP project in which to store secrets in Secret Manager. + project_id = 'YOUR_PROJECT_ID' + + # ID of the secret to create. + secret_id = 'YOUR_SECRET_ID' + + # [END secretmanager_quickstart] + project_id = _project_id + secret_id = _secret_id + # [START secretmanager_quickstart] + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the parent name from the project. + parent = client.project_path(project_id) + + # Create the parent secret. + secret = client.create_secret(parent, secret_id, { + 'replication': { + 'automatic': {}, + }, + }) + + # Add the secret version. + version = client.add_secret_version(secret.name, {'data': b'hello world!'}) + + # Access the secret version. + response = client.access_secret_version(version.name) + + # Print the secret payload. + # + # WARNING: Do not print the secret in a production environment - this + # snippet is showing how to access the secret material. + payload = response.payload.data.decode('UTF-8') + print('Plaintext: {}'.format(payload)) + # [END secretmanager_quickstart] + + +if __name__ == '__main__': + quickstart() diff --git a/secretmanager/snippets/requirements-test.txt b/secretmanager/snippets/requirements-test.txt new file mode 100644 index 000000000000..7e460c8c866e --- /dev/null +++ b/secretmanager/snippets/requirements-test.txt @@ -0,0 +1 @@ +pytest==6.0.1 diff --git a/secretmanager/snippets/requirements.txt b/secretmanager/snippets/requirements.txt new file mode 100644 index 000000000000..da667b1c4b33 --- /dev/null +++ b/secretmanager/snippets/requirements.txt @@ -0,0 +1 @@ +google-cloud-secret-manager==1.0.0 diff --git a/secretmanager/snippets/snippets_test.py b/secretmanager/snippets/snippets_test.py new file mode 100644 index 000000000000..65f93be6b0f6 --- /dev/null +++ b/secretmanager/snippets/snippets_test.py @@ -0,0 +1,191 @@ +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and + +import os +import uuid + +from google.api_core import exceptions +from google.cloud import secretmanager +import pytest + +from access_secret_version import access_secret_version +from add_secret_version import add_secret_version +from create_secret import create_secret +from delete_secret import delete_secret +from destroy_secret_version import destroy_secret_version +from disable_secret_version import disable_secret_version +from enable_secret_version import enable_secret_version +from get_secret import get_secret +from get_secret_version import get_secret_version +from iam_grant_access import iam_grant_access +from iam_revoke_access import iam_revoke_access +from list_secret_versions import list_secret_versions +from list_secrets import list_secrets +from quickstart import quickstart +from update_secret import update_secret + + +@pytest.fixture() +def client(): + return secretmanager.SecretManagerServiceClient() + + +@pytest.fixture() +def project_id(): + return os.environ['GOOGLE_CLOUD_PROJECT'] + + +@pytest.fixture() +def iam_user(): + return 'serviceAccount:' + os.environ['GCLOUD_SECRETS_SERVICE_ACCOUNT'] + + +@pytest.fixture() +def secret(client, project_id): + parent = client.project_path(project_id) + secret_id = 'python-secret-{}'.format(uuid.uuid4()) + + print('creating secret {}'.format(secret_id)) + secret = client.create_secret(parent, secret_id, { + 'replication': { + 'automatic': {}, + }, + }) + + yield project_id, secret_id + + print('deleting secret {}'.format(secret_id)) + try: + client.delete_secret(secret.name) + except exceptions.NotFound: + # Secret was already deleted, probably in the test + pass + + +another_secret = secret + + +@pytest.fixture() +def secret_version(client, secret): + project_id, secret_id = secret + + print('adding secret version to {}'.format(secret_id)) + parent = client.secret_path(project_id, secret_id) + payload = 'hello world!'.encode('UTF-8') + version = client.add_secret_version(parent, {'data': payload}) + + yield project_id, secret_id, version.name.rsplit('/', 1)[-1] + + +another_secret_version = secret_version + + +def test_quickstart(project_id): + secret_id = 'python-secret-{}'.format(uuid.uuid4()) + quickstart(project_id, secret_id) + + +def test_access_secret_version(secret_version): + project_id, secret_id, version_id = secret_version + version = access_secret_version(project_id, secret_id, version_id) + assert version.payload.data == b'hello world!' + + +def test_add_secret_version(secret): + project_id, secret_id = secret + payload = 'test123' + version = add_secret_version(project_id, secret_id, payload) + assert secret_id in version.name + + +def test_create_secret(client, project_id): + secret_id = 'python-secret-{}'.format(uuid.uuid4()) + secret = create_secret(project_id, secret_id) + assert secret_id in secret.name + client.delete_secret(secret.name) + + +def test_delete_secret(client, secret): + project_id, secret_id = secret + delete_secret(project_id, secret_id) + with pytest.raises(exceptions.NotFound): + print('{}'.format(client)) + name = client.secret_version_path(project_id, secret_id, 'latest') + client.access_secret_version(name) + + +def test_destroy_secret_version(client, secret_version): + project_id, secret_id, version_id = secret_version + version = destroy_secret_version(project_id, secret_id, version_id) + assert version.destroy_time + + +def test_enable_disable_secret_version(client, secret_version): + project_id, secret_id, version_id = secret_version + version = disable_secret_version(project_id, secret_id, version_id) + assert version.state == secretmanager.enums.SecretVersion.State.DISABLED + + version = enable_secret_version(project_id, secret_id, version_id) + assert version.state == secretmanager.enums.SecretVersion.State.ENABLED + + +def test_get_secret_version(client, secret_version): + project_id, secret_id, version_id = secret_version + version = get_secret_version(project_id, secret_id, version_id) + assert secret_id in version.name + assert version_id in version.name + + +def test_get_secret(client, secret): + project_id, secret_id = secret + snippet_secret = get_secret(project_id, secret_id) + assert secret_id in snippet_secret.name + + +def test_iam_grant_access(client, secret, iam_user): + project_id, secret_id = secret + policy = iam_grant_access(project_id, secret_id, iam_user) + assert any(iam_user in b.members for b in policy.bindings) + + +def test_iam_revoke_access(client, secret, iam_user): + project_id, secret_id = secret + policy = iam_revoke_access(project_id, secret_id, iam_user) + assert not any(iam_user in b.members for b in policy.bindings) + + +def test_list_secret_versions(capsys, secret_version, another_secret_version): + project_id, secret_id, version_id = secret_version + _, _, another_version_id = another_secret_version + list_secret_versions(project_id, secret_id) + + out, _ = capsys.readouterr() + assert secret_id in out + assert version_id in out + assert another_version_id in out + + +def test_list_secrets(capsys, secret, another_secret): + project_id, secret_id = secret + _, another_secret_id = another_secret + list_secrets(project_id) + + out, _ = capsys.readouterr() + assert secret_id in out + assert another_secret_id in out + + +def test_update_secret(secret): + project_id, secret_id = secret + secret = update_secret(project_id, secret_id) + assert secret.labels['secretmanager'] == 'rocks' diff --git a/secretmanager/snippets/update_secret.py b/secretmanager/snippets/update_secret.py new file mode 100644 index 000000000000..8c97d919c291 --- /dev/null +++ b/secretmanager/snippets/update_secret.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python + +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and + +import argparse + + +# [START secretmanager_update_secret] +def update_secret(project_id, secret_id): + """ + Update the metadata about an existing secret. + """ + + # Import the Secret Manager client library. + from google.cloud import secretmanager + + # Create the Secret Manager client. + client = secretmanager.SecretManagerServiceClient() + + # Build the resource name of the secret. + name = client.secret_path(project_id, secret_id) + + # Update the secret. + secret = {'name': name, 'labels': {'secretmanager': 'rocks'}} + update_mask = {'paths': ['labels']} + response = client.update_secret(secret, update_mask) + + # Print the new secret name. + print('Updated secret: {}'.format(response.name)) + # [END secretmanager_update_secret] + + return response + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('project_id', help='id of the GCP project') + parser.add_argument('--secret-id', required=True) + args = parser.parse_args() + + update_secret(args.project_id, args.secret_id)