Search Tutorials


Top GCP IAM & Identity Interview Questions (2026) | JavaInUse

Top 20 GCP IAM & Identity Interview Questions


  1. What is GCP IAM?
  2. What are IAM roles?
  3. What are service accounts?
  4. What is the principle of least privilege?
  5. What are IAM policies?
  6. What is Identity Platform?
  7. How do you manage service account keys?
  8. What is Workload Identity?
  9. What are IAM conditions?
  10. How do you audit IAM permissions?
  11. What is organization policy?
  12. What are custom roles?
  13. How do you implement cross-project access?
  14. What is Identity-Aware Proxy (IAP)?
  15. How do you manage access at scale?
  16. What are IAM recommender insights?
  17. What is VPC Service Controls?
  18. How do you implement identity federation?
  19. What are domain-wide delegation?
  20. What are IAM best practices?

Google Cloud Interview Questions

1. What is GCP IAM?

Identity and Access Management (IAM) controls who (identity) has what access (role) to which resources.

IAM Concepts:
+-------------------------------------------------------------+
|                      GCP IAM                                 |
+-------------------------------------------------------------+
|                                                              |
|  WHO (Members/Principals)                                    |
|  +-- Google Account (user@gmail.com)                        |
|  +-- Service Account (sa@project.iam.gserviceaccount.com)  |
|  +-- Google Group (group@googlegroups.com)                  |
|  +-- Google Workspace domain (domain.com)                   |
|  +-- Cloud Identity domain                                  |
|  +-- allUsers, allAuthenticatedUsers                        |
|                                                              |
|  WHAT (Roles)                                                |
|  +-- Basic: Owner, Editor, Viewer                           |
|  +-- Predefined: roles/bigquery.dataViewer                  |
|  +-- Custom: projects/my-project/roles/customRole          |
|                                                              |
|  WHICH (Resources)                                           |
|  +-- Organization                                           |
|  +-- Folder                                                 |
|  +-- Project                                                |
|  +-- Individual resources (bucket, dataset, etc.)          |
|                                                              |
|  Policy = Bindings (Member + Role) attached to Resource     |
+-------------------------------------------------------------+

Resource Hierarchy:
+------------------+
|  Organization    |
+--------+---------+
         |
    +----+----+
    |  Folder | (optional)
    +----+----+
         |
    +----+----+
    | Project |
    +----+----+
         |
    +----+----+
    | Resource| (bucket, VM, etc.)
    +---------+

# View IAM policy
gcloud projects get-iam-policy my-project

# Add binding
gcloud projects add-iam-policy-binding my-project \
    --member="user:alice@example.com" \
    --role="roles/viewer"

2. What are IAM roles?

Role Types:

1. Basic Roles (Primitive)
+-- roles/owner - Full access + IAM management
+-- roles/editor - Read/write access
+-- roles/viewer - Read-only access
# Avoid basic roles in production - too broad

2. Predefined Roles (Fine-grained)
# BigQuery
+-- roles/bigquery.admin
+-- roles/bigquery.dataEditor
+-- roles/bigquery.dataViewer
+-- roles/bigquery.jobUser
+-- roles/bigquery.user

# Cloud Storage
+-- roles/storage.admin
+-- roles/storage.objectAdmin
+-- roles/storage.objectViewer
+-- roles/storage.objectCreator

# Compute Engine
+-- roles/compute.admin
+-- roles/compute.instanceAdmin
+-- roles/compute.viewer

3. Custom Roles
gcloud iam roles create myCustomRole \
    --project=my-project \
    --title="My Custom Role" \
    --description="Custom role for specific tasks" \
    --permissions=bigquery.datasets.get,bigquery.tables.list,bigquery.jobs.create

# List permissions for a role
gcloud iam roles describe roles/bigquery.dataViewer

# View all predefined roles
gcloud iam roles list --filter="name:roles/bigquery"

Role Binding Example:
{
  "bindings": [
    {
      "role": "roles/bigquery.dataViewer",
      "members": [
        "user:alice@example.com",
        "serviceAccount:sa@project.iam.gserviceaccount.com",
        "group:data-team@example.com"
      ]
    },
    {
      "role": "roles/bigquery.jobUser",
      "members": [
        "user:bob@example.com"
      ]
    }
  ]
}

3. What are service accounts?

Service accounts are special accounts for applications and services to authenticate to GCP APIs.

Service Account Types:
+-- User-managed - Created by users
+-- Default - Created automatically (avoid using)
+-- Google-managed - Used by GCP services

