Service account security means preferring short-lived credentials over stored static keys, scoping every non-human identity to least privilege, storing any remaining secrets in a dedicated vault, and monitoring machine identities for anomalous behavior. In practice that means preferring AWS IAM roles over access keys, Azure managed identities over service principals with client secrets, and GCP workload identity over downloaded JSON keys where supported. Non-human identities (NHIs) can proliferate across cloud accounts and automation, and their lifecycle controls differ from those for human accounts.
The risk depends on how the identity authenticates, what it can access, and whether its use is monitored. The diagram below traces how a leaked static key can lead to unauthorized access and where controls reduce that risk; a decision table maps workloads to alternatives; and a symptom-cause-fix table turns the guidance into a remediation checklist.
Unlike human identities with interactive sign-in controls, non-human identities may rely on static credentials and may retain permissions beyond what a workload needs. Review their credentials, permissions, and activity as part of routine cloud security work.
This guide covers how to secure non-human identities across cloud environments, from basic hygiene to advanced workload identity federation. These controls also support Zero Trust architecture.
The Non-Human Identity Problem
Scale and Complexity
A cloud environment can have:
- Service accounts across multiple providers and projects
- API keys and access tokens used by applications and automation
- Secrets scattered across config files, environment variables, and vaults
- Complex machine-to-machine authentication relationships
Why NHIs Are Targeted
Long-lived credentials. Some API keys and service account credentials remain valid until explicitly expired or revoked. A leaked key can remain usable if no one detects and disables it.
Overprivileged by default. Service accounts often get broad permissions "to make things work" during development, then keep them in production.
Limited visibility. Organizations track human logins but often miss anomalous service account behavior. NHIs don't have managers to report suspicious activity.
Distributed everywhere. Secrets end up in CI/CD pipelines, container images, config files, developer laptops, and chat logs—any of which can leak.
Types of Non-Human Identities
Service Accounts (Cloud Provider)
Identity objects within cloud providers for machine-to-machine authentication:
| Provider | Service Account Type | Key Management |
|---|---|---|
| AWS | IAM Users (legacy), IAM Roles | Access keys, STS tokens |
| Azure | Service Principals, Managed Identities | Client secrets, certificates |
| GCP | Service Accounts | JSON keys, workload identity |
API Keys
Long-lived tokens for API authentication:
- Third-party SaaS API keys (Stripe, Twilio, Datadog)
- Internal API authentication tokens
- Webhook secrets
OAuth Applications
Applications that authenticate via OAuth/OIDC:
- GitHub Apps
- Slack integrations
- Azure enterprise applications
Certificates and Secrets
- TLS certificates for service authentication
- Signing keys for tokens and artifacts
- Encryption keys for data protection
Which Authentication Method Should I Use?
Removing a stored static credential reduces the risk of long-lived key exposure. Use this table to choose an authentication method before generating a downloadable key. Token lifetimes and support vary by service and configuration; check each vendor's current documentation.
| Where the workload runs | Avoid storing | Prefer where supported | Token lifetime | When a static key may be needed |
|---|---|---|---|---|
| AWS EC2 / Lambda / ECS / EKS | IAM user access key | IAM role for the compute service or workload | Service and role dependent; temporary | If the workload cannot use a role or federation; document the exception |
| Azure VM / Function / AKS | Service principal client secret | Managed identity, where the workload supports it | Platform managed; verify service behavior | If managed identity or federation is unavailable to the application |
| GCP GCE / GKE / Cloud Run | Downloaded service account JSON key | Attached service account or Workload Identity Federation for GKE | Service dependent; temporary | If the workload cannot use an attached or federated identity |
| GitHub Actions / GitLab CI → cloud | Long-lived cloud secret in CI | OIDC federation to a scoped cloud identity | Provider and configuration dependent | If the pipeline or target provider cannot federate |
| On-prem / other cloud → cloud | Copied cloud access key | Workload identity federation with a trusted external issuer | Provider and configuration dependent | If the workload cannot use a supported external issuer |
| Third-party SaaS (Stripe, Datadog) | API key in code or config | Scoped API key in a secrets vault, with rotation | Vendor dependent | When the vendor requires a key; scope and monitor it |
| Which should I use? | — | Prefer a supported identity without a stored long-lived key. Give any static-key exception an owner, scope, expiration, and rotation plan. | — | — |
Securing Cloud Service Accounts
AWS: IAM Roles Over Access Keys
Anti-pattern: Creating IAM users with long-lived access keys for applications.
Better: Use IAM roles wherever possible. This example is an EC2 role trust policy; the role also needs a scoped permissions policy and an instance profile attached to the instance:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
IAM roles avoid stored long-lived access keys:
- EC2 instances assume roles via instance metadata
- Lambda functions have execution roles
- ECS/EKS use task/pod roles
- Credentials rotate automatically
When access keys are necessary:
- Set an expiration and rotation schedule based on AWS guidance and your risk policy
- Automate rotation before expiration
- Monitor for usage anomalies
- Scope permissions minimally
Azure: Managed Identities First
Anti-pattern: Creating service principals with client secrets that never rotate.
Better: Use Managed Identities:
- System-assigned: Tied to resource lifecycle, automatically deleted
- User-assigned: Reusable across resources, independent lifecycle
# Enable system-assigned managed identity on a VM
az vm identity assign --name myVM --resource-group myRG
When service principals are necessary:
- Use certificate authentication over client secrets
- Set an expiration and rotation schedule based on Microsoft guidance and your risk policy
- Implement automated rotation
- Apply conditional access policies
GCP: Workload Identity Federation
Anti-pattern: Downloading JSON service account keys for applications.
Better: Use Workload Identity:
- GKE Workload Identity: Pods authenticate as GCP service accounts without keys
- Workload Identity Federation: External workloads (AWS, Azure, GitHub) authenticate to GCP
The annotation is one part of the setup; the Kubernetes service account also needs the appropriate IAM binding and the workload must use it.
# GKE Workload Identity annotation
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-service-account
annotations:
iam.gke.io/gcp-service-account: mysa@myproject.iam.gserviceaccount.com
When keys are necessary:
- Download only when workload identity isn't possible
- Set an expiration and rotation schedule based on Google Cloud guidance and your risk policy
- Store in Secret Manager, not code
- Disable unused keys immediately
Secrets Management
Centralized Secrets Storage
Store application secrets in dedicated vaults where supported:
Cloud-native options:
- AWS Secrets Manager
- Azure Key Vault
- GCP Secret Manager
- HashiCorp Vault (multi-cloud)
Benefits:
- Centralized audit logging
- Access control and policies
- Automatic rotation support
- Encryption at rest
Secret Rotation Strategies
Automatic rotation: Configure supported secrets managers to rotate credentials on a schedule. The following AWS example illustrates a rotation request; it requires a deployed Lambda rotation function with access to the secret and the target system. The placeholder ARN does not provide a working rotation implementation:
# Illustrative AWS Secrets Manager rotation configuration; requires a working rotation Lambda
import boto3
def rotate_secret():
client = boto3.client('secretsmanager')
client.rotate_secret(
SecretId='my-database-password',
RotationLambdaARN='arn:aws:lambda:...',
RotationRules={'AutomaticallyAfterDays': 30}
)
Dual-token rotation: To reduce downtime during rotation:
- Create new credential (both old and new work)
- Update applications to use new credential
- Verify new credential works
- Delete old credential
Secret Scanning
Prevent secrets from leaking to code repositories:
Pre-commit scanning:
- Gitleaks
- TruffleHog
- detect-secrets
Repository scanning:
- GitHub secret scanning (enable and verify coverage for your repositories)
- GitLab secret detection
- Snyk Code
CI/CD scanning:
- Scan environment variables
- Check container images for embedded secrets
- Audit deployment configurations
Least Privilege for NHIs
Permission Analysis
Regularly audit NHI permissions:
AWS IAM Access Analyzer:
aws accessanalyzer create-analyzer \
--analyzer-name my-analyzer \
--type ACCOUNT
Azure access reviews:
- Review service principal permissions
- Identify unused permissions
- Recommend permission reduction
GCP IAM Recommender:
- Suggests permission reduction based on usage
- Identifies unused service accounts
- Recommends role downgrades
Just-In-Time Access
Implement dynamic credential provisioning:
- HashiCorp Vault dynamic secrets
- AWS STS temporary credentials
- Azure Managed Identity tokens
- GCP service account impersonation
Scope Limiting
Resource-based policies: Limit which resources NHIs can access:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::my-bucket/specific-prefix/*"
}
]
}
Conditional access: Require specific conditions:
- Source IP ranges
- Time-based access
- Resource tags
- Authentication method
Monitoring and Detection
Baseline Behavior
Establish normal patterns for NHI activity:
- Typical API call patterns
- Source IP addresses
- Access times
- Target resources
Anomaly Detection
Alert on deviations from baseline:
AWS CloudTrail + GuardDuty:
- Unusual API calls from service accounts
- Access from unexpected locations
If activity appears in CloudTrail after a key or identity was deleted, compare the event time with the deletion time and check for delayed log delivery, another principal, or previously issued temporary credentials. A deleted access key cannot authenticate new requests.
Azure Sentinel:
- Service principal anomalous sign-ins
- Unusual application consent grants
- Risky workload identities
GCP Security Command Center:
- Anomalous service account usage
- Key exposure notifications
- Unusual resource access
Key Metrics to Track
| Metric | Target | Alert Threshold |
|---|---|---|
| Unused service accounts | No identity without an owner and purpose | Inactive beyond its approved review window |
| Static keys past their approved rotation date | 0 | Any overdue key |
| Overprivileged accounts | No unjustified broad grants | Unexpected admin or wildcard permissions |
| Secrets in code | 0 | Any detection |
Symptom → Cause → Fix
When an NHI review turns up a red flag, map it to the underlying cause and the concrete remediation instead of reaching for a one-off patch.
| Symptom you observe | Likely root cause | Fix |
|---|---|---|
| Access key past its approved rotation date still in use | No rotation automation; app may hardcode the key | Migrate to IAM role / managed identity; if impossible, automate rotation and update the consumer |
AWS IAM identity with Action: "*", service:*, or broad admin access | Broad permissions granted during development without later review | Use IAM Access Analyzer or GCP IAM Recommender as applicable, right-size to least privilege, and add resource and condition constraints where supported |
| Activity appears in logs after an AWS access key or identity was deleted | Log delivery may be delayed, another active principal may be involved, or previously issued temporary credentials may still be valid; a deleted access key cannot authenticate a new request | Compare event and deletion times, identify the principal and credential type in logs, and revoke any remaining active credentials as appropriate |
| Secret found in a Git repo or container image | No pre-commit scanning; secret pasted into code | Rotate the exposed secret immediately, add Gitleaks/TruffleHog pre-commit hooks, enable repo secret scanning |
| Service account calling APIs from an unexpected region | Credential theft, or a legitimate but undocumented workload | Alert via GuardDuty/Sentinel/SCC, confirm ownership, revoke and rotate if unowned |
| Orphaned NHI with no owner listed | Creator left; no lifecycle process at creation time | Assign an accountable owner or decommission (disable, verify no breakage, then delete) |
| CI pipeline holds a long-lived cloud secret | Pipeline may predate OIDC federation | Where supported, replace the stored cloud secret with OIDC role assumption so the pipeline need not store a long-lived cloud key |
Governance and Lifecycle
Inventory Management
Maintain comprehensive NHI inventory:
- Owner/team assignment for each NHI
- Business justification
- Expiration/review dates
- Dependency mapping
Lifecycle Processes
Creation:
- Business justification required
- Security review for high-privilege accounts
- Least-privilege permissions assigned
- Expiration date set
Review:
- Scheduled access reviews based on risk and policy
- Permission right-sizing
- Usage verification
- Owner confirmation
Decommissioning:
- Identify dependencies
- Rotate consuming applications
- Disable (don't delete immediately)
- Delete after verification period
Ownership Model
Assign an accountable human or team to each NHI:
- Application owners for app service accounts
- Platform teams for infrastructure credentials
- Security team for break-glass accounts
- Clear escalation for orphaned identities
Workload Identity Federation
The Future: Keyless Authentication
Workload identity federation can replace stored long-lived cloud keys by establishing trust between identity providers. The resulting temporary credentials still need scoped permissions and monitoring.
GitHub Actions to AWS: First configure an AWS OIDC provider for GitHub and an IAM role with a trust policy scoped to the intended repository and workflow context, plus the permissions the job needs. The workflow or job also needs id-token: write to request an OIDC token. This excerpt belongs inside a workflow with an appropriate trigger:
permissions:
id-token: write
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::ACCOUNT:role/GitHubActionsRole
aws-region: us-east-1
Azure to GCP: Configure a GCP workload identity pool and provider to trust the Azure workload's issuer and claims, then grant the federated principal access to the intended service account. The exact issuer and attribute mapping depend on your Azure identity setup.
Benefits of Federation
- No stored long-lived cloud key for the workload
- Temporary credentials with provider- and configuration-dependent lifetimes
- Uses existing identity infrastructure
- Auditable through identity provider logs
An attacker who steals an issued token may still use it within its permissions until it expires or is revoked. Protect token delivery and workload runtimes, and check the vendor's current guidance for token lifetimes and revocation behavior.
Implementation Roadmap
- Inventory current NHIs and their authentication methods
- Prioritize high-privilege accounts for migration
- Implement federation for CI/CD pipelines
- Migrate workloads to managed/workload identity
- Eliminate static credentials where possible
- Monitor for credential usage patterns
Frequently Asked Questions
How do we verify a migration away from static keys?
Confirm the workload authenticates with its new identity, then inspect access logs for use of the old key. Revoke the old key after testing, and check again for failed requests or remaining consumers.
What if a temporary workload token is exposed?
Treat it as a live credential. Restrict or revoke access where the provider supports it, investigate use during the token's validity period, and fix the path that exposed it. Check the provider's current revocation guidance.
How should we document a static-key exception?
Record the workload, owner, required permissions, reason federation is unavailable, storage location, approved expiration and rotation schedule, and a plan to revisit the exception.
How do we validate least privilege after migration?
Compare the new identity's granted permissions with the APIs and resources the workload actually uses. Test narrower permissions in a controlled environment, then monitor for denied requests and adjust only where needed.
What should monitoring investigate first?
Start with unexpected source locations, new API actions, unusual access times, and requests to resources outside the workload's normal scope. Confirm whether the behavior belongs to a documented deployment before revoking access.
Conclusion
Non-human identities can hold privileged access and operate continuously. Their credentials and permissions need the same deliberate ownership, review, and monitoring as human access.
Start by gaining visibility into your NHI inventory. Migrate to dynamic, short-lived credentials wherever possible. Implement secrets management and rotation. Apply least privilege consistently. Monitor for anomalous behavior.
Where supported, use roles, managed identities, or federation to remove stored long-lived keys. Continue to protect issued tokens, limit permissions, and investigate unusual use.
Part of the 30 Cloud Security Tips for 2026 series.