|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2020 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 revoking access to a secret. |
| 17 | +""" |
| 18 | + |
| 19 | +import argparse |
| 20 | + |
| 21 | + |
| 22 | +# [START secretmanager_iam_revoke_access] |
| 23 | +def iam_revoke_access(project_id, secret_id, member): |
| 24 | + """ |
| 25 | + Revoke the given member access to a secret. |
| 26 | + """ |
| 27 | + |
| 28 | + # Import the Secret Manager client library. |
| 29 | + from google.cloud import secretmanager_v1beta1 as secretmanager |
| 30 | + |
| 31 | + # Create the Secret Manager client. |
| 32 | + client = secretmanager.SecretManagerServiceClient() |
| 33 | + |
| 34 | + # Build the resource name of the secret. |
| 35 | + name = client.secret_path(project_id, secret_id) |
| 36 | + |
| 37 | + # Get the current IAM policy. |
| 38 | + policy = client.get_iam_policy(name) |
| 39 | + |
| 40 | + # Remove the given member's access permissions. |
| 41 | + accessRole = 'roles/secretmanager.secretAccessor' |
| 42 | + for b in list(policy.bindings): |
| 43 | + if b.role == accessRole and member in b.members: |
| 44 | + b.members.remove(member) |
| 45 | + |
| 46 | + # Update the IAM Policy. |
| 47 | + new_policy = client.set_iam_policy(name, policy) |
| 48 | + |
| 49 | + # Print data about the secret. |
| 50 | + print('Updated IAM policy on {}'.format(secret_id)) |
| 51 | +# [END secretmanager_iam_revoke_access] |
| 52 | + |
| 53 | + return new_policy |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == '__main__': |
| 57 | + parser = argparse.ArgumentParser( |
| 58 | + description=__doc__, |
| 59 | + formatter_class=argparse.RawDescriptionHelpFormatter) |
| 60 | + parser.add_argument('project_id', help='id of the GCP project') |
| 61 | + parser.add_argument('secret_id', help='id of the secret to get') |
| 62 | + parser.add_argument('member', help='member to revoke access') |
| 63 | + args = parser.parse_args() |
| 64 | + |
| 65 | + iam_revoke_access(args.project_id, args.secret_id, args.member) |
0 commit comments