|
| 1 | +# Copyright 2022 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http:#www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# [START iam_rename_service_account] |
| 16 | +from google.cloud import iam_admin_v1 |
| 17 | +from google.cloud.iam_admin_v1 import types |
| 18 | + |
| 19 | + |
| 20 | +def rename_service_account(project_id: str, account: str, new_name: str) -> types.ServiceAccount: |
| 21 | + """ |
| 22 | + Renames service account display name. |
| 23 | +
|
| 24 | + project_id: ID or number of the Google Cloud project you want to use. |
| 25 | + account: ID or email which is unique identifier of the service account. |
| 26 | + new_name: New display name of the service account. |
| 27 | + """ |
| 28 | + |
| 29 | + iam_admin_client = iam_admin_v1.IAMClient() |
| 30 | + |
| 31 | + get_request = types.GetServiceAccountRequest() |
| 32 | + get_request.name = f"projects/{project_id}/serviceAccounts/{account}" |
| 33 | + service_account = iam_admin_client.get_service_account(request=get_request) |
| 34 | + |
| 35 | + service_account.display_name = new_name |
| 36 | + |
| 37 | + request = types.PatchServiceAccountRequest() |
| 38 | + request.service_account = service_account |
| 39 | + # You can patch only the `display_name` and `description` fields. You must use |
| 40 | + # the `update_mask` field to specify which of these fields you want to patch. |
| 41 | + # To successfully set update mask you need to transform snake_case field to camelCase. |
| 42 | + # e.g. `display_name` will become `displayName` |
| 43 | + request.update_mask = "displayName" |
| 44 | + |
| 45 | + updated_account = iam_admin_client.patch_service_account(request=request) |
| 46 | + return updated_account |
| 47 | + |
| 48 | +# [END iam_rename_service_account] |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == "__main__": |
| 52 | + # To run the sample you would need |
| 53 | + # iam.serviceAccounts.update permission (roles/iam.serviceAccountAdmin) |
| 54 | + |
| 55 | + # Your Google Cloud project ID. |
| 56 | + project_id = "your-google-cloud-project-id" |
| 57 | + # Existing service account name within the project specified above. |
| 58 | + account_name = "test-service-account" |
| 59 | + account_id = f"{account_name}@{project_id}.iam.gserviceaccount.com" |
| 60 | + new_name = "New Name" |
| 61 | + |
| 62 | + rename_service_account(project_id, account_id, new_name) |
0 commit comments