$ cat /etc/redhat-release
CentOS Linux release 7.1.1503 (Core)
$ python -V
Python 2.7.5
$ pip -V
pip 7.1.0 from /usr/lib/python2.7/site-packages (python 2.7)
$ sudo pip install --upgrade google-api-python-client
$ sudo curl https://sdk.cloud.google.com | bash
→ All questions in the middle can be left with Y or the default value.
$ exec -l $SHELL
I will explain two methods.
How to create an application account instead of your google account. Of course, it is a mechanism for the application that you (they) use, so be careful not to distribute it to people.
In your project's Google Developer Console, select "Add Credentials-Service Account" from "APIs and Authentication-Credentials".
Specify "JSON" as the key type and select "Create".
The credential file will be downloaded with the name "project name-xxx.json", so save it in any path of the host that uses the API Client Library (* Handling precautions *).
Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of the credential file. If necessary, it is good to describe it in .bash_profile and others.
$ export GOOGLE_APPLICATION_CREDENTIALS='/xxx/xxx/Project name-xxx.json'
How to authenticate with your google account and save your credentials on the host.
$ gcloud auth login
Go to the following link in your browser:
https://accounts.google.com/o/oauth2/auth?redirect_uri=xxx...
→ Connect to the displayed URL with a web browser logged in with a google account that has access rights to your project.
Enter verification code:* Enter the authentication code displayed at the above URL
Saved Application Default Credentials.
sample.py
1 #!/usr/bin/python
2
3 from oauth2client.client import GoogleCredentials
4 from googleapiclient.discovery import build
5
6 credentials = GoogleCredentials.get_application_default()
7
8 compute = build('compute', 'v1', credentials=credentials)
9 project = 'Project ID'
10 zone = 'Zone name'
11
12 print compute.instances().list(project=project, zone=zone).execute()
Execute and check the operation when the GCE instance information is displayed in a staggered manner.
I'm not afraid of anything when I get here. Just write a nice code while referring to the Reference as appropriate.
The gcloud command is sufficient for small operations, but sometimes you may want to do something nifty.
However, the OAuth authentication procedure required for that was troublesome to the extent that there were a certain number of people who gave up, but this story (http://googlecloudplatform-japan.blogspot.jp) /2015/07/application-default-credentials-google.html) I'm grateful that it has become much easier since then.
This content is as of September 2015. Since google related changes quickly, please do not rush to get the latest primary information even if something changes.
Recommended Posts