CG
SkillsPerforming Service Account Credential Rotation
Start Free
Back to Skills Library
Identity & Access Management๐ŸŸก Intermediate

Performing Service Account Credential Rotation

Automate credential rotation for service accounts across Active Directory, cloud platforms, and application databases to eliminate stale secrets and reduce compromise risk.

4 min read6 code examples

Prerequisites

  • Inventory of all service accounts across AD, cloud, and applications
  • Secrets management platform (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, or CyberArk)
  • Service dependency mapping (which services use which credentials)
  • Change management process for rotation windows
  • Monitoring for service health post-rotation

Performing Service Account Credential Rotation

Overview

Service accounts are non-human identities used by applications, daemons, CI/CD pipelines, and automated processes to authenticate to systems and APIs. These accounts often have elevated privileges and their credentials (passwords, API keys, certificates, tokens) are frequently long-lived and shared across teams, making them prime targets for attackers. Credential rotation is the systematic process of replacing these secrets on a scheduled basis, propagating new credentials to all dependent systems, and verifying service continuity after rotation.

Prerequisites

  • Inventory of all service accounts across AD, cloud, and applications
  • Secrets management platform (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, or CyberArk)
  • Service dependency mapping (which services use which credentials)
  • Change management process for rotation windows
  • Monitoring for service health post-rotation

Core Concepts

Service Account Types

TypePlatformCredentialRotation Method
Active Directory Service AccountWindows/ADPasswordgMSA (automatic) or PAM-managed
AWS IAM UserAWSAccess Key/Secret KeyAWS Secrets Manager rotation Lambda
GCP Service AccountGCPJSON key fileKey rotation via IAM API
Azure Service PrincipalAzureClient secret/certificateKey Vault + rotation policy
Database Service AccountSQL/Oracle/PostgresPasswordVault dynamic secrets
API KeySaaS applicationsAPI tokenApplication-specific API

Group Managed Service Accounts (gMSA)

Windows gMSAs provide automatic password management by Active Directory:

  • AD automatically rotates the password every 30 days
  • Password is 240 bytes, cryptographically random
  • Multiple servers can use the same gMSA simultaneously
  • No administrator knows or manages the password
  • Eliminates manual rotation for Windows services

Rotation Architecture

Secrets Manager / Vault
        โ”‚
        โ”œโ”€โ”€ Rotation Trigger (schedule or on-demand)
        โ”‚
        โ”œโ”€โ”€ Generate new credential
        โ”‚
        โ”œโ”€โ”€ Update credential at source (AD, cloud IAM, database)
        โ”‚
        โ”œโ”€โ”€ Update credential in all consumers:
        โ”‚   โ”œโ”€โ”€ Application configuration
        โ”‚   โ”œโ”€โ”€ CI/CD pipeline secrets
        โ”‚   โ”œโ”€โ”€ Kubernetes secrets
        โ”‚   โ””โ”€โ”€ Other dependent services
        โ”‚
        โ”œโ”€โ”€ Verify service health
        โ”‚   โ”œโ”€โ”€ Health check endpoints
        โ”‚   โ”œโ”€โ”€ Authentication test
        โ”‚   โ””โ”€โ”€ Functional smoke test
        โ”‚
        โ””โ”€โ”€ Revoke old credential (after grace period)

Implementation Steps

Step 1: Discover and Inventory Service Accounts

Enumerate all service accounts and their dependencies:

# Active Directory: Find all service accounts
Get-ADServiceAccount -Filter * -Properties *
Get-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName,PasswordLastSet,LastLogonDate

# Find accounts with passwords older than 90 days
$threshold = (Get-Date).AddDays(-90)
Get-ADUser -Filter {PasswordLastSet -lt $threshold -and Enabled -eq $true} -Properties PasswordLastSet,ServicePrincipalName |
    Where-Object {$_.ServicePrincipalName} |
    Select-Object Name, PasswordLastSet, ServicePrincipalName

Step 2: Implement gMSA for Windows Services

# Create KDS Root Key (one-time, domain-wide)
Add-KdsRootKey -EffectiveImmediately

