|
| 1 | +#!/usr/bin/env ruby |
| 2 | + |
| 3 | +# Copyright 2015 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 | +module Samples |
| 18 | + # Cloud Storage Samples module |
| 19 | + module Storage |
| 20 | + # A short sample demonstrating making an authenticated api request. |
| 21 | + # |
| 22 | + # Specifically, it creates a Service object to the Google Cloud Storage api, |
| 23 | + # and uses Application Default Credentials to authenticate. |
| 24 | + # [START all] |
| 25 | + class ListBuckets |
| 26 | + # [START list_buckets] |
| 27 | + require "google/apis/storage_v1" |
| 28 | + |
| 29 | + # Alias the Google Cloud Storage module |
| 30 | + Storage = Google::Apis::StorageV1 |
| 31 | + |
| 32 | + def list_buckets project_id |
| 33 | + # Create the storage service object, used to access the storage api. |
| 34 | + storage = Storage::StorageService.new |
| 35 | + # Have the service object use the application default credentials to |
| 36 | + # auth, which infers credentials from the environment. |
| 37 | + storage.authorization = Google::Auth.get_application_default( |
| 38 | + # Set the credentials to have a readonly scope to the storage service. |
| 39 | + Storage::AUTH_DEVSTORAGE_READ_ONLY |
| 40 | + ) |
| 41 | + |
| 42 | + # Make the api call to list buckets owned by the default credentials. |
| 43 | + storage.list_buckets(project_id).items.each do |bucket| |
| 44 | + # Print out each bucket name. |
| 45 | + puts bucket.name |
| 46 | + end |
| 47 | + end |
| 48 | + # [END list_buckets] |
| 49 | + end |
| 50 | + |
| 51 | + if __FILE__ == $PROGRAM_NAME |
| 52 | + project_id = ARGV.shift |
| 53 | + |
| 54 | + ListBuckets.new.list_buckets project_id |
| 55 | + end |
| 56 | + # [END all] |
| 57 | + end |
| 58 | +end |
0 commit comments