Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install iam-helper-for-privileged-access-management@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin iam-helper-for-privileged-access-management v1.0.0 follows the Agent Plugins spec.
gh skills-hub install iam-helper-for-privileged-access-management Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/iam-helper-for-privileged-access-management/ Extract the ZIP to .github/skills/ in your repo. The folder name must match iam-helper-for-privileged-access-management for Copilot to auto-discover it.
Skill Files (7)
SKILL.md 12.6 KB
---
name: iam-helper-for-privileged-access-management
metadata:
version: "1.0.2"
category: Security
description: >-
Manages the end-to-end lifecycle of on-demand, temporary access using
Privileged Access Manager (PAM). Use when a user asks to create, read,
update, or delete PAM entitlements, request temporary access, or
approve/deny pending PAM grants. Do NOT use for permanent IAM policy
bindings, troubleshooting IAM permission errors, or general Google Cloud
resource provisioning.
---
# Privileged Access Manager (PAM)
This skill provides step-by-step guidance for planning, validating, and
executing Privileged Access Manager (PAM) entitlement CRUD operations, approval
workflow configurations, access elevations, and grant approval/denial workflows.
## Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
## Table of Contents
* [Core Concepts](#core-concepts)
* [Approval Workflows & Max Request Duration](#approval-workflows)
* [Safety & Confirmation Strategy](#safety-confirmation)
* [Plan-Validate-Execute Pattern](#plan-validate-execute)
* [Mode 1: Interactive Access Elevation](#mode-1)
* [Mode 2: Standalone Entitlement CRUD](#mode-2)
* [Mode 3: Approver Workflow](#mode-3)
* [Supporting Links & Resources](#supporting-links)
## Core Concepts {#core-concepts}
Privileged Access Manager (PAM) replaces permanent or ambient IAM role
assignments with on-demand, time-bound, and audited access elevations. Rather than
appending permanent IAM policy bindings, PAM uses:
* **Entitlements:** Configurations defining access scopes, eligible
requesters, and approvers.
* **Grants:** Short-lived requests created against entitlements to activate
the entitlement's IAM roles.
### Privileged Access (`privilegedAccess`)
The `privilegedAccess` block in an entitlement defines the precise access scope that will be granted. An access scope comprises three essential components:
* **Resource:** The target Google Cloud resource (Project, Folder, or Organization) where access is granted.
* **Role Setup:** The IAM role (`roleBindings.role`) to be assigned.
* **Condition:** (Optional) An IAM condition expression (`roleBindings.conditionExpression`) restricting when or where the role applies.
### Core Workflow
1. Administrators create Entitlements.
2. Requesters can then request Grants against these entitlements.
3. If the entitlement is configured with approvals, then an approver must
approve the requested grant.
4. Once all necessary approval steps are completed, the grant is activated for
the requested time.
5. The grant automatically ends after the requested duration has elapsed, and
the elevated access is removed.
## Approval Workflows & Max Request Duration {#approval-workflows}
### Approval Workflows (`approvalWorkflow`)
When sensitive environments require human approval before temporary access is
activated, configure the `approvalWorkflow` block in the entitlement YAML
manifest (`entitlement.yaml`).
```yaml
approvalWorkflow:
manualApprovals:
# Optional: requires approver to supply a justification string
requireApproverJustification: true
steps:
- approvalsNeeded: 1
approverEmailRecipients:
- approver@example.com
approvers:
- principals:
- user:db-lead@my-company.com # or group:sre-leads@my-company.com
```
* **When to include:** Include `approvalWorkflow` whenever the user prompt
specifies that manual approval or an approver (user or group) is required.
* **Outcome:** When a user requests a grant against an entitlement
with `approvalWorkflow`, the grant transitions to `APPROVAL_AWAITED`.
Requesters must await an Approver's decision (`Mode 3`).
### Max Request Duration (`maxRequestDuration`)
`maxRequestDuration` defines the maximum single access elevation timeframe a requester
may ask for when placing a grant request.
* **Flexible Configuration:** Configure `maxRequestDuration` according to the
user's specific request (e.g. `8 hours` / `28800s`, `1 hour` / `3600s`, `24
hours` / `86400s`).
* **Default Value:** If the user does NOT specify a maximum request duration,
default to `4 hours` (`14400s`).
* **YAML Syntax:** Always format `maxRequestDuration` as a string in seconds
in the entitlement YAML (e.g., `"14400s"`, `"28800s"`).
## Safety & Confirmation Strategy {#safety-confirmation}
Adhere strictly to these workflow guards:
* **Modifying / Destructive Executions (Create, Update, Delete, Approve, Deny, Revoke):** Always
present a plain-text summary of the planned adjustments and prompt the user
for explicit confirmation (Yes/No).
* **Read-Only Inspections (List, Describe, Search):** Run autonomously without
requesting confirmation.
* **Batching Bash Commands (Reduce User Confirmations):** The host environment
requires user approval for every individual shell tool call. To minimize
confirmation popups, combine sequential read-only and lookup commands into a
single compound bash script within one tool call (e.g., combining project,
folder, and organization hierarchy audits into a single multiline
execution).
* **Anti-Loop Strategy:** If a command fails with a clear, actionable error,
you may attempt to self-debug and retry. If the error is ambiguous, halt
immediately, present the stderr output, and await user direction.
## Plan-Validate-Execute Pattern {#plan-validate-execute}
For all modifying actions (Mode 1 Step 3, Mode 2 Create, Update, Delete, Mode 3 Approve, Deny):
1. **Plan:** Construct the proposed parameters or read the sample entitlement
structure. (For entitlement creation, load and use the template:
[assets/entitlement_template.yaml](assets/entitlement_template.yaml)).
2. **Validate:** Inspect the target configuration parameters (resource names,
role bindings, duration limits) for compliance with corporate rules.
3. **Execute:** Present the validated plan, obtain explicit user confirmation,
and run the `gcloud` command.
--------------------------------------------------------------------------------
## Mode 1: Interactive Access Elevation {#mode-1}
When the user requests temporary access elevation as a Requester, load and
follow the detailed instructions in
[`references/requester.md`](references/requester.md).
--------------------------------------------------------------------------------
## Mode 2: Standalone Entitlement CRUD {#mode-2}
Follow these steps for entitlement configurations.
### Required Permissions for Entitlement Admins
* `roles/privilegedaccessmanager.admin`: Required to create, update, and
delete entitlement configurations (`Mode 2 CRUD`).
* **Scope IAM Admin Rights:** Required on the target hierarchy scope because
creating an entitlement authorizes future role evaluations and bindings on
that scope:
* **Organizations:** `roles/iam.securityAdmin`
* **Folders:** `roles/resourcemanager.folderAdmin`
* **Projects:** `roles/resourcemanager.projectIamAdmin`
* `roles/privilegedaccessmanager.viewer`: Required to list and describe
entitlements across scopes.
*(Rule: For all Standalone Entitlement CRUD commands below, use the flag
matching where the entitlement is defined: pass `--project=PROJECT_ID`,
`--folder=FOLDER_ID`, or `--organization=ORGANIZATION_ID`).*
### 1. Create Entitlement
1. Check if `ENTITLEMENT_ID` exists:
```bash
gcloud pam entitlements describe ENTITLEMENT_ID \
--location=global \
--project=PROJECT_ID
```
* **If Exists:** Halt. Ask: *"The requested PAM Entitlement `ENTITLEMENT_ID`
already exists. Would you like to view its details or update it instead?
(View / Update / Exit)"*
* **If NOT_FOUND:** Load the template
[assets/entitlement_template.yaml](assets/entitlement_template.yaml).
Generate IDs in lowercase using hyphen separators derived from the role name
(e.g., `compute-admin` for `roles/compute.admin`). **Note:**
* You may specify multiple IAM roles under `roleBindings`.
* You may also include an optional IAM `conditionExpression` for each role binding.
* Legacy basic roles (e.g., `roles/viewer`, `roles/editor`, `roles/owner`)
are NOT supported. Instead, use the basic roles (`roles/reader`,
`roles/writer`, `roles/admin`). Ensure you select a valid predefined,
custom, or basic role.
* Set `maxRequestDuration` based on user specification (e.g. `"28800s"` for 8
hours, `"3600s"` for 1 hour). If unspecified by the user, default to
`"14400s"` (4 hours). If manual approval is specified by policy or requested
by the user, configure the `approvalWorkflow` block in `entitlement.yaml`.
Preserve `requesterJustificationConfig: {unstructured: {}}`.
* Prompt: *"You are about to create the PAM Entitlement `ENTITLEMENT_ID`. Do
you approve this creation? (Yes/No)"*
* Deploy:
```bash
gcloud pam entitlements create ENTITLEMENT_ID \
--location=global \
--entitlement-file=entitlement.yaml \
--project=PROJECT_ID
```
### 2. Read Entitlements
Run these read operations autonomously:
List all entitlements at a single scope:
```bash
gcloud pam entitlements list \
--location=global \
--project=PROJECT_ID
```
To list all entitlements defined across the entire resource hierarchy (project, ancestor folders, and organization), use the hierarchy listing script:
```bash
bash scripts/list_entitlements_hierarchy.sh --project=PROJECT_ID
```
*(Or pass `--folder=FOLDER_ID` or `--organization=ORGANIZATION_ID`).*
Describe target entitlement:
```bash
gcloud pam entitlements describe ENTITLEMENT_ID \
--location=global \
--project=PROJECT_ID
```
### 3. Update Entitlement
1. Run the `export` command to generate the current config (which includes the `etag`):
```bash
gcloud pam entitlements export ENTITLEMENT_ID \
--location=global \
--project=PROJECT_ID > {scratch}/updated_entitlement.yaml
```
If missing, offer to run `list` or exit.
2. Edit the exported `{scratch}/updated_entitlement.yaml` file to apply the requested changes (e.g., updating
`maxRequestDuration`, `approvalWorkflow`, or `eligibleUsers`). Do not alter the `etag`.
3. Prompt: *"You are about to update the PAM Entitlement `ENTITLEMENT_ID`. Do
you approve this update? (Yes/No)"*
4. Execute:
```bash
gcloud pam entitlements update ENTITLEMENT_ID \
--location=global \
--entitlement-file={scratch}/updated_entitlement.yaml \
--project=PROJECT_ID
```
### 4. Delete Entitlement
1. Verify existence using `describe`. If missing, offer list/exit.
2. **Safety Check:** An entitlement cannot be deleted if there are open grants.
Before deleting, search for any `ACTIVE` or `SCHEDULED` grants:
```bash
gcloud pam grants list \
--entitlement=ENTITLEMENT_ID \
--location=global \
--project=PROJECT_ID \
--filter="state:(ACTIVE, SCHEDULED)"
```
If any open grants are found, prompt the user for permission to revoke them: *"There are active or scheduled grants on this entitlement. Do you authorize me to revoke them so the entitlement can be deleted? (Yes/No)"*
If Yes, revoke them:
```bash
gcloud pam grants revoke GRANT_ID \
--entitlement=ENTITLEMENT_ID \
--location=global \
--project=PROJECT_ID \
--reason="Revoking to delete entitlement"
```
3. Prompt: *"You are about to permanently delete the PAM Entitlement
`ENTITLEMENT_ID`. Do you approve this deletion? (Yes/No)"*
4. Execute:
```bash
gcloud pam entitlements delete ENTITLEMENT_ID \
--location=global \
--project=PROJECT_ID
```
--------------------------------------------------------------------------------
## Mode 3: Approver Workflow {#mode-3}
When an Approver needs to review, approve, or reject pending grant requests,
load and follow the detailed instructions in
[`references/approver.md`](references/approver.md).
--------------------------------------------------------------------------------
## Supporting Links & Resources {#supporting-links}
For further information on working with Privileged Access Manager, refer to:
* [Google Cloud Privileged Access Manager Overview][pam-overview]
* [Setting up PAM Entitlements][pam-create]
* [Requesting and auditing PAM Grants][pam-grants]
* [gcloud SDK pam Reference Guide][pam-gcloud]
[pam-overview]: https://cloud.google.com/iam/docs/pam-overview
[pam-create]: https://cloud.google.com/iam/docs/pam-create-entitlements
[pam-grants]: https://cloud.google.com/iam/docs/pam-request-temporary-elevated-access
[pam-gcloud]: https://cloud.google.com/sdk/gcloud/reference/pam
entitlement_template.yaml 1.2 KB
privilegedAccess:
gcpIamAccess:
resourceType: cloudresourcemanager.googleapis.com/Project
resource: //cloudresourcemanager.googleapis.com/projects/PROJECT_ID
# Examples for other resources:
# resourceType: cloudresourcemanager.googleapis.com/Folder
# resource: //cloudresourcemanager.googleapis.com/folders/FOLDER_ID
# resourceType: cloudresourcemanager.googleapis.com/Organization
# resource: //cloudresourcemanager.googleapis.com/organizations/ORG_ID
roleBindings:
- role: ROLE_NAME
# conditionExpression: "request.time < timestamp('2027-01-01T00:00:00Z')"
maxRequestDuration: "14400s" # Maximum duration a requester can ask for (e.g. 14400s / 4 hours default, or custom like 28800s / 8 hours)
requesterJustificationConfig:
unstructured: {}
eligibleUsers:
- principals:
- user:user@example.com
# Optional: Manual Approval Workflow Configuration
# approvalWorkflow:
# manualApprovals:
# requireApproverJustification: true
# steps:
# - approvalsNeeded: 1
# approverEmailRecipients:
# - approver@example.com
# approvers:
# - principals:
# - user:approver@example.com # or group:approvers@example.com
approver.md 3.1 KB
# Mode 3: Approver Workflow (Grants)
Follow these steps when an Approver needs to review, approve, or reject pending
grant requests raised by requesters.
*(Rule: Select the scope flag matching where the entitlement/grant is located:
pass `--project=PROJECT_ID`, `--folder=FOLDER_ID`, or
`--organization=ORGANIZATION_ID`).*
## Table of Contents
* [Prerequisites & Permissions](#prerequisites)
* [Step 1: Search Pending Grants](#step-1)
* [Step 2: Approve Pending Grant](#step-2)
* [Step 3: Deny Pending Grant](#step-3)
### Prerequisites & Permissions {#prerequisites}
* **Approver Authorization:** To become an approver, the user simply must be
added to the `approvers` list in the entitlement's `approvalWorkflow`
configuration. No explicit IAM roles are required.
* **Discover Grants to Approve:** Approvers can directly search for grants
they are authorized to approve across a project, folder, or organization
using `gcloud pam grants search --caller-relationship=can-approve` without
needing the `roles/privilegedaccessmanager.viewer` role or knowing specific
entitlement IDs beforehand.
### Step 1: Search Pending Grants {#step-1}
Approvers can search directly for pending grants awaiting their decision across
a project, folder, or organization:
```bash
gcloud pam grants search \
--caller-relationship=can-approve \
--location=global \
--project=PROJECT_ID
```
*(Or pass `--folder=FOLDER_ID`, `--organization=ORGANIZATION_ID` matching the
target resource hierarchy).*
You can also list all grants for a specific entitlement if the entitlement ID is
already known:
```bash
gcloud pam grants list \
--entitlement=ENTITLEMENT_ID \
--location=global \
--project=PROJECT_ID
```
*(Note: Read-only search/list operations run autonomously without user prompt).*
### Step 2: Approve Pending Grant {#step-2}
When the user asks to approve a pending PAM grant:
1. Verify grant existence and state using `gcloud pam grants describe` or
`search`.
2. Prompt the user to provide a justification string for the approval.
3. Prompt the user for explicit approval under Plan-Validate-Execute rules:
*"You are about to approve PAM Grant `GRANT_ID` under entitlement
`ENTITLEMENT_ID` with reason: 'USER_PROVIDED_REASON'. Do you approve? (Yes/No)"*
4. Execute approval:
```bash
gcloud pam grants approve GRANT_ID \
--entitlement=ENTITLEMENT_ID \
--location=global \
--project=PROJECT_ID \
--reason="USER_PROVIDED_REASON"
```
### Step 3: Deny Pending Grant {#step-3}
When the user asks to deny or reject a pending PAM grant:
1. Verify grant existence and state using `gcloud pam grants describe` or
`search`.
2. Prompt the user to provide a justification string for the denial.
3. Prompt the user for explicit approval under Plan-Validate-Execute rules:
*"You are about to deny PAM Grant `GRANT_ID` under entitlement
`ENTITLEMENT_ID` with reason: 'USER_PROVIDED_REASON'. Do you approve? (Yes/No)"*
4. Execute denial:
```bash
gcloud pam grants deny GRANT_ID \
--entitlement=ENTITLEMENT_ID \
--location=global \
--project=PROJECT_ID \
--reason="USER_PROVIDED_REASON"
```
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:iam-helper-for-privileged-access-management)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:iam-helper-for-privileged-access-management)`
in the `User-Agent` header. If a `User-Agent` header is already specified,
append this string to the end of it rather than overwriting existing
`User-Agent` data — the collection pipeline parses the
`agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:iam-helper-for-privileged-access-management)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
requester.md 5.7 KB
# Mode 1: Interactive Access Elevation (Requester Workflow)
Follow these steps when the user requests temporary access elevation.
*(Rule: Throughout this playbook, select the resource scope flag corresponding
to where the target entitlement is defined: pass `--project=PROJECT_ID`,
`--folder=FOLDER_ID`, or `--organization=ORGANIZATION_ID`).*
## Table of Contents
* [Prerequisites & Permissions](#prerequisites)
* [Step 1: Collect & Validate Core Inputs](#step-1)
* [Step 2: Search Existing PAM Entitlements Along the Hierarchy](#step-2)
* [Step 3: Request Grant](#step-3)
* [Step 4: Handle Status & Termination](#step-4)
### Prerequisites & Permissions {#prerequisites}
* **Requester Eligibility:** To become a requester, the user simply must be
added to the `eligibleUsers` list in the entitlement. No explicit IAM roles
are required.
* **Discover Eligible Entitlements:** Requesters can discover their eligible
entitlements using `gcloud pam entitlements search --caller-access-type=grant-requester` without needing the
`roles/privilegedaccessmanager.viewer` role.
* **Broad Search & Role Inspection:** Searching all entitlements across scopes
(`list`/`describe`) requires `roles/privilegedaccessmanager.viewer`, and
inspecting role definitions (`gcloud iam roles describe`) requires
`roles/iam.roleViewer`.
### Step 1: Collect & Validate Core Inputs {#step-1}
Validate or ask the user for these four parameters:
* **Principal Email:** The Identity requesting access (e.g.,
`user:user@example.com`).
* **Permission Name:** The required IAM permission (e.g.,
`compute.instances.start`).
* **Requested Duration:** Default to `3600s` (60 mins) if unspecified.
* **Target Resource:** Accept short names (like `my-project`) from the user and
format them as fully qualified URIs internally (e.g.,
`//cloudresourcemanager.googleapis.com/projects/my-project`).
### Step 2: Search Existing PAM Entitlements Along the Hierarchy {#step-2}
Check for active entitlements satisfying the request across the target resource and its ancestor hierarchy (Project, ancestor Folders, and Organization).
> [!IMPORTANT]
> A single `gcloud pam entitlements search` command only queries the exact scope specified and does **not** automatically traverse parent folders or organizations. Because entitlements granting access to a project can be defined at ancestor folder or organization levels, use the helper script to search across the entire hierarchy.
Run the hierarchy search script:
```bash
bash scripts/search_eligible_entitlements.sh --project=PROJECT_ID
```
*(Or pass `--folder=FOLDER_ID` or `--organization=ORGANIZATION_ID` based on the target resource scope).*
#### Fallback (Direct Bash Command)
If executing without local script access, search across the project and its ancestor hierarchy using:
```bash
project="PROJECT_ID"
echo "=== Searching Project Scope ==="
gcloud pam entitlements search --caller-access-type=grant-requester \
--location=global --project="$project" --format=json
echo "=== Searching Ancestor Folders & Organization ==="
while read -r id type; do
if [[ "$type" == "folder" ]]; then
gcloud pam entitlements search --caller-access-type=grant-requester \
--location=global --folder="$id" --format=json
elif [[ "$type" == "organization" ]]; then
gcloud pam entitlements search --caller-access-type=grant-requester \
--location=global --organization="$id" --format=json
fi
done < <(gcloud projects get-ancestors "$project" --format="value(id,type)" 2>/dev/null || true)
```
Extract the `roleBindings` from the search results to verify if any returned entitlement grants the needed permission or role.
* **Match Found:** If an entitlement grants the required permission, store its `ENTITLEMENT_ID` and the scope level where it was found (Project, Folder, or Organization). **Rule:** If multiple eligible entitlements are found across the hierarchy, prefer the least scoped entitlement (e.g., prefer Project over Folder, and Folder over Organization). Proceed to Step 3.
* **No Match:** Abort and inform the user that no eligible entitlement exists for their request.
--------------------------------------------------------------------------------
### Step 3: Request Grant {#step-3}
Request a temporary grant using `gcloud pam grants create`:
Ensure the `--requested-duration` flag matches the exact timeframe specified by
the user (e.g., if the user requests elevation for `2 hours`, pass exactly
`--requested-duration=7200s`). If the user omitted specifying a custom
timeframe, use the `60 mins` (`3600s`) default.
Pass the scope flag matching where the entitlement is defined (`--project`,
`--folder`, or `--organization`):
```bash
# Example using a project-level entitlement:
gcloud pam grants create \
--entitlement=ENTITLEMENT_ID \
--location=global \
--requested-duration=DURATION \
--justification="Automated temporary access request" \
--project=PROJECT_ID
```
*(Note: The scope flag `--project`, `--folder`, or `--organization` must match
where the entitlement is defined. To narrow an organization- or folder-level
entitlement to a child resource via `--requested-resources=projects/PROJECT_ID`,
use `gcloud beta pam grants create`, as `--requested-resources` is only
available
in the `beta` track).*
### Step 4: Handle Status & Termination {#step-4}
Verify state in response:
* **`APPROVAL_AWAITED`:** Notify: "The grant request (`GRANT_ID`) is raised.
Access will be active after approval." Terminate immediately.
* **`SCHEDULED` or `ACTIVATING`:** The grant is approved but provisioning is pending. Wait ~30 seconds and retry checking the state 2-3 times.
* **`ACTIVE`:** Confirm activation and proceed. Do not revoke the grant upon
completing tasks; allow automatic expiration.
list_entitlements_hierarchy.sh 2.9 KB
#!/bin/bash
#
# Lists all PAM entitlements defined across the resource hierarchy (project,
# ancestor folders, and organization).
#
# Usage:
# ./list_entitlements_hierarchy.sh --project=PROJECT_ID
# ./list_entitlements_hierarchy.sh --folder=FOLDER_ID
# ./list_entitlements_hierarchy.sh --organization=ORGANIZATION_ID
#
set -euo pipefail
LOCATION="global"
PROJECT_ID=""
FOLDER_ID=""
ORG_ID=""
while [[ $# -gt 0 ]]; do
case "$1" in
--project=*)
PROJECT_ID="${1#*=}"
shift
;;
--project|-p)
PROJECT_ID="$2"
shift 2
;;
--folder=*)
FOLDER_ID="${1#*=}"
shift
;;
--folder|-f)
FOLDER_ID="$2"
shift 2
;;
--organization=*)
ORG_ID="${1#*=}"
shift
;;
--organization|-o)
ORG_ID="$2"
shift 2
;;
--location=*)
LOCATION="${1#*=}"
shift
;;
--location|-l)
LOCATION="$2"
shift 2
;;
*)
echo "Unknown argument: $1" >&2
shift
;;
esac
done
list_scope() {
local scope_flag="$1"
local scope_val="$2"
gcloud pam entitlements list \
--location="$LOCATION" \
"$scope_flag=$scope_val" \
--format=json 2>/dev/null || true
}
if [[ -n "$PROJECT_ID" ]]; then
echo "=== Listing Project Scope: $PROJECT_ID ===" >&2
list_scope "--project" "$PROJECT_ID"
echo "=== Listing Ancestor Hierarchy for Project: $PROJECT_ID ===" >&2
while read -r id type; do
if [[ "$type" == "folder" && "$id" != "$PROJECT_ID" ]]; then
echo "=== Listing Folder Scope: $id ===" >&2
list_scope "--folder" "$id"
elif [[ "$type" == "organization" && "$id" != "$PROJECT_ID" ]]; then
echo "=== Listing Organization Scope: $id ===" >&2
list_scope "--organization" "$id"
fi
done < <(gcloud projects get-ancestors "$PROJECT_ID" --format="value(id,type)" 2>/dev/null || true)
elif [[ -n "$FOLDER_ID" ]]; then
echo "=== Listing Folder Scope: $FOLDER_ID ===" >&2
list_scope "--folder" "$FOLDER_ID"
current_folder="$FOLDER_ID"
while [[ -n "$current_folder" ]]; do
parent=$(gcloud resource-manager folders describe "$current_folder" --format="value(parent)" 2>/dev/null || true)
if [[ "$parent" =~ ^folders/(.+) ]]; then
current_folder="${BASH_REMATCH[1]}"
echo "=== Listing Parent Folder Scope: $current_folder ===" >&2
list_scope "--folder" "$current_folder"
elif [[ "$parent" =~ ^organizations/(.+) ]]; then
parent_org="${BASH_REMATCH[1]}"
echo "=== Listing Parent Organization Scope: $parent_org ===" >&2
list_scope "--organization" "$parent_org"
break
else
break
fi
done
elif [[ -n "$ORG_ID" ]]; then
echo "=== Listing Organization Scope: $ORG_ID ===" >&2
list_scope "--organization" "$ORG_ID"
else
echo "Error: Must specify one of --project=PROJECT_ID, --folder=FOLDER_ID, or --organization=ORGANIZATION_ID" >&2
exit 1
fi
search_eligible_entitlements.sh 3.0 KB
#!/bin/bash
#
# Searches for PAM entitlements across the resource hierarchy (project,
# ancestor folders, and organization) that the caller is eligible to request.
#
# Usage:
# ./search_eligible_entitlements.sh --project=PROJECT_ID
# ./search_eligible_entitlements.sh --folder=FOLDER_ID
# ./search_eligible_entitlements.sh --organization=ORGANIZATION_ID
#
set -euo pipefail
LOCATION="global"
PROJECT_ID=""
FOLDER_ID=""
ORG_ID=""
while [[ $# -gt 0 ]]; do
case "$1" in
--project=*)
PROJECT_ID="${1#*=}"
shift
;;
--project|-p)
PROJECT_ID="$2"
shift 2
;;
--folder=*)
FOLDER_ID="${1#*=}"
shift
;;
--folder|-f)
FOLDER_ID="$2"
shift 2
;;
--organization=*)
ORG_ID="${1#*=}"
shift
;;
--organization|-o)
ORG_ID="$2"
shift 2
;;
--location=*)
LOCATION="${1#*=}"
shift
;;
--location|-l)
LOCATION="$2"
shift 2
;;
*)
echo "Unknown argument: $1" >&2
shift
;;
esac
done
search_scope() {
local scope_flag="$1"
local scope_val="$2"
gcloud pam entitlements search \
--caller-access-type=grant-requester \
--location="$LOCATION" \
"$scope_flag=$scope_val" \
--format=json 2>/dev/null || true
}
if [[ -n "$PROJECT_ID" ]]; then
echo "=== Searching Project Scope: $PROJECT_ID ===" >&2
search_scope "--project" "$PROJECT_ID"
echo "=== Searching Ancestor Hierarchy for Project: $PROJECT_ID ===" >&2
while read -r id type; do
if [[ "$type" == "folder" && "$id" != "$PROJECT_ID" ]]; then
echo "=== Searching Folder Scope: $id ===" >&2
search_scope "--folder" "$id"
elif [[ "$type" == "organization" && "$id" != "$PROJECT_ID" ]]; then
echo "=== Searching Organization Scope: $id ===" >&2
search_scope "--organization" "$id"
fi
done < <(gcloud projects get-ancestors "$PROJECT_ID" --format="value(id,type)" 2>/dev/null || true)
elif [[ -n "$FOLDER_ID" ]]; then
echo "=== Searching Folder Scope: $FOLDER_ID ===" >&2
search_scope "--folder" "$FOLDER_ID"
current_folder="$FOLDER_ID"
while [[ -n "$current_folder" ]]; do
parent=$(gcloud resource-manager folders describe "$current_folder" --format="value(parent)" 2>/dev/null || true)
if [[ "$parent" =~ ^folders/(.+) ]]; then
current_folder="${BASH_REMATCH[1]}"
echo "=== Searching Parent Folder Scope: $current_folder ===" >&2
search_scope "--folder" "$current_folder"
elif [[ "$parent" =~ ^organizations/(.+) ]]; then
parent_org="${BASH_REMATCH[1]}"
echo "=== Searching Parent Organization Scope: $parent_org ===" >&2
search_scope "--organization" "$parent_org"
break
else
break
fi
done
elif [[ -n "$ORG_ID" ]]; then
echo "=== Searching Organization Scope: $ORG_ID ===" >&2
search_scope "--organization" "$ORG_ID"
else
echo "Error: Must specify one of --project=PROJECT_ID, --folder=FOLDER_ID, or --organization=ORGANIZATION_ID" >&2
exit 1
fi
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE