Creating and Managing IAM Users in Google Cloud


Google Cloud Identity and Access Management (IAM) allows you to create and manage users who have access to Google Cloud resources. In this guide, we'll explore the process of creating and managing IAM users in Google Cloud, and provide a sample Python code snippet for creating a new user using the Google Cloud IAM Python client library.


Key Concepts

Before we dive into the code, let's understand some key concepts related to creating and managing IAM users:

  • IAM User: An IAM user represents an individual who can interact with Google Cloud resources. Users can be members of one or more Google Groups.
  • Google Group: A Google Group is a collection of users. You can manage access by adding and removing users from groups.
  • Roles and Permissions: IAM users are granted permissions through roles, which define what actions they can perform on resources.

Sample Code: Creating an IAM User

Here's a sample Python code snippet for creating a new IAM user in Google Cloud using the Google Cloud IAM Python client library. To use this code, you need to set up a Google Cloud project and have the necessary permissions to manage IAM users:


from google.oauth2 import service_account
from googleapiclient.discovery import build
# Define the IAM service account key and project ID
service_account_key = 'your-service-account-key.json'
project_id = 'your-project-id'
# Load the service account credentials
credentials = service_account.Credentials.from_service_account_file(
service_account_key,
scopes=['https://www.googleapis.com/auth/cloud-platform']
)
# Create the IAM service client
iam_service = build('iam', 'v1', credentials=credentials)
# Define the email and role for the new user
new_user_email = 'new.user@example.com'
new_user_role = 'roles/viewer'
# Create the new IAM user
request_body = {
'email': new_user_email,
'role': new_user_role
}
response = iam_service.projects().serviceAccounts().create(
name=f'projects/{project_id}',
body=request_body
).execute()
print('New IAM user created:')
print(response)

Replace `'your-service-account-key.json'`, `'your-project-id'`, `'new.user@example.com'`, and `'roles/viewer'` with your service account key file, project ID, new user's email, and desired role. This code creates a new IAM user in Google Cloud with the specified role.


Conclusion

Creating and managing IAM users in Google Cloud is essential for controlling access to resources and maintaining a secure environment. By using the provided code snippet and understanding the key concepts, you can efficiently manage IAM users and their roles.