# Create service account
gcloud iam service-accounts create my-service-account \
    --display-name="My Service Account" \
    --description="Used for data processing"

# Grant roles to service account
gcloud projects add-iam-policy-binding my-project \
    --member="serviceAccount:my-service-account@my-project.iam.gserviceaccount.com" \
    --role="roles/bigquery.dataEditor"

# Service account impersonation
gcloud iam service-accounts add-iam-policy-binding \
    my-service-account@my-project.iam.gserviceaccount.com \
    --member="user:developer@example.com" \
    --role="roles/iam.serviceAccountUser"

# Impersonate in gcloud
gcloud config set auth/impersonate_service_account \
    my-service-account@my-project.iam.gserviceaccount.com

# Python with impersonation
from google.auth import impersonated_credentials
from google.auth import default

source_credentials, _ = default()

target_credentials = impersonated_credentials.Credentials(
    source_credentials=source_credentials,
    target_principal='sa@project.iam.gserviceaccount.com',
    target_scopes=['https://www.googleapis.com/auth/cloud-platform']
)

# Use in client
from google.cloud import bigquery
client = bigquery.Client(credentials=target_credentials)

Service Account Best Practices:
+-- One SA per application/service
+-- Grant minimum required permissions
+-- Avoid SA keys (use Workload Identity)
+-- Rotate keys if they must be used
+-- Use short-lived tokens when possible
+-- Audit SA usage regularly

4. What is the principle of least privilege?

Least Privilege Principle:
+-- Grant only permissions needed
+-- For the specific resources needed
+-- For the time needed
+-- Audit and revoke unused permissions

Implementation:

1. Use predefined roles instead of basic
# Bad
gcloud projects add-iam-policy-binding my-project \
    --member="user:analyst@example.com" \
    --role="roles/editor"

# Good
gcloud projects add-iam-policy-binding my-project \
    --member="user:analyst@example.com" \
    --role="roles/bigquery.dataViewer"

2. Grant at resource level, not project
# Instead of project-level
gcloud projects add-iam-policy-binding my-project \
    --member="serviceAccount:etl@project.iam.gserviceaccount.com" \
    --role="roles/bigquery.dataEditor"

# Grant on specific dataset
bq add-iam-policy-binding \
    --member="serviceAccount:etl@project.iam.gserviceaccount.com" \
    --role="roles/bigquery.dataEditor" \
    project:dataset

3. Use IAM conditions for time-bound access
gcloud projects add-iam-policy-binding my-project \
    --member="user:contractor@example.com" \
    --role="roles/viewer" \
    --condition="expression=request.time < timestamp('2024-03-31T23:59:59Z'),title=temporary-access"

4. Regular access reviews
# Use IAM Recommender
gcloud recommender recommendations list \
    --project=my-project \
    --location=global \
    --recommender=google.iam.policy.Recommender

5. Separate environments
+-- Development - More permissive
+-- Staging - Production-like permissions
+-- Production - Strictest controls

5. What are IAM policies?

IAM Policy Structure:

# Get current policy
gcloud projects get-iam-policy my-project --format=json > policy.json

# policy.json
{
  "version": 3,
  "etag": "BwXXXXXXXXX=",
  "bindings": [
    {
      "role": "roles/owner",
      "members": [
        "user:admin@example.com"
      ]
    },
    {
      "role": "roles/bigquery.dataViewer",
      "members": [
        "user:analyst@example.com",
        "group:data-team@example.com"
      ],
      "condition": {
        "title": "Dataset access only",
        "description": "Access to specific datasets",
        "expression": "resource.name.startsWith('projects/my-project/datasets/public_')"
      }
    }
  ],
  "auditConfigs": [
    {
      "service": "bigquery.googleapis.com",
      "auditLogConfigs": [
        {"logType": "ADMIN_READ"},
        {"logType": "DATA_READ"},
        {"logType": "DATA_WRITE"}
      ]
    }
  ]
}

# Set policy
gcloud projects set-iam-policy my-project policy.json

Policy Inheritance:
+------------------+
|  Organization    | --- Policy A
+--------+---------+
         | (inherits)
    +----+----+
    |  Folder | --- Policy B
    +----+----+
         | (inherits)
    +----+----+
    | Project | --- Policy C
    +----+----+
         | (inherits)
    +----+----+
    | Resource| --- Policy D
    +---------+

Effective policy = A + B + C + D (union)
Note: Deny policies override allow

# Python: Get/Set policy
from google.cloud import resourcemanager_v3

