Cloud Security

Service Account Security: Managing Non-Human Identities in Cloud Environments

Non-human identities can be numerous and hard to track. Learn how to secure service accounts, API keys, and machine identities across AWS, Azure, and GCP to reduce credential exposure and cloud access risk.

By InventiveHQ Team

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.

How a leaked static credential can lead to unauthorized access, and how controls reduce the risk A static credential leaks from CI/CD or config. If it remains valid, has broad permissions, and goes unmonitored, an attacker may misuse it. Keyless authentication avoids storing a long-lived key, but issued tokens can still be stolen and misused until expiry or revocation. The static-credential kill chain A leaked key can enable unauthorized access. These controls reduce exposure and impact. Key leaks CI/CD, image, config, chat log Never expires old key still valid Overprivileged broad perms from dev days No baseline machine use unmonitored Misuse standing access attacker Keyless auth IAM roles / managed identity / federation avoids stored keys Least privilege scoped policies, JIT access limits impact Rotation + vault risk-based schedule, no secrets in code limits key reuse Baseline + alert GuardDuty, Sentinel, Security Command Ctr helps detect misuse
This chain shows one way a leaked static key can be misused. Keyless authentication avoids storing a long-lived key and limits the validity of issued credentials. Short-lived tokens can still be stolen and misused until they expire or are revoked; least privilege and monitoring remain necessary.

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:

ProviderService Account TypeKey Management
AWSIAM Users (legacy), IAM RolesAccess keys, STS tokens
AzureService Principals, Managed IdentitiesClient secrets, certificates
GCPService AccountsJSON 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 runsAvoid storingPrefer where supportedToken lifetimeWhen a static key may be needed
AWS EC2 / Lambda / ECS / EKSIAM user access keyIAM role for the compute service or workloadService and role dependent; temporaryIf the workload cannot use a role or federation; document the exception
Azure VM / Function / AKSService principal client secretManaged identity, where the workload supports itPlatform managed; verify service behaviorIf managed identity or federation is unavailable to the application
GCP GCE / GKE / Cloud RunDownloaded service account JSON keyAttached service account or Workload Identity Federation for GKEService dependent; temporaryIf the workload cannot use an attached or federated identity
GitHub Actions / GitLab CI → cloudLong-lived cloud secret in CIOIDC federation to a scoped cloud identityProvider and configuration dependentIf the pipeline or target provider cannot federate
On-prem / other cloud → cloudCopied cloud access keyWorkload identity federation with a trusted external issuerProvider and configuration dependentIf the workload cannot use a supported external issuer
Third-party SaaS (Stripe, Datadog)API key in code or configScoped API key in a secrets vault, with rotationVendor dependentWhen 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
Advertisement

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:

  1. Create new credential (both old and new work)
  2. Update applications to use new credential
  3. Verify new credential works
  4. 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

MetricTargetAlert Threshold
Unused service accountsNo identity without an owner and purposeInactive beyond its approved review window
Static keys past their approved rotation date0Any overdue key
Overprivileged accountsNo unjustified broad grantsUnexpected admin or wildcard permissions
Secrets in code0Any 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 observeLikely root causeFix
Access key past its approved rotation date still in useNo rotation automation; app may hardcode the keyMigrate to IAM role / managed identity; if impossible, automate rotation and update the consumer
AWS IAM identity with Action: "*", service:*, or broad admin accessBroad permissions granted during development without later reviewUse 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 deletedLog 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 requestCompare 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 imageNo pre-commit scanning; secret pasted into codeRotate the exposed secret immediately, add Gitleaks/TruffleHog pre-commit hooks, enable repo secret scanning
Service account calling APIs from an unexpected regionCredential theft, or a legitimate but undocumented workloadAlert via GuardDuty/Sentinel/SCC, confirm ownership, revoke and rotate if unowned
Orphaned NHI with no owner listedCreator left; no lifecycle process at creation timeAssign an accountable owner or decommission (disable, verify no breakage, then delete)
CI pipeline holds a long-lived cloud secretPipeline may predate OIDC federationWhere 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:

  1. Business justification required
  2. Security review for high-privilege accounts
  3. Least-privilege permissions assigned
  4. Expiration date set

Review:

  1. Scheduled access reviews based on risk and policy
  2. Permission right-sizing
  3. Usage verification
  4. Owner confirmation