# Create the gMSA account
New-ADServiceAccount -Name "svc-webapp-gmsa" `
    -DNSHostName "svc-webapp-gmsa.corp.example.com" `
    -PrincipalsAllowedToRetrieveManagedPassword "WebServerGroup" `
    -KerberosEncryptionType AES128,AES256

# Install on target server
Install-ADServiceAccount -Identity "svc-webapp-gmsa"

# Test the account
Test-ADServiceAccount -Identity "svc-webapp-gmsa"

# Configure IIS Application Pool to use gMSA
# Set identity to: CORP\svc-webapp-gmsa$

Step 3: AWS Access Key Rotation with Secrets Manager

import boto3
import json

def rotate_iam_access_key(secret_arn, iam_username):
    """Rotate an IAM user's access key via Secrets Manager."""
    iam = boto3.client("iam")
    sm = boto3.client("secretsmanager")

    # Create new access key
    new_key = iam.create_access_key(UserName=iam_username)
    new_access_key = new_key["AccessKey"]["AccessKeyId"]
    new_secret_key = new_key["AccessKey"]["SecretAccessKey"]

    # Store new credentials in Secrets Manager
    sm.put_secret_value(
        SecretId=secret_arn,
        SecretString=json.dumps({
            "accessKeyId": new_access_key,
            "secretAccessKey": new_secret_key,
            "username": iam_username,
        })
    )

    # List old access keys and deactivate them
    keys = iam.list_access_keys(UserName=iam_username)
    for key in keys["AccessKeyMetadata"]:
        if key["AccessKeyId"] != new_access_key and key["Status"] == "Active":
            iam.update_access_key(
                UserName=iam_username,
                AccessKeyId=key["AccessKeyId"],
                Status="Inactive"
            )

    return {"new_key_id": new_access_key, "old_keys_deactivated": True}

Step 4: Database Credential Rotation with Vault

import hvac

def configure_vault_database_rotation(vault_url, vault_token, db_config):
    """Configure HashiCorp Vault for automatic database credential rotation."""
    client = hvac.Client(url=vault_url, token=vault_token)

    # Enable database secrets engine
    client.sys.enable_secrets_engine(
        backend_type="database",
        path="database"
    )

    # Configure database connection
    client.secrets.database.configure(
        name=db_config["name"],
        plugin_name="postgresql-database-plugin",
        connection_url=f"postgresql://{{{{username}}}}:{{{{password}}}}@"
                       f"{db_config['host']}:{db_config['port']}/{db_config['database']}",
        allowed_roles=[db_config["role_name"]],
        username=db_config["admin_user"],
        password=db_config["admin_password"],
    )

    # Create a role for dynamic credentials
    client.secrets.database.create_role(
        name=db_config["role_name"],
        db_name=db_config["name"],
        creation_statements=[
            "CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';",
            f"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO \"{{{{name}}}}\";"
        ],
        default_ttl="1h",
        max_ttl="24h",
    )

    return {"status": "configured", "role": db_config["role_name"]}

Step 5: Post-Rotation Verification

After every rotation, verify service continuity:

import requests
import time

def verify_service_health(service_endpoints, max_retries=3, delay=10):
    """Check that services are healthy after credential rotation."""
    results = []
    for endpoint in service_endpoints:
        for attempt in range(max_retries):
            try:
                response = requests.get(
                    endpoint["health_url"],
                    timeout=10,
                    headers=endpoint.get("headers", {})
                )
                healthy = response.status_code == 200
                results.append({
                    "service": endpoint["name"],
                    "status": "healthy" if healthy else f"unhealthy ({response.status_code})",
                    "attempt": attempt + 1,
                })
                if healthy:
                    break
            except requests.RequestException as e:
                results.append({
                    "service": endpoint["name"],
                    "status": f"error: {str(e)}",
                    "attempt": attempt + 1,
                })
            if attempt < max_retries - 1:
                time.sleep(delay)

    return results

Validation Checklist

  • [ ] Complete inventory of service accounts with dependency mapping
  • [ ] gMSA implemented for all eligible Windows service accounts
  • [ ] Cloud access keys rotated via secrets manager (AWS, GCP, Azure)
  • [ ] Database credentials managed via dynamic secrets (Vault) or rotation policy
  • [ ] Rotation schedule defined (30-90 days depending on risk level)
  • [ ] Post-rotation health checks automated
  • [ ] Alerting configured for rotation failures
  • [ ] Old credentials revoked after grace period
  • [ ] Rotation events logged and auditable
  • [ ] Rollback procedure documented and tested

Compliance Framework Mapping

This skill supports compliance evidence collection across multiple frameworks:

  • SOC 2: CC6.1 (Logical Access), CC6.2 (Credentials), CC6.3 (Provisioning)
  • ISO 27001: A.9.1 (Access Control), A.9.2 (User Access Management), A.9.4 (System Access Control)
  • NIST 800-53: AC-2 (Account Management), IA-2 (Identification), AC-6 (Least Privilege)
  • NIST CSF: PR.AC (Access Control)

Claw GRC Tip: When this skill is executed by a registered agent, compliance evidence is automatically captured and mapped to the relevant controls in your active frameworks.

Deploying This Skill with Claw GRC

Agent Execution

Register this skill with your Claw GRC agent for automated execution:

# Install via CLI
npx claw-grc skills add performing-service-account-credential-rotation

# Or load dynamically via MCP
grc.load_skill("performing-service-account-credential-rotation")

Audit Trail Integration

When executed through Claw GRC, every step of this skill generates tamper-evident audit records:

  • SHA-256 chain hashing ensures no step can be modified after execution
  • Evidence artifacts (configs, scan results, logs) are automatically attached to relevant controls
  • Trust score impact โ€” successful execution increases your agent's trust score

Continuous Compliance

Schedule this skill for recurring execution to maintain continuous compliance posture. Claw GRC monitors for drift and alerts when re-execution is needed.

References

  • Google Cloud Service Account Key Rotation
  • AWS Secrets Manager Rotation
  • Microsoft gMSA Documentation
  • HashiCorp Vault Database Secrets Engine

Use with Claw GRC Agents

This skill is fully compatible with Claw GRC's autonomous agent system. Deploy it to any registered agent via MCP, and every execution will be logged in the tamper-evident audit trail.

// Load this skill in your agent
npx claw-grc skills add performing-service-account-credential-rotation
// Or via MCP
grc.load_skill("performing-service-account-credential-rotation")

Tags

service-accountscredential-rotationsecrets-managementpamautomationvault

Related Skills

Identity & Access Management

Implementing HashiCorp Vault Dynamic Secrets

10mยทintermediate
Identity & Access Management

Implementing PAM for Database Access

3mยทintermediate
Identity & Access Management

Implementing Privileged Access Management with Cyberark

3mยทintermediate
Identity & Access Management

Implementing Privileged Session Monitoring

3mยทintermediate
Identity & Access Management

Implementing Scim Provisioning with Okta

4mยทintermediate
Identity & Access Management

Implementing Zero Standing Privilege with Cyberark

5mยทintermediate

Skill Details

Domain
Identity & Access Management
Difficulty
intermediate
Read Time
4 min
Code Examples
6

On This Page

OverviewPrerequisitesCore ConceptsImplementation StepsValidation ChecklistReferencesCompliance Framework MappingDeploying This Skill with Claw GRC

Deploy This Skill

Add this skill to your Claw GRC agent and start automating.

Get Started Free โ†’