client = resourcemanager_v3.ProjectsClient()
policy = client.get_iam_policy(resource=f"projects/my-project")

# Add binding
policy.bindings.add(
    role="roles/viewer",
    members=["user:new@example.com"]
)

client.set_iam_policy(resource=f"projects/my-project", policy=policy)





6. What is Identity Platform?

Identity Platform is a customer identity and access management (CIAM) platform for adding authentication to apps.

Identity Platform Features:
+-- Multi-tenant authentication
+-- Multiple identity providers
+-- Email/password, phone, social
+-- SAML and OIDC federation
+-- Multi-factor authentication
+-- User management APIs
+-- Compatible with Firebase Auth

Authentication Methods:
+-- Email/Password
+-- Phone (SMS)
+-- Google, Facebook, Twitter, etc.
+-- Anonymous
+-- SAML
+-- OIDC

# Enable Identity Platform
gcloud services enable identitytoolkit.googleapis.com

# Web SDK usage
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithEmailAndPassword } from 'firebase/auth';

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

// Sign in
signInWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {
    const user = userCredential.user;
    // Get ID token for backend
    user.getIdToken().then(token => {
      // Send to backend
    });
  });

# Backend token verification (Python)
from google.auth.transport import requests
from google.oauth2 import id_token

def verify_token(token):
    try:
        decoded = id_token.verify_firebase_token(
            token,
            requests.Request(),
            audience='my-project'
        )
        return decoded
    except Exception as e:
        return None

# Admin SDK for user management
from firebase_admin import auth

# Create user
user = auth.create_user(
    email='user@example.com',
    password='secretPassword',
    display_name='John Doe'
)

# Set custom claims
auth.set_custom_user_claims(user.uid, {'admin': True})

# Get user
user = auth.get_user_by_email('user@example.com')

7. How do you manage service account keys?

Key Management Best Practices:

Avoid keys when possible:
+-- Use Workload Identity (GKE)
+-- Use attached service accounts (GCE, Cloud Functions)
+-- Use identity federation
+-- Use short-lived tokens

If keys are necessary:

# Create key
gcloud iam service-accounts keys create key.json \
    --iam-account=my-sa@my-project.iam.gserviceaccount.com

# List keys
gcloud iam service-accounts keys list \
    --iam-account=my-sa@my-project.iam.gserviceaccount.com

# Delete key
gcloud iam service-accounts keys delete KEY_ID \
    --iam-account=my-sa@my-project.iam.gserviceaccount.com

Key Security:
+-- Store in Secret Manager
+-- Rotate regularly (90 days max)
+-- Monitor key usage
+-- Delete unused keys
+-- Never commit to source control

# Store key in Secret Manager
gcloud secrets create sa-key \
    --data-file=key.json

# Access key from Secret Manager
gcloud secrets versions access latest --secret=sa-key > key.json

# Python: Use key from Secret Manager
from google.cloud import secretmanager
from google.oauth2 import service_account
import json

client = secretmanager.SecretManagerServiceClient()
name = f"projects/my-project/secrets/sa-key/versions/latest"
response = client.access_secret_version(name=name)
key_data = json.loads(response.payload.data.decode('UTF-8'))

credentials = service_account.Credentials.from_service_account_info(key_data)

# Key rotation automation
# Cloud Function to rotate keys
def rotate_key(event, context):
    from google.cloud import iam_admin_v1
    
    client = iam_admin_v1.IAMClient()
    sa_name = f"projects/my-project/serviceAccounts/my-sa@my-project.iam.gserviceaccount.com"
    
    # Create new key
    new_key = client.create_service_account_key(name=sa_name)
    
    # Update Secret Manager
    # ...
    
    # Delete old keys
    keys = client.list_service_account_keys(name=sa_name)
    for key in keys.keys:
        if is_old(key):
            client.delete_service_account_key(name=key.name)

8. What is Workload Identity?

Workload Identity allows GKE workloads to access GCP services without service account keys.

Workload Identity Architecture:
+-------------------------------------------------------------+
|                      GKE Cluster                             |
|  +-----------------------------------------------------+   |
|  |                    Pod                               |   |
|  |  +---------------------------------------------+   |   |
|  |  |  Kubernetes Service Account                  |   |   |
|  |  |  (my-namespace/my-ksa)                       |   |   |
|  |  +---------------------------------------------+   |   |
|  +-----------------------------------------------------+   |
+-------------------------------------------------------------+
                          |
                          | Bound via annotation
                          v