Decommissioning:

  1. Identify dependencies
  2. Rotate consuming applications
  3. Disable (don't delete immediately)
  4. 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

  1. Inventory current NHIs and their authentication methods
  2. Prioritize high-privilege accounts for migration
  3. Implement federation for CI/CD pipelines
  4. Migrate workloads to managed/workload identity
  5. Eliminate static credentials where possible
  6. 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.

Frequently Asked Questions

What is a non-human identity (NHI)?

A non-human identity is any credential or identity object used by software rather than a person: cloud service accounts, IAM roles, API keys, OAuth client secrets, TLS certificates, and machine tokens. NHIs authenticate machine-to-machine, so they have no human to complete MFA, notice a phishing attempt, or report suspicious activity. Their numbers can grow quickly across cloud accounts and automation systems.

What is the difference between a service account and a service principal?

The terms are provider-specific and overlap, but they are not identical. AWS uses IAM users (legacy) and IAM roles; Azure uses service principals and managed identities; GCP uses service accounts. All provide a machine identity for authentication and authorization. The modern, key-free variants — AWS IAM roles, Azure managed identities, and GCP Workload Identity — are preferred over identities that require a static, downloadable credential when the workload supports them. Issued temporary credentials still need protection.

Should service accounts use MFA?

Traditional MFA does not apply because there is no human present to supply a second factor. The equivalent controls for NHIs are short-lived, auto-rotating credentials, workload identity federation instead of static keys, certificate-based authentication, and conditional access that scopes use by source network, resource tag, or time window.

How long should a service account access key live before rotation?

Prefer a role, managed identity, or workload identity federation so the workload does not store a long-lived key. If a static credential is unavoidable, assign an owner, set an expiration and rotation schedule based on the provider's guidance and your risk policy, automate rotation where supported, and revoke it immediately if exposed. Token lifetimes vary by provider and configuration; check the vendor's current guidance.

What is workload identity federation?

Workload identity federation lets a workload authenticate to a cloud provider using its existing identity from a trusted issuer — a GitHub Actions OIDC token, a Kubernetes service account, or another cloud's identity — instead of a stored secret. The provider exchanges the verified external token for a short-lived credential. This avoids storing a long-lived cloud key, but an issued token can still be misused until it expires or is revoked. Check the provider's current token-lifetime guidance.

How do we find all of our service accounts and API keys?

Start with each cloud provider's IAM inventory (AWS IAM, Azure Entra ID, GCP IAM), then add secrets manager contents, CI/CD pipeline variables, and Kubernetes secrets. Use a CSPM or dedicated NHI-discovery tool for cross-account coverage. Treat the first inventory as incomplete — new identities are created continuously, so discovery must be ongoing, not a one-time project.

Where should secrets be stored instead of in code?

Store secrets in a dedicated vault — AWS Secrets Manager, Azure Key Vault, GCP Secret Manager, or HashiCorp Vault for multi-cloud — which gives you centralized audit logging, access policies, encryption at rest, and rotation support where configured. Keep secrets out of source control with pre-commit scanners such as Gitleaks, TruffleHog, or detect-secrets, and enable repository-side secret scanning as a backstop.

How do we secure secrets in CI/CD pipelines?

Prefer OIDC federation so the pipeline can access a cloud role without a stored long-lived cloud secret — for example GitHub Actions assuming an AWS IAM role. Where a secret is unavoidable, use the platform's native store (GitHub Secrets, GitLab CI variables, Azure DevOps secret variables), scope it to a single environment, and scan pipeline logs and container images for accidental exposure.

What is a break-glass service account and how do you protect it?

A break-glass account is a highly privileged identity reserved for emergencies when normal automation fails. Protect it by storing the credential in a vault behind a documented break-glass procedure, requiring an approval workflow to retrieve it, alerting on any use, rotating it immediately after each use, and reviewing whether it is still needed on a set schedule.

Why do non-human identities create cloud security risk?

NHIs can have broad privileges, long-lived credentials, and unclear ownership. Secrets can appear in pipelines, images, config files, and chat logs. A leaked credential can give an attacker access within its permissions and validity period, so inventory, least privilege, and monitoring matter.

Service AccountsNon-Human IdentitiesCloud SecuritySecrets ManagementMachine Identity