|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2019 Google, Inc. |
| 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 | +# limitations under the License. |
| 16 | + |
| 17 | +import argparse |
| 18 | +# [START storage_s3_sdk_list_objects] |
| 19 | +import boto3 |
| 20 | + |
| 21 | + |
| 22 | +def list_gcs_objects(google_access_key_id, google_access_key_secret, |
| 23 | + bucket_name): |
| 24 | + """Lists GCS objects using boto3 SDK""" |
| 25 | + # Create a new client and do the following: |
| 26 | + # 1. Change the endpoint URL to use the |
| 27 | + # Google Cloud Storage XML API endpoint. |
| 28 | + # 2. Use Cloud Storage HMAC Credentials. |
| 29 | + |
| 30 | + client = boto3.client("s3", region_name="auto", |
| 31 | + endpoint_url="https://storage.googleapis.com", |
| 32 | + aws_access_key_id=google_access_key_id, |
| 33 | + aws_secret_access_key=google_access_key_secret) |
| 34 | + |
| 35 | + # Call GCS to list objects in bucket_name |
| 36 | + response = client.list_objects(Bucket=bucket_name) |
| 37 | + |
| 38 | + # Print object names |
| 39 | + print("Objects:") |
| 40 | + for blob in response["Contents"]: |
| 41 | + print(blob["Key"]) |
| 42 | +# [END storage_s3_sdk_list_objects] |
| 43 | + |
| 44 | + |
| 45 | +if __name__ == "__main__": |
| 46 | + parser = argparse.ArgumentParser( |
| 47 | + description=__doc__, |
| 48 | + formatter_class=argparse.RawDescriptionHelpFormatter) |
| 49 | + parser.add_argument("google_access_key_id", |
| 50 | + help="Your Cloud Storage HMAC Access Key ID.") |
| 51 | + parser.add_argument("google_access_key_secret", |
| 52 | + help="Your Cloud Storage HMAC Access Key Secret.") |
| 53 | + parser.add_argument('bucket_name', |
| 54 | + help="Your Cloud Storage bucket name") |
| 55 | + |
| 56 | + args = parser.parse_args() |
| 57 | + |
| 58 | + list_gcs_objects(google_access_key_id=args.google_access_key_id, |
| 59 | + google_access_key_secret=args.google_access_key_secret, |
| 60 | + bucket_name=args.bucket_name) |
0 commit comments