+-------------------------------------------------------------+
|              GCP Service Account                             |
|  (my-gsa@my-project.iam.gserviceaccount.com)               |
|                                                              |
|  Roles: roles/bigquery.dataViewer                           |
+-------------------------------------------------------------+

Setup Steps:

# 1. Enable Workload Identity on cluster
gcloud container clusters update my-cluster \
    --location=us-central1 \
    --workload-pool=my-project.svc.id.goog

# 2. Create GCP service account
gcloud iam service-accounts create my-gsa \
    --display-name="My GKE Service Account"

# 3. Grant roles to GCP SA
gcloud projects add-iam-policy-binding my-project \
    --member="serviceAccount:my-gsa@my-project.iam.gserviceaccount.com" \
    --role="roles/bigquery.dataViewer"

# 4. Create Kubernetes service account
kubectl create serviceaccount my-ksa --namespace my-namespace

# 5. Bind KSA to GSA
gcloud iam service-accounts add-iam-policy-binding \
    my-gsa@my-project.iam.gserviceaccount.com \
    --role="roles/iam.workloadIdentityUser" \
    --member="serviceAccount:my-project.svc.id.goog[my-namespace/my-ksa]"

# 6. Annotate KSA
kubectl annotate serviceaccount my-ksa \
    --namespace=my-namespace \
    iam.gke.io/gcp-service-account=my-gsa@my-project.iam.gserviceaccount.com

# 7. Use in Pod
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  namespace: my-namespace
spec:
  serviceAccountName: my-ksa
  containers:
  - name: app
    image: gcr.io/my-project/my-app
    # Application auto-authenticates using Workload Identity

9. What are IAM conditions?

IAM Conditions:
+-- Attribute-based access control
+-- Resource attributes
+-- Request attributes
+-- Time-based conditions
+-- CEL expression language

# Time-based condition
gcloud projects add-iam-policy-binding my-project \
    --member="user:contractor@example.com" \
    --role="roles/editor" \
    --condition='
        expression=request.time < timestamp("2024-06-30T23:59:59Z"),
        title=temporary-access,
        description=Access until end of Q2'

# Resource-based condition
gcloud projects add-iam-policy-binding my-project \
    --member="user:analyst@example.com" \
    --role="roles/bigquery.dataViewer" \
    --condition='
        expression=resource.name.startsWith("projects/my-project/datasets/public_"),
        title=public-datasets-only,
        description=Access only to public datasets'

# Request-based condition (IP)
gcloud projects add-iam-policy-binding my-project \
    --member="user:admin@example.com" \
    --role="roles/owner" \
    --condition='
        expression=request.auth.accessLevels.exists(x, x == "accessPolicies/123456/accessLevels/corpNetwork"),
        title=corp-network-only'

CEL Expression Examples:

# Time window
request.time.getHours("America/Los_Angeles") >= 9 &&
request.time.getHours("America/Los_Angeles") <= 17 &&
request.time.getDayOfWeek("America/Los_Angeles") >= 1 &&
request.time.getDayOfWeek("America/Los_Angeles") <= 5

# Resource name pattern
resource.name.startsWith("projects/my-project/datasets/team_")

# Resource type
resource.type == "storage.googleapis.com/Bucket"

# Combined conditions
(resource.name.startsWith("projects/my-project/datasets/dev_") &&
 request.time < timestamp("2024-12-31T23:59:59Z")) ||
resource.name.startsWith("projects/my-project/datasets/public_")

# Tag-based
resource.matchTag("env", "production")

10. How do you audit IAM permissions?

IAM Auditing Methods:

1. Cloud Audit Logs
# Enable data access logs
gcloud projects get-iam-policy my-project --format=json > policy.json

# Add audit config to policy.json
"auditConfigs": [
  {
    "service": "allServices",
    "auditLogConfigs": [
      {"logType": "ADMIN_READ"},
      {"logType": "DATA_READ"},
      {"logType": "DATA_WRITE"}
    ]
  }
]

gcloud projects set-iam-policy my-project policy.json

# Query audit logs
gcloud logging read '
    protoPayload.serviceName="cloudresourcemanager.googleapis.com" AND
    protoPayload.methodName="SetIamPolicy"
' --limit=50

2. Policy Analyzer
# Who has access to a resource
gcloud asset analyze-iam-policy \
    --organization=123456789 \
    --full-resource-name="//bigquery.googleapis.com/projects/my-project/datasets/my_dataset"

# What can a user access
gcloud asset analyze-iam-policy \
    --organization=123456789 \
    --identity="user:alice@example.com"

