Files
skills/public/cloud-gcp-iam-security.html
zeekayandHanzo Dev 9e10c1c10e Each llms index points at the other two
hanzoskills.com/llms.txt now opens with the install line, the API
reference index and the company index, so an agent that lands on any
one of the three can find the rest.

robots.txt claimed 537 documents while llms.txt counts 920. The number
is gone from robots.txt; llms.txt derives it.

public/ is regenerated from scripts/site.py, which it had fallen
behind: the copy-prompt menu and agent bar were in the generator and
not in the committed pages. tests/site.mjs passes against the result.

Co-authored-by: Hanzo Dev <[email protected]>
2026-09-11 00:27:59 -07:00

707 lines
34 KiB
HTML

<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>cloud-gcp-iam-security</title>
<meta name="color-scheme" content="dark">
<style>
/* Committed to one visual world: a dark instrument panel. No light variant —
the dot field and the hairline rules only read on black, and a naive
inversion would wash both out. Every colour is painted explicitly so the page
never borrows a host background. */
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
:root{
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
--font-zen-pixel-square:'Zen Pixel Square',monospace;
--mono:var(--font-zen-mono);
--sans:var(--font-zen-sans);
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
--r:999px; --r-soft:14px;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
/* The dot field. A halftone made of one repeating radial-gradient, faded out
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
/* No overflow clip here: the dot field is inset to the box already, and a clip
would cut off the copy-prompt menu. */
.hero{position:relative;border-bottom:1px solid var(--line)}
.hero::before{content:"";position:absolute;inset:0;
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
background-size:7px 7px;
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
pointer-events:none}
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
nav{border-bottom:1px solid var(--line)}
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
justify-content:space-between;align-items:center;gap:1rem}
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--ink);text-decoration:none;
display:inline-flex;align-items:center;gap:.6rem}
.brand i{font-style:normal;color:var(--faint)}
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--soft);text-decoration:none}
nav a.up:hover{color:var(--ink)}
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
h1 em{font-style:normal;color:var(--faint)}
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
line-height:1.2;font-weight:400}
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
.btn.solid:hover{background:#d8d8d4}
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
/* Copy-prompt selector. Each row copies the prompt for its own target. */
.copy{position:relative;display:inline-flex}
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
padding:.4rem;display:flex;flex-direction:column;
box-shadow:0 12px 32px rgba(0,0,0,.75)}
.menu[hidden]{display:none}
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
white-space:nowrap}
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
.mi:hover .mark{color:var(--ink)}
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
letter-spacing:.1em;text-transform:uppercase}
/* Works-with bar: one scrolling row, name and mark per agent. */
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
display:flex;align-items:center}
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
-webkit-overflow-scrolling:touch;
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
.bar::-webkit-scrollbar{display:none}
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
text-decoration:none;background:var(--ground)}
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
.agent .mark{width:.95rem;height:.95rem}
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
p{margin:0 0 1rem;max-width:70ch}
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
li{margin:.22rem 0}
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
text-decoration-color:var(--line-hi)}
a:hover{text-decoration-color:var(--ink)}
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
display:block;overflow-x:auto}
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
.curl{display:block;background:var(--panel);border:1px solid var(--line);
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
white-space:pre;line-height:1.9}
.curl b{color:var(--ink);font-weight:400}
.curl i{font-style:normal;color:var(--faint)}
/* index */
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
#q:focus{outline:none;border-color:var(--soft)}
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
text-transform:uppercase;margin:0 0 2rem}
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
padding-bottom:.45rem}
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
border-radius:var(--r-soft);text-decoration:none}
.row:hover{background:#0a0a0a}
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
color:var(--faint);font-size:.85rem}
footer a{color:var(--soft)}
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
margin:0 0 2rem;font-size:.85rem}
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
border-bottom:1px solid var(--line);padding-bottom:.4rem}
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
.fmap a:hover{text-decoration:underline}
.fmap div{color:var(--faint);line-height:1.5}
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
@media (max-width:640px){
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
.btns{gap:.5rem}
.btn{padding:.75rem 1.15rem;font-size:.68rem}
.copy,.copy .btn{width:100%;justify-content:center}
.menu{left:0;right:0;min-width:0}
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
.strip b{border-right:0;padding-right:0}
.bar{width:100%}
}
</style>
<link rel="alternate" type="text/markdown" href="/cloud-gcp-iam-security.md">
<link rel="icon" href="/favicon.svg">
<link rel="canonical" href="https://hanzoskills.com/cloud-gcp-iam-security">
</head>
<!-- Reading this with a machine? Every page here is also plain markdown.
This one: https://hanzoskills.com/cloud-gcp-iam-security.md
Index: https://hanzoskills.com/llms.txt
Corpus: https://hanzoskills.com/all.md
Append .md to any path for the markdown twin. -->
<body>
<nav><div class="in">
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
<a class="up" href="/">All skills</a>
</div></nav>
<div class="wrap">
<h1>cloud-gcp-iam-security</h1><p class="lede">Google Cloud IAM, service accounts, Secret Manager, and Cloud KMS security practices</p><h1>GCP IAM and Security</h1>
<p><strong>Scope</strong>: IAM policies, service accounts, authentication, Secret Manager, and Cloud KMS encryption <strong>Lines</strong>: ~330 <strong>Last Updated</strong>: 2025-10-25 <strong>Format Version</strong>: 1.0 (Atomic)</p>
<hr>
<h2>When to Use This Skill</h2>
<p>Activate this skill when:</p>
<ul><li>Configuring IAM roles and permissions for users and services</li><li>Creating and managing service accounts for workloads</li><li>Implementing authentication with Identity Platform</li><li>Storing secrets and credentials in Secret Manager</li><li>Managing encryption keys with Cloud KMS</li><li>Setting up organization policies and constraints</li><li>Implementing least privilege access control</li><li>Rotating service account keys and secrets</li></ul>
<h2>Core Concepts</h2>
<h3>Concept 1: IAM Roles and Policies</h3>
<p><strong>Role types</strong>:</p>
<ul><li><strong>Basic roles</strong>: Owner, Editor, Viewer (legacy, too broad)</li><li><strong>Predefined roles</strong>: Curated by Google (e.g., Storage Admin, Compute Instance Admin)</li><li><strong>Custom roles</strong>: User-defined with specific permissions</li></ul>
<pre><code class="lang-bash"># Grant user a predefined role at project level
gcloud projects add-iam-policy-binding my-project \
--member=user:[email protected] \
--role=roles/compute.instanceAdmin.v1
# Grant service account a role at resource level
gcloud storage buckets add-iam-policy-binding gs://my-bucket \
--member=serviceAccount:[email protected] \
--role=roles/storage.objectViewer
# Create custom role with specific permissions
gcloud iam roles create customStorageRole \
--project=my-project \
--title=&quot;Custom Storage Role&quot; \
--description=&quot;Read objects and list buckets&quot; \
--permissions=storage.objects.get,storage.objects.list,storage.buckets.list \
--stage=GA</code></pre>
<h3>Concept 2: Service Accounts</h3>
<p><strong>Service account types</strong>:</p>
<ul><li><strong>User-managed</strong>: Created by users for applications</li><li><strong>Default</strong>: Automatically created by Google (Compute, App Engine)</li><li><strong>Google-managed</strong>: Used internally by Google services</li></ul>
<pre><code class="lang-python">from google.cloud import iam_admin_v1
from google.oauth2 import service_account
# Create service account
def create_service_account(project_id, account_id, display_name):
client = iam_admin_v1.IAMClient()
service_account = iam_admin_v1.ServiceAccount(
display_name=display_name
)
request = iam_admin_v1.CreateServiceAccountRequest(
name=f&quot;projects/{project_id}&quot;,
account_id=account_id,
service_account=service_account
)
account = client.create_service_account(request=request)
return account
# Use service account credentials in application
credentials = service_account.Credentials.from_service_account_file(
&#x27;path/to/service-account-key.json&#x27;,
scopes=[&#x27;https://www.googleapis.com/auth/cloud-platform&#x27;]
)
# Best practice: Use Workload Identity instead of key files
# See Pattern 5 below</code></pre>
<h3>Concept 3: Secret Manager</h3>
<p><strong>Features</strong>:</p>
<ul><li>Store API keys, passwords, certificates securely</li><li>Automatic encryption at rest</li><li>Version management and rotation</li><li>IAM-based access control</li></ul>
<pre><code class="lang-python">from google.cloud import secretmanager
def create_secret(project_id, secret_id, secret_value):
client = secretmanager.SecretManagerServiceClient()
# Create secret
parent = f&quot;projects/{project_id}&quot;
secret = client.create_secret(
request={
&quot;parent&quot;: parent,
&quot;secret_id&quot;: secret_id,
&quot;secret&quot;: {&quot;replication&quot;: {&quot;automatic&quot;: {}}},
}
)
# Add secret version
payload = secret_value.encode(&quot;UTF-8&quot;)
version = client.add_secret_version(
request={
&quot;parent&quot;: secret.name,
&quot;payload&quot;: {&quot;data&quot;: payload}
}
)
return version.name
def access_secret(project_id, secret_id, version_id=&quot;latest&quot;):
client = secretmanager.SecretManagerServiceClient()
name = f&quot;projects/{project_id}/secrets/{secret_id}/versions/{version_id}&quot;
response = client.access_secret_version(request={&quot;name&quot;: name})
return response.payload.data.decode(&quot;UTF-8&quot;)
# Example usage
api_key = access_secret(&quot;my-project&quot;, &quot;third-party-api-key&quot;)</code></pre>
<h3>Concept 4: Cloud KMS Encryption</h3>
<p><strong>Key types</strong>:</p>
<ul><li><strong>Symmetric</strong>: Same key for encryption/decryption (AEAD)</li><li><strong>Asymmetric</strong>: Public/private key pairs (signing, decryption)</li><li><strong>Key rings</strong>: Logical grouping of keys in a location</li></ul>
<pre><code class="lang-python">from google.cloud import kms
def create_key_ring_and_key(project_id, location_id, key_ring_id, key_id):
client = kms.KeyManagementServiceClient()
# Create key ring
location_name = f&quot;projects/{project_id}/locations/{location_id}&quot;
key_ring = client.create_key_ring(
request={
&quot;parent&quot;: location_name,
&quot;key_ring_id&quot;: key_ring_id
}
)
# Create crypto key
key = client.create_crypto_key(
request={
&quot;parent&quot;: key_ring.name,
&quot;crypto_key_id&quot;: key_id,
&quot;crypto_key&quot;: {
&quot;purpose&quot;: kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT,
&quot;version_template&quot;: {
&quot;algorithm&quot;: kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION
}
}
}
)
return key
def encrypt_symmetric(project_id, location_id, key_ring_id, key_id, plaintext):
client = kms.KeyManagementServiceClient()
key_name = f&quot;projects/{project_id}/locations/{location_id}/keyRings/{key_ring_id}/cryptoKeys/{key_id}&quot;
plaintext_bytes = plaintext.encode(&quot;utf-8&quot;)
response = client.encrypt(
request={&quot;name&quot;: key_name, &quot;plaintext&quot;: plaintext_bytes}
)
return response.ciphertext
def decrypt_symmetric(project_id, location_id, key_ring_id, key_id, ciphertext):
client = kms.KeyManagementServiceClient()
key_name = f&quot;projects/{project_id}/locations/{location_id}/keyRings/{key_ring_id}/cryptoKeys/{key_id}&quot;
response = client.decrypt(
request={&quot;name&quot;: key_name, &quot;ciphertext&quot;: ciphertext}
)
return response.plaintext.decode(&quot;utf-8&quot;)</code></pre>
<hr>
<h2>Patterns</h2>
<h3>Pattern 1: Least Privilege with Conditional IAM</h3>
<p><strong>When to use</strong>:</p>
<ul><li>Grant access only when specific conditions are met</li><li>Time-based access, IP-based restrictions</li></ul>
<pre><code class="lang-python"># ❌ Bad: Grant broad access without conditions
# Member can access from anywhere, anytime
gcloud projects add-iam-policy-binding my-project \
--member=user:[email protected] \
--role=roles/compute.admin
# ✅ Good: Conditional access with time and IP restrictions
from google.cloud import iam_v1
def add_conditional_binding(project_id, member, role):
client = iam_v1.IAMPolicyClient()
policy = client.get_iam_policy(request={&quot;resource&quot;: f&quot;projects/{project_id}&quot;})
# Add conditional binding
binding = iam_v1.Binding(
role=role,
members=[member],
condition=iam_v1.Expr(
title=&quot;Temporary access during business hours&quot;,
description=&quot;Access granted Mon-Fri 9am-5pm from office IP&quot;,
expression=&quot;&quot;&quot;
request.time.getHours(&quot;America/Los_Angeles&quot;) &gt;= 9 &amp;&amp;
request.time.getHours(&quot;America/Los_Angeles&quot;) &lt; 17 &amp;&amp;
request.time.getDayOfWeek(&quot;America/Los_Angeles&quot;) &gt;= 1 &amp;&amp;
request.time.getDayOfWeek(&quot;America/Los_Angeles&quot;) &lt;= 5 &amp;&amp;
inIpRange(request.ip, &#x27;203.0.113.0/24&#x27;)
&quot;&quot;&quot;
)
)
policy.bindings.append(binding)
client.set_iam_policy(request={&quot;resource&quot;: f&quot;projects/{project_id}&quot;, &quot;policy&quot;: policy})</code></pre>
<p><strong>Benefits</strong>:</p>
<ul><li>Enforce time-based access for contractors</li><li>Restrict access to specific IP ranges (VPN, office)</li><li>Reduce attack surface and unauthorized access</li></ul>
<h3>Pattern 2: Service Account Impersonation</h3>
<p><strong>Use case</strong>: Developers test with service account permissions without downloading keys</p>
<pre><code class="lang-bash"># ❌ Bad: Download service account key and share with developers
gcloud iam service-accounts keys create key.json \
[email protected]
# Key can be leaked, no audit trail
# ✅ Good: Grant impersonation permission to developer
gcloud iam service-accounts add-iam-policy-binding \
[email protected] \
--member=user:[email protected] \
--role=roles/iam.serviceAccountTokenCreator
# Developer impersonates service account
gcloud compute instances list \
--impersonate-service-account=app@my-project.iam.gserviceaccount.com
# Or in code
from google.auth import impersonated_credentials
import google.auth
source_credentials, project_id = google.auth.default()
target_scopes = [&#x27;https://www.googleapis.com/auth/cloud-platform&#x27;]
target_credentials = impersonated_credentials.Credentials(
source_credentials=source_credentials,
target_principal=&#x27;[email protected]&#x27;,
target_scopes=target_scopes
)</code></pre>
<h3>Pattern 3: Secret Rotation with Versions</h3>
<p><strong>Use case</strong>: Rotate secrets without downtime</p>
<pre><code class="lang-python">from google.cloud import secretmanager
def rotate_secret(project_id, secret_id, new_value):
client = secretmanager.SecretManagerServiceClient()
# Add new version
secret_name = f&quot;projects/{project_id}/secrets/{secret_id}&quot;
payload = new_value.encode(&quot;UTF-8&quot;)
new_version = client.add_secret_version(
request={
&quot;parent&quot;: secret_name,
&quot;payload&quot;: {&quot;data&quot;: payload}
}
)
# Application automatically uses latest version
# After verifying new version works:
# Disable old versions (don&#x27;t delete immediately)
versions = client.list_secret_versions(request={&quot;parent&quot;: secret_name})
for version in versions:
if version.name != new_version.name:
client.disable_secret_version(request={&quot;name&quot;: version.name})
# After grace period (e.g., 30 days), destroy old versions
# client.destroy_secret_version(request={&quot;name&quot;: old_version.name})
return new_version</code></pre>
<h3>Pattern 4: Organization Policies</h3>
<p><strong>Use case</strong>: Enforce security constraints across entire organization</p>
<pre><code class="lang-bash"># Disable service account key creation organization-wide
gcloud resource-manager org-policies set-policy \
--organization=ORGANIZATION_ID \
policy.yaml
# policy.yaml
constraint: constraints/iam.disableServiceAccountKeyCreation
listPolicy:
allValues: DENY
# Restrict VM external IPs to specific projects
constraint: constraints/compute.vmExternalIpAccess
listPolicy:
allowedValues:
- projects/production-project
- projects/staging-project
deniedValues:
- projects/dev-project
# Require CMEK encryption for Cloud Storage
constraint: constraints/storage.requireCMEK
booleanPolicy:
enforced: true</code></pre>
<h3>Pattern 5: Workload Identity for GKE</h3>
<p><strong>Use case</strong>: Pods authenticate as GCP service accounts without key files</p>
<pre><code class="lang-bash"># ❌ Bad: Mount service account key as Kubernetes secret
kubectl create secret generic gcp-key \
--from-file=key.json=./service-account-key.json
# Key can be extracted from cluster
# ✅ Good: Use Workload Identity
# Enable Workload Identity on cluster
gcloud container clusters create prod-cluster \
--workload-pool=my-project.svc.id.goog \
--zone=us-central1-a
# Create Kubernetes service account
kubectl create serviceaccount app-sa
# Create GCP service account
gcloud iam service-accounts create app-gsa
# Grant GCP permissions to service account
gcloud projects add-iam-policy-binding my-project \
--member=serviceAccount:[email protected] \
--role=roles/storage.objectViewer
# Bind Kubernetes SA to GCP SA
gcloud iam service-accounts add-iam-policy-binding \
[email protected] \
--role=roles/iam.workloadIdentityUser \
--member=&quot;serviceAccount:my-project.svc.id.goog[default/app-sa]&quot;
# Annotate Kubernetes service account
kubectl annotate serviceaccount app-sa \
iam.gke.io/[email protected]
# Pods using app-sa automatically get GCP credentials</code></pre>
<h3>Pattern 6: Audit Logging</h3>
<p><strong>Use case</strong>: Track who did what, when, and from where</p>
<pre><code class="lang-python">from google.cloud import logging
def query_admin_activity_logs(project_id, hours=24):
client = logging.Client(project=project_id)
# Query admin activity logs
filter_str = f&quot;&quot;&quot;
logName=&quot;projects/{project_id}/logs/cloudaudit.googleapis.com%2Factivity&quot;
AND timestamp &gt;= &quot;{hours}h&quot;
AND protoPayload.methodName:&quot;compute.instances.delete&quot;
&quot;&quot;&quot;
entries = client.list_entries(filter_=filter_str)
for entry in entries:
print(f&quot;User: {entry.payload.get(&#x27;authenticationInfo&#x27;, {}).get(&#x27;principalEmail&#x27;)}&quot;)
print(f&quot;Action: {entry.payload.get(&#x27;methodName&#x27;)}&quot;)
print(f&quot;Resource: {entry.payload.get(&#x27;resourceName&#x27;)}&quot;)
print(f&quot;Time: {entry.timestamp}&quot;)
print(f&quot;IP: {entry.payload.get(&#x27;requestMetadata&#x27;, {}).get(&#x27;callerIp&#x27;)}&quot;)
print(&quot;---&quot;)</code></pre>
<pre><code class="lang-bash"># Create log sink to export logs to Cloud Storage
gcloud logging sinks create audit-logs-sink \
storage.googleapis.com/audit-logs-bucket \
--log-filter=&#x27;logName:&quot;cloudaudit.googleapis.com&quot;&#x27;</code></pre>
<h3>Pattern 7: VPC Service Controls</h3>
<p><strong>Use case</strong>: Create security perimeters to prevent data exfiltration</p>
<pre><code class="lang-bash"># Create access policy
gcloud access-context-manager policies create \
--organization=ORGANIZATION_ID \
--title=&quot;Corporate Policy&quot;
# Create access level (who can access)
gcloud access-context-manager levels create corporate_network \
--policy=POLICY_ID \
--title=&quot;Corporate Network&quot; \
--basic-level-spec=access_level.yaml
# access_level.yaml
ipSubnetworks:
- 203.0.113.0/24 # Office IP range
# Create service perimeter (what resources are protected)
gcloud access-context-manager perimeters create production_perimeter \
--policy=POLICY_ID \
--title=&quot;Production Data&quot; \
--resources=projects/123456789 \
--restricted-services=storage.googleapis.com,bigquery.googleapis.com \
--access-levels=corporate_network
# Now Cloud Storage and BigQuery in project can only be accessed from office IP</code></pre>
<h3>Pattern 8: IAM Recommender</h3>
<p><strong>Use case</strong>: Identify and remove excessive permissions</p>
<pre><code class="lang-bash"># List IAM recommendations
gcloud recommender recommendations list \
--project=my-project \
--location=global \
--recommender=google.iam.policy.Recommender
# Apply recommendation to remove unused permissions
gcloud recommender recommendations mark-claimed \
RECOMMENDATION_ID \
--project=my-project \
--location=global \
--recommender=google.iam.policy.Recommender
# After testing, mark as succeeded
gcloud recommender recommendations mark-succeeded \
RECOMMENDATION_ID \
--project=my-project \
--location=global \
--recommender=google.iam.policy.Recommender</code></pre>
<hr>
<h2>Quick Reference</h2>
<h3>IAM Role Types</h3>
<pre><code>Role Type | Example | Use Case
--------------|--------------------------------|----------------------------
Basic | Owner, Editor, Viewer | Avoid in production (too broad)
Predefined | roles/compute.instanceAdmin.v1 | Use for common scenarios
Custom | customStorageRole | Fine-grained permissions</code></pre>
<h3>Key gcloud Commands</h3>
<pre><code class="lang-bash"># IAM
gcloud projects add-iam-policy-binding PROJECT --member=MEMBER --role=ROLE
gcloud projects get-iam-policy PROJECT
gcloud projects remove-iam-policy-binding PROJECT --member=MEMBER --role=ROLE
# Service Accounts
gcloud iam service-accounts create SA_ID --display-name=NAME
gcloud iam service-accounts list
gcloud iam service-accounts keys create key.json --iam-account=SA_EMAIL
# Secrets
gcloud secrets create SECRET_ID --replication-policy=automatic
gcloud secrets versions add SECRET_ID --data-file=secret.txt
gcloud secrets versions access latest --secret=SECRET_ID
# KMS
gcloud kms keyrings create KEYRING --location=LOCATION
gcloud kms keys create KEY --keyring=KEYRING --location=LOCATION --purpose=encryption</code></pre>
<h3>Security Best Practices</h3>
<pre><code>✅ DO: Use predefined roles over basic roles (Owner/Editor/Viewer)
✅ DO: Rotate service account keys every 90 days (or use Workload Identity)
✅ DO: Enable audit logging for all projects
✅ DO: Use Secret Manager for sensitive data (never hardcode)
✅ DO: Implement VPC Service Controls for sensitive data
✅ DO: Review IAM Recommender suggestions monthly
❌ DON&#x27;T: Use basic roles in production (too broad)
❌ DON&#x27;T: Download service account keys (use Workload Identity)
❌ DON&#x27;T: Store secrets in environment variables or code
❌ DON&#x27;T: Grant project-level permissions when resource-level suffices
❌ DON&#x27;T: Ignore audit logs (monitor for anomalies)</code></pre>
<hr>
<h2>Anti-Patterns</h2>
<h3>Critical Violations</h3>
<pre><code class="lang-bash"># ❌ NEVER: Grant Owner role to service accounts
gcloud projects add-iam-policy-binding my-project \
--member=serviceAccount:[email protected] \
--role=roles/owner
# Service account can delete entire project!
# ✅ CORRECT: Grant minimal permissions needed
gcloud projects add-iam-policy-binding my-project \
--member=serviceAccount:[email protected] \
--role=roles/storage.objectViewer
gcloud storage buckets add-iam-policy-binding gs://specific-bucket \
--member=serviceAccount:[email protected] \
--role=roles/storage.objectAdmin</code></pre>
<p>❌ <strong>Overly broad service account permissions</strong>: Granting Owner or Editor to service accounts creates massive security risk. ✅ <strong>Correct approach</strong>: Grant specific predefined roles at resource level, not project level.</p>
<h3>Common Mistakes</h3>
<pre><code class="lang-python"># ❌ Don&#x27;t: Hardcode secrets in code (example of what NOT to do)
DATABASE_PASSWORD = &quot;super_secret_password&quot; # Exposed in source control! Example only
# ✅ Correct: Load from Secret Manager
from google.cloud import secretmanager
client = secretmanager.SecretManagerServiceClient()
name = f&quot;projects/my-project/secrets/db-password/versions/latest&quot;
response = client.access_secret_version(request={&quot;name&quot;: name})
DATABASE_PASSWORD = response.payload.data.decode(&quot;UTF-8&quot;)</code></pre>
<p>❌ <strong>Hardcoded secrets</strong>: Secrets in code are exposed via source control, logs, and error messages. ✅ <strong>Better</strong>: Store all secrets in Secret Manager and retrieve at runtime.</p>
<pre><code class="lang-bash"># ❌ Don&#x27;t: Create service account keys unnecessarily
gcloud iam service-accounts keys create key.json \
[email protected]
# Keys can be leaked, hard to rotate
# ✅ Correct: Use Workload Identity (GKE) or Application Default Credentials
# On GCE/GKE/Cloud Run: Automatically uses instance/pod service account
# On local dev: Use impersonation
gcloud auth application-default login \
--impersonate-service-account=app@my-project.iam.gserviceaccount.com</code></pre>
<p>❌ <strong>Service account key files</strong>: Keys are long-lived credentials that can be leaked and are difficult to rotate. ✅ <strong>Better</strong>: Use Workload Identity for GKE, instance service accounts for GCE, or impersonation for development.</p>
<pre><code class="lang-bash"># ❌ Don&#x27;t: Disable organization policies to &quot;get things working&quot;
gcloud resource-manager org-policies disable-enforce \
constraints/compute.requireOsLogin \
--organization=ORG_ID
# Opens security hole across entire organization
# ✅ Correct: Understand policy and create exception if needed
gcloud resource-manager org-policies set-policy \
--organization=ORG_ID \
policy.yaml
# policy.yaml - Allow exception for specific project
constraint: constraints/compute.requireOsLogin
listPolicy:
deniedValues:
- projects/legacy-project # Exception for legacy system</code></pre>
<p>❌ <strong>Disabling org policies</strong>: Disabling organization-wide policies creates security vulnerabilities. ✅ <strong>Better</strong>: Understand the policy requirement and create targeted exceptions if absolutely necessary.</p>
<hr>
<h2>Related Skills</h2>
<ul><li><code>gcp-compute.md</code> - Service accounts for Compute Engine instances</li><li><code>gcp-databases.md</code> - Database user management and IAM authentication</li><li><code>gcp-storage.md</code> - Bucket IAM policies and signed URLs</li><li><code>gcp-networking.md</code> - Firewall rules and network security</li></ul>
<hr>
<p><strong>Last Updated</strong>: 2025-10-25 <strong>Format Version</strong>: 1.0 (Atomic)</p>
<footer>
<div class="fmap">
<div><b>Build</b>
<a href="https://hanzo.app">hanzo.app</a> app builder
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
<div><b>Run</b>
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
<div><b>Account</b>
<a href="https://hanzo.id">hanzo.id</a> sign in
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
<div><b>Company</b>
<a href="https://hanzo.ai">hanzo.ai</a> canonical
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
</div>
<div class="fend"><a href="/cloud-gcp-iam-security.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
</footer>
</div></body></html>