8000 feat(iam): use Application Default Credentials (ADC) in IAM quickstar… · mortn/python-docs-samples@aba210a · GitHub
[go: up one dir, main page]

Skip to content

Commit aba210a

Browse files
hegemonicengelke
andauthored
feat(iam): use Application Default Credentials (ADC) in IAM quickstart (GoogleCloudPlatform#7447)
* feat(iam): use Application Default Credentials (ADC) in IAM quickstart ADC allows users to authenticate with methods other than a service account key—for example, with credentials for a Google Account created via `gcloud auth application-default login`. Co-authored-by: Charles Engelke <engelke@google.com>
1 parent 432664b commit aba210a

File tree

2 files changed

+39
-38
lines changed

2 files changed

+39
-38
lines changed

iam/api-client/quickstart.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,7 @@
1515
# limitations under the License.
1616

1717
# [START iam_quickstart]
18-
import os
19-
20-
from google.oauth2 import service_account
18+
import google.auth
2119
import googleapiclient.discovery
2220

2321

@@ -39,7 +37,7 @@ def quickstart(project_id, member):
3937
print(f'Role: {(binding["role"])}')
4038
print("Members: ")
4139
for m in binding["members"]:
42-
print(f'[{m}]')
40+
print(f"[{m}]")
4341

4442
# Removes the member from the 'Log Writer' role.
4543
modify_policy_remove_member(crm_service, project_id, role, member)
@@ -48,9 +46,8 @@ def quickstart(project_id, member):
4846
def initialize_service():
4947
"""Initializes a Cloud Resource Manager service."""
5048

51-
credentials = service_account.Credentials.from_service_account_file(
52-
filename=os.environ["GOOGLE_APPLICATION_CREDENTIALS"],
53-
scopes=["https://www.googleapis.com/auth/cloud-platform"],
49+
credentials, _ = google.auth.default(
50+
scopes=["https://www.googleapis.com/auth/cloud-platform"]
5451
)
5552
crm_service = googleapiclient.discovery.build(
5653
"cloudresourcemanager", "v1", credentials=credentials
@@ -114,7 +111,7 @@ def set_policy(crm_service, project_id, policy):
114111
return policy
115112

116113

117-
if __name__ == '__main__':
114+
if __name__ == "__main__":
118115

119116
# TODO: replace with your project ID
120117
project_id = "your-project-id"

iam/api-client/quickstart_test.py

Lines changed: 34 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import os
1818
import uuid
1919

20-
from google.oauth2 import service_account
20+
import google.auth
2121
from googleapiclient import errors
2222
import googleapiclient.discovery
2323
import pytest
@@ -30,20 +30,19 @@
3030

3131

3232
def retry_if_conflict(exception):
33-
return (isinstance(exception, errors.HttpError)
34-
and 'There were concurrent policy changes' in str(exception))
33+
return isinstance(
34+
exception, errors.HttpError
35+
) and "There were concurrent policy changes" in str(exception)
3536

3637

3738
@pytest.fixture(scope="module")
3839
def test_member():
3940
# section to create service account to test policy updates.
4041
# we use the first portion of uuid4 because full version is too long.
41-
name = f'test-{uuid.uuid4().hex[:25]}'
42+
name = f"test-{uuid.uuid4().hex[:25]}"
4243
email = name + "@" + GCLOUD_PROJECT + ".iam.gserviceaccount.com"
4344
member = "serviceAccount:" + email
44-
create_service_account(
45-
GCLOUD_PROJECT, name, "Py Test Account"
46-
)
45+
create_service_account(GCLOUD_PROJECT, name, "Py Test Account")
4746

4847
yield member
4948

@@ -54,47 +53,52 @@ def test_member():
5453
def create_service_account(project_id, name, display_name):
5554
"""Creates a service account."""
5655

57-
credentials = service_account.Credentials.from_service_account_file(
58-
filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
59-
scopes=['https://www.googleapis.com/auth/cloud-platform'])
56+
credentials, _ = google.auth.default(
57+
scopes=["https://www.googleapis.com/auth/cloud-platform"]
58+
)
6059

61-
service = googleapiclient.discovery.build(
62-
'iam', 'v1', credentials=credentials)
60+
service = googleapiclient.discovery.build("iam", "v1", credentials=credentials)
6361

64-
my_service_account = service.projects().serviceAccounts().create(
65-
name='projects/' + project_id,
66-
body={
67-
'accountId': name,
68-
'serviceAccount': {
69-
'displayName': display_name
70-
}
71-
}).execute()
62+
my_service_account = (
63+
service.projects()
64+
.serviceAccounts()
65+
.create(
66+
name="projects/" + project_id,
67+
body={"accountId": name, "serviceAccount": {"displayName": display_name}},
68+
)
69+
.execute()
70+
)
7271

73-
print('Created service account: ' + my_service_account['email'])
72+
print("Created service account: " + my_service_account["email"])
7473
return my_service_account
7574

7675

7776
def delete_service_account(email):
7877
"""Deletes a service account."""
7978

80-
credentials = service_account.Credentials.from_service_account_file(
81-
filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
82-
scopes=['https://www.googleapis.com/auth/cloud-platform'])
79+
credentials, _ = google.auth.default(
80+
scopes=["https://www.googleapis.com/auth/cloud-platform"]
81+
)
8382

84-
service = googleapiclient.discovery.build(
85-
'iam', 'v1', credentials=credentials)
83+
service = googleapiclient.discovery.build("iam", "v1", credentials=credentials)
8684

8785
service.projects().serviceAccounts().delete(
88-
name='projects/-/serviceAccounts/' + email).execute()
86+
name="projects/-/serviceAccounts/" + email
87+
).execute()
8988

90-
print('Deleted service account: ' + email)
89+
print("Deleted service account: " + email)
9190

9291

9392
def test_quickstart(test_member, capsys):
94-
@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000,
95-
stop_max_attempt_number=5, retry_on_exception=retry_if_conflict)
93+
@retry(
94+
wait_exponential_multiplier=1000,
95+
wait_exponential_max=10000,
96+
stop_max_attempt_number=5,
97+
retry_on_exception=retry_if_conflict,
98+
)
9699
def test_call():
97100
quickstart.quickstart(GCLOUD_PROJECT, test_member)
98101
out, _ = capsys.readouterr()
99102
assert test_member in out
103+
100104
test_call()

0 commit comments

Comments
 (0)
0