3. IAM Recommender
gcloud recommender recommendations list \
    --project=my-project \
    --location=global \
    --recommender=google.iam.policy.Recommender

# Apply recommendation
gcloud recommender recommendations mark-claimed \
    --project=my-project \
    --location=global \
    --recommender=google.iam.policy.Recommender \
    --recommendation=RECOMMENDATION_ID

4. Security Command Center
# View IAM findings
gcloud scc findings list organizations/123456789 \
    --filter='category="IAM_ANOMALOUS_GRANT"'

5. Export and analyze
# Export to BigQuery
gcloud asset export \
    --project=my-project \
    --content-type=iam-policy \
    --output-bigquery-force \
    --output-bigquery-dataset=my_dataset \
    --output-bigquery-table=iam_policies

11. What is organization policy?

Organization Policies:
+-- Constraints on resource configuration
+-- Applied at org/folder/project level
+-- Inherited down the hierarchy
+-- Override allow/deny inheritance

Common Constraints:

# Disable service account key creation
gcloud org-policies set-policy policy.yaml

# policy.yaml
name: projects/my-project/policies/iam.disableServiceAccountKeyCreation
spec:
  rules:
  - enforce: true

# Restrict allowed locations
name: organizations/123456789/policies/gcp.resourceLocations
spec:
  rules:
  - values:
      allowedValues:
      - us-central1
      - us-east1
      - europe-west1

# Disable external IP for VMs
name: projects/my-project/policies/compute.vmExternalIpAccess
spec:
  rules:
  - values:
      deniedValues:
      - all

# Restrict public access
name: organizations/123456789/policies/storage.publicAccessPrevention
spec:
  rules:
  - enforce: true

# Apply policy
gcloud org-policies set-policy policy.yaml

# List constraints
gcloud org-policies list --organization=123456789

# Describe constraint
gcloud org-policies describe iam.disableServiceAccountKeyCreation \
    --organization=123456789

# Get effective policy
gcloud org-policies describe gcp.resourceLocations \
    --project=my-project \
    --effective

Policy Inheritance:
+--------------------+
|    Organization    | -- Deny external IP
+---------+----------+
          |
     +----+----+
     |  Folder | -- Allow us-central1 only
     +----+----+
          |
     +----+----+
     | Project | -- Inherits: no external IP + us-central1 only
     +---------+

12. What are custom roles?

Custom Roles:

# Create custom role
gcloud iam roles create dataAnalyst \
    --project=my-project \
    --title="Data Analyst" \
    --description="Read-only access to BigQuery and GCS" \
    --permissions=bigquery.datasets.get,bigquery.tables.list,bigquery.tables.getData,storage.objects.get,storage.objects.list \
    --stage=GA

# Create from YAML
# role.yaml
title: "Data Analyst"
description: "Read-only access for analysts"
stage: "GA"
includedPermissions:
- bigquery.datasets.get
- bigquery.tables.list
- bigquery.tables.getData
- bigquery.jobs.create
- bigquery.jobs.get
- storage.objects.get
- storage.objects.list

gcloud iam roles create dataAnalyst \
    --project=my-project \
    --file=role.yaml

# Update custom role
gcloud iam roles update dataAnalyst \
    --project=my-project \
    --add-permissions=bigquery.tables.export

# List custom roles
gcloud iam roles list --project=my-project

# Delete custom role
gcloud iam roles delete dataAnalyst --project=my-project

# Use custom role
gcloud projects add-iam-policy-binding my-project \
    --member="user:analyst@example.com" \
    --role="projects/my-project/roles/dataAnalyst"

Best Practices:
+-- Start with predefined roles
+-- Create custom only when needed
+-- Document purpose clearly
+-- Version control role definitions
+-- Review and audit regularly
+-- Use organization-level for reuse

13. How do you implement cross-project access?

Cross-Project Access Patterns:

1. Service Account in Another Project
# Project A service account accessing Project B resources

# In Project B: Grant access to SA from Project A
gcloud projects add-iam-policy-binding project-b \
    --member="serviceAccount:my-sa@project-a.iam.gserviceaccount.com" \
    --role="roles/bigquery.dataViewer"

2. Shared VPC
# Host project shares network with service projects
# IAM for shared VPC resources

gcloud compute shared-vpc enable host-project

gcloud compute shared-vpc associated-projects add service-project \
    --host-project=host-project

3. Cross-Project BigQuery
# Grant access to specific dataset
bq add-iam-policy-binding \
    --member="serviceAccount:etl@project-a.iam.gserviceaccount.com" \
    --role="roles/bigquery.dataViewer" \
    project-b:my_dataset

# Query across projects
SELECT * FROM `project-b.dataset.table`

4. Cross-Project GCS
# Grant access to bucket in another project
gsutil iam ch \
    serviceAccount:my-sa@project-a.iam.gserviceaccount.com:objectViewer \
    gs://bucket-in-project-b

5. Service Account Impersonation
# Allow SA in Project A to impersonate SA in Project B
gcloud iam service-accounts add-iam-policy-binding \
    target-sa@project-b.iam.gserviceaccount.com \
    --member="serviceAccount:source-sa@project-a.iam.gserviceaccount.com" \
    --role="roles/iam.serviceAccountTokenCreator"

# Code to impersonate
from google.auth import impersonated_credentials

target_creds = impersonated_credentials.Credentials(
    source_credentials=source_creds,
    target_principal='target-sa@project-b.iam.gserviceaccount.com',
    target_scopes=['https://www.googleapis.com/auth/cloud-platform']
)

14. What is Identity-Aware Proxy (IAP)?

IAP Features:
+-- Context-aware access control
+-- Protects apps behind load balancer
+-- Integrates with Cloud IAM
+-- Zero trust security model
+-- No VPN required

# Enable IAP on App Engine
gcloud iap web enable \
    --resource-type=app-engine \
    --oauth2-client-id=CLIENT_ID \
    --oauth2-client-secret=CLIENT_SECRET

# Enable IAP on backend service
gcloud compute backend-services update my-backend \
    --iap=enabled,oauth2-client-id=CLIENT_ID,oauth2-client-secret=CLIENT_SECRET \
    --global

# Grant access
gcloud iap web add-iam-policy-binding \
    --member="user:user@example.com" \
    --role="roles/iap.httpsResourceAccessor" \
    --resource-type=app-engine

# Conditional access
gcloud iap web add-iam-policy-binding \
    --member="user:user@example.com" \
    --role="roles/iap.httpsResourceAccessor" \
    --resource-type=app-engine \
    --condition='
        expression=accessPolicies/123/accessLevels/corpNetwork,
        title=corp-access'

# Access context condition
# Create access level
gcloud access-context-manager levels create corpNetwork \
    --policy=123456789 \
    --basic-level-spec=spec.yaml

# spec.yaml
conditions:
  - ipSubnetworks:
      - "10.0.0.0/8"
      - "192.168.0.0/16"
  - devicePolicy:
      requireScreenlock: true
      osConstraints:
        - osType: DESKTOP_CHROME_OS
          minimumVersion: "80"

# Backend code to get user info
def get_user_info(request):
    # IAP injects these headers
    user_email = request.headers.get('X-Goog-Authenticated-User-Email')
    user_id = request.headers.get('X-Goog-Authenticated-User-Id')
    
    # Verify JWT (optional, for additional security)
    jwt_assertion = request.headers.get('X-Goog-IAP-JWT-Assertion')
    ...

15. How do you manage access at scale?

Access Management at Scale:

1. Use Groups
# Create Google Group in Admin Console or Cloud Identity
# Grant roles to groups, not individuals

gcloud projects add-iam-policy-binding my-project \
    --member="group:data-engineers@company.com" \
    --role="roles/bigquery.dataEditor"

# Team-based access
+-- data-engineers@company.com - BigQuery Editor
+-- data-analysts@company.com - BigQuery Viewer
+-- ml-engineers@company.com - Vertex AI User

2. Resource Hierarchy
# Organization
+-- Folders (by department/team/environment)
    +-- Projects (by application/service)
        +-- Resources

# Grant at appropriate level
gcloud resource-manager folders add-iam-policy-binding FOLDER_ID \
    --member="group:team@company.com" \
    --role="roles/viewer"

3. Terraform for IaC
resource "google_project_iam_binding" "data_viewers" {
  project = "my-project"
  role    = "roles/bigquery.dataViewer"
  
  members = [
    "group:analysts@company.com",
    "group:data-scientists@company.com",
  ]
}

# Modules for reusable access patterns
module "project_access" {
  source  = "./modules/project-iam"
  project = "my-project"
  
  bindings = {
    "roles/viewer" = [
      "group:all-staff@company.com"
    ]
    "roles/bigquery.user" = [
      "group:analysts@company.com"
    ]
  }
}

4. Privileged Access Management
# Just-in-time access with Privileged Access Manager
gcloud pam grants create \
    --entitlement=my-entitlement \
    --requested-duration=3600s \
    --justification="Production debugging"

5. Regular Access Reviews
# Automate with Cloud Asset Inventory
gcloud asset search-all-iam-policies \
    --scope=organizations/123456789 \
    --query="policy:user"

16. What are IAM recommender insights?

IAM Recommender:
+-- Identifies excess permissions
+-- Suggests role downgrades
+-- Based on actual usage
+-- Reduces security risk

# List recommendations
gcloud recommender recommendations list \
    --project=my-project \
    --location=global \
    --recommender=google.iam.policy.Recommender

# Describe recommendation
gcloud recommender recommendations describe RECOMMENDATION_ID \
    --project=my-project \
    --location=global \
    --recommender=google.iam.policy.Recommender

# View insights (unused permissions)
gcloud recommender insights list \
    --project=my-project \
    --location=global \
    --insight-type=google.iam.policy.Insight

# Apply recommendation
gcloud recommender recommendations mark-claimed \
    --project=my-project \
    --location=global \
    --recommender=google.iam.policy.Recommender \
    --recommendation=RECOMMENDATION_ID \
    --state-metadata=reason="Applying least privilege"

# Python: Automate recommendations
from google.cloud import recommender_v1

client = recommender_v1.RecommenderClient()

parent = f"projects/my-project/locations/global/recommenders/google.iam.policy.Recommender"

recommendations = client.list_recommendations(parent=parent)

for rec in recommendations:
    print(f"Recommendation: {rec.description}")
    print(f"Impact: {rec.primary_impact}")
    
    for operation in rec.content.operation_groups:
        for op in operation.operations:
            print(f"  Action: {op.action} on {op.resource}")

Recommendation Types:
+-- Remove unused permissions
+-- Replace with more specific role
+-- Remove binding entirely
+-- Replace basic role with predefined
+-- Service account cleanup

17. What is VPC Service Controls?

VPC Service Controls:
+-- Data exfiltration protection
+-- Perimeter around GCP resources
+-- Context-aware access
+-- Works with IAP
+-- Audit logging

# Create access policy
gcloud access-context-manager policies create \
    --organization=123456789 \
    --title="My Access Policy"

# Create access level
gcloud access-context-manager levels create trusted \
    --policy=POLICY_ID \
    --basic-level-spec=level.yaml

# level.yaml
conditions:
  - ipSubnetworks:
      - "10.0.0.0/8"
  - regions:
      - "US"
      - "EU"

# Create service perimeter
gcloud access-context-manager perimeters create data-perimeter \
    --policy=POLICY_ID \
    --title="Data Perimeter" \
    --resources=projects/123456789,projects/987654321 \
    --restricted-services=bigquery.googleapis.com,storage.googleapis.com \
    --access-levels=trusted

# Allow ingress (external access in)
gcloud access-context-manager perimeters update data-perimeter \
    --policy=POLICY_ID \
    --set-ingress-policies=ingress.yaml

# ingress.yaml
- ingressFrom:
    identityType: ANY_IDENTITY
    sources:
      - accessLevel: accessPolicies/POLICY_ID/accessLevels/trusted
  ingressTo:
    operations:
      - serviceName: bigquery.googleapis.com
        methodSelectors:
          - method: "*"
    resources:
      - "*"

# Allow egress (data out from perimeter)
gcloud access-context-manager perimeters update data-perimeter \
    --policy=POLICY_ID \
    --set-egress-policies=egress.yaml

# egress.yaml
- egressTo:
    operations:
      - serviceName: storage.googleapis.com
    resources:
      - projects/external-project
  egressFrom:
    identityType: ANY_IDENTITY





18. How do you implement identity federation?

Identity Federation:
+-- Workload Identity Federation (external workloads)
+-- SAML/OIDC for users
+-- No service account keys
+-- Direct access from AWS, Azure, etc.

# Workload Identity Federation (AWS to GCP)
# 1. Create workload identity pool
gcloud iam workload-identity-pools create aws-pool \
    --location=global \
    --display-name="AWS Pool"

# 2. Add AWS provider
gcloud iam workload-identity-pools providers create-aws aws-provider \
    --location=global \
    --workload-identity-pool=aws-pool \
    --account-id=123456789012 \
    --attribute-mapping=\
google.subject=assertion.arn,\
attribute.aws_role=assertion.arn.extract('assumed-role/{role}/')

# 3. Grant service account access
gcloud iam service-accounts add-iam-policy-binding \
    my-sa@my-project.iam.gserviceaccount.com \
    --role="roles/iam.workloadIdentityUser" \
    --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/aws-pool/attribute.aws_role/my-role"

# 4. Configure credential in AWS
# credential-config.json
{
  "type": "external_account",
  "audience": "//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/aws-pool/providers/aws-provider",
  "subject_token_type": "urn:ietf:params:aws:token-type:aws4_request",
  "service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/my-sa@my-project.iam.gserviceaccount.com:generateAccessToken",
  "token_url": "https://sts.googleapis.com/v1/token",
  "credential_source": {
    "environment_id": "aws1",
    "regional_cred_verification_url": "https://sts.{region}.amazonaws.com"
  }
}

# 5. Use in code
export GOOGLE_APPLICATION_CREDENTIALS=credential-config.json
python my_gcp_script.py  # Auto-authenticates

# OIDC Federation (GitHub Actions)
gcloud iam workload-identity-pools providers create-oidc github \
    --location=global \
    --workload-identity-pool=github-pool \
    --issuer-uri="https://token.actions.githubusercontent.com" \
    --attribute-mapping=\
google.subject=assertion.sub,\
attribute.repository=assertion.repository

19. What is domain-wide delegation?

Domain-Wide Delegation:
+-- Service account acts as users
+-- Access Google Workspace data
+-- Requires Workspace admin setup
+-- Used for admin operations

# 1. Enable domain-wide delegation on SA
gcloud iam service-accounts update \
    my-sa@my-project.iam.gserviceaccount.com \
    --enable-delegation

# 2. In Google Workspace Admin Console:
# Security > API Controls > Domain-wide delegation
# Add client ID and scopes

Scopes needed:
+-- Gmail: https://www.googleapis.com/auth/gmail.readonly
+-- Drive: https://www.googleapis.com/auth/drive.readonly
+-- Calendar: https://www.googleapis.com/auth/calendar.readonly
+-- Directory: https://www.googleapis.com/auth/admin.directory.user.readonly

# Python: Impersonate user
from google.oauth2 import service_account
from googleapiclient.discovery import build

# Load service account credentials
credentials = service_account.Credentials.from_service_account_file(
    'key.json',
    scopes=['https://www.googleapis.com/auth/gmail.readonly']
)

# Impersonate a user
delegated_credentials = credentials.with_subject('user@company.com')

# Build service
service = build('gmail', 'v1', credentials=delegated_credentials)

# Access user's Gmail
results = service.users().messages().list(userId='me').execute()

# Admin SDK example
credentials = service_account.Credentials.from_service_account_file(
    'key.json',
    scopes=['https://www.googleapis.com/auth/admin.directory.user.readonly']
)
delegated_credentials = credentials.with_subject('admin@company.com')

admin_service = build('admin', 'directory_v1', credentials=delegated_credentials)
users = admin_service.users().list(customer='my_customer').execute()

20. What are IAM best practices?

IAM Best Practices:

1. Use principle of least privilege
+-- Grant minimum required permissions
+-- Use predefined roles over basic roles
+-- Create custom roles when needed
+-- Grant at resource level, not project

2. Use groups for access management
# Instead of:
--member="user:alice@company.com"
--member="user:bob@company.com"

# Use:
--member="group:data-team@company.com"

3. Avoid service account keys
+-- Use Workload Identity for GKE
+-- Use attached SAs for GCE/Functions
+-- Use Workload Identity Federation for external
+-- If keys needed, rotate and store securely

4. Implement defense in depth
+-- IAM policies
+-- VPC Service Controls
+-- Organization policies
+-- IAP for applications
+-- Audit logging

5. Regular access reviews
# Automate with recommender
gcloud recommender recommendations list \
    --recommender=google.iam.policy.Recommender

6. Separate environments
+-- Development - Permissive for iteration
+-- Staging - Production-like
+-- Production - Strictest controls

7. Use conditions for context-aware access
--condition='
    expression=request.time < timestamp("2024-12-31") &&
    resource.name.startsWith("projects/my-project/datasets/dev_"),
    title=temporary-dev-access'

8. Enable comprehensive logging
"auditConfigs": [{
    "service": "allServices",
    "auditLogConfigs": [
        {"logType": "ADMIN_READ"},
        {"logType": "DATA_READ"},
        {"logType": "DATA_WRITE"}
    ]
}]

9. Use organization policies
+-- Disable SA key creation
+-- Restrict resource locations
+-- Prevent public access
+-- Enforce security baselines

10. Document and automate
+-- Infrastructure as Code (Terraform)
+-- Version control IAM configs
+-- Automated testing
+-- Change management process

Google Cloud Interview Questions


Popular Posts