[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6NW7RNX1T1S34PVPRXH0Q4S":3,"skill-same:01M6NW7RNX1T1S34PVPRXH0Q4S":70},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":31,"commitSha":51,"skillDirectory":52,"forksCount":13,"repositoryHtmlUrl":53,"repositoryHomepageUrl":6,"ownerHtmlUrl":54,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":55,"install":56,"resources":69},"01M6NW7RNX1T1S34PVPRXH0Q4S","aws-secrets-manager",null,"Store and rotate secrets in AWS Secrets Manager.","duc-duy-1612\u002FOnline-Delivery-Systems-Web","duc-duy-1612","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F192231384?v=4","01M6NSDKQQDKVTHZ8DZMZ1VYY6","01M6NSDKW8DDVTQHBT1HBDDJPT",0,"MIT","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Faws-secrets-manager\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"manager","aws","secrets manager","secrets","aws secrets manager","for","security","relevant","helper","scripts","scope","critical","active","main","community","agent-skills","only","devops-security","license","assessment","2026-11-10 10:12:30",false,"---\nname: aws-secrets-manager\ndescription: Store and rotate secrets in AWS Secrets Manager.\ncategory: security\nrisk: critical\nsource: https:\u002F\u002Fgithub.com\u002FBagelHole\u002FDevOps-Security-Agent-Skills\nsource_repo: BagelHole\u002FDevOps-Security-Agent-Skills\nsource_type: community\ndate_added: '2026-09-20'\nlicense: MIT\nlicense_source: https:\u002F\u002Fgithub.com\u002FBagelHole\u002FDevOps-Security-Agent-Skills\u002Fblob\u002Fmain\u002FLICENSE\ncompatibility: Requires the relevant security tooling (scanners, vault CLIs) and an\n  authorized scope for any active assessment. Docs-only; helper scripts and templates\n  not bundled.\nmetadata:\n  author: devops-skills\n  version: '1.0'\n---\n\n# AWS Secrets Manager\n\nSecurely store, manage, and rotate secrets in AWS.\n\n## When to Use This Skill\n\nUse this skill when:\n- Storing database credentials, API keys, or tokens in AWS\n- Implementing automatic credential rotation for RDS or other services\n- Replacing hardcoded secrets in application code or config files\n- Integrating secrets into ECS, EKS, or Lambda workloads\n- Meeting compliance requirements for secret management and rotation\n\n## Prerequisites\n\n- AWS account with appropriate IAM permissions\n- AWS CLI v2 installed and configured\n- IAM policy allowing `secretsmanager:*` actions (or scoped permissions)\n- For rotation: Lambda execution role and VPC access to target services\n- Python 3.9+ with `boto3` for SDK examples\n\n## Secret Creation and Management\n\n```bash\n# Create a secret with JSON structure\naws secretsmanager create-secret \\\n  --name myapp\u002Fproduction\u002Fdatabase \\\n  --description \"Production database credentials\" \\\n  --secret-string '{\"username\":\"dbadmin\",\"password\":\"S3cur3P@ssw0rd!\",\"engine\":\"postgres\",\"host\":\"db.internal.example.com\",\"port\":5432,\"dbname\":\"myapp\"}' \\\n  --tags '[{\"Key\":\"Environment\",\"Value\":\"production\"},{\"Key\":\"Team\",\"Value\":\"platform\"}]'\n\n# Create a secret with KMS encryption (custom key)\naws secretsmanager create-secret \\\n  --name myapp\u002Fproduction\u002Fapi-key \\\n  --description \"Third-party API key\" \\\n  --secret-string \"ak_live_xxxxxxxxxxxx\" \\\n  --kms-key-id alias\u002Fsecrets-key\n\n# Create a binary secret (certificates, keys)\naws secretsmanager create-secret \\\n  --name myapp\u002Fproduction\u002Ftls-cert \\\n  --secret-binary fileb:\u002F\u002Fserver.pfx\n\n# Get secret value\naws secretsmanager get-secret-value \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase \\\n  --query 'SecretString' --output text | jq .\n\n# Get a specific version\naws secretsmanager get-secret-value \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase \\\n  --version-stage AWSPREVIOUS\n\n# Update secret value\naws secretsmanager put-secret-value \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase \\\n  --secret-string '{\"username\":\"dbadmin\",\"password\":\"N3wS3cur3P@ss!\",\"engine\":\"postgres\",\"host\":\"db.internal.example.com\",\"port\":5432,\"dbname\":\"myapp\"}'\n\n# List all secrets\naws secretsmanager list-secrets \\\n  --filters Key=name,Values=myapp\u002Fproduction\n\n# Delete secret (with recovery window)\naws secretsmanager delete-secret \\\n  --secret-id myapp\u002Fproduction\u002Fold-key \\\n  --recovery-window-in-days 7\n\n# Restore a deleted secret\naws secretsmanager restore-secret \\\n  --secret-id myapp\u002Fproduction\u002Fold-key\n\n# Tag a secret\naws secretsmanager tag-resource \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase \\\n  --tags '[{\"Key\":\"RotationEnabled\",\"Value\":\"true\"}]'\n```\n\n## Automatic Rotation\n\n### Enable Rotation\n\n```bash\n# Enable rotation with an existing Lambda function\naws secretsmanager rotate-secret \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase \\\n  --rotation-lambda-arn arn:aws:lambda:us-east-1:123456789012:function:SecretsManagerRDSPostgreSQLRotation \\\n  --rotation-rules '{\"AutomaticallyAfterDays\":30,\"ScheduleExpression\":\"rate(30 days)\"}'\n\n# Trigger immediate rotation\naws secretsmanager rotate-secret \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase\n\n# Check rotation status\naws secretsmanager describe-secret \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase \\\n  --query '{RotationEnabled:RotationEnabled,RotationLambdaARN:RotationLambdaARN,RotationRules:RotationRules,LastRotatedDate:LastRotatedDate}'\n```\n\n### Lambda Rotation Function\n\n```python\n\"\"\"rotation_function.py - Custom rotation Lambda for database credentials.\"\"\"\n\nimport boto3\nimport json\nimport logging\nimport psycopg2\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\ndef lambda_handler(event, context):\n    \"\"\"Secrets Manager rotation handler.\n\n    The rotation process has four steps:\n    1. createSecret - Generate new secret value\n    2. setSecret - Apply the new secret to the target service\n    3. testSecret - Verify the new secret works\n    4. finishSecret - Mark rotation complete\n    \"\"\"\n    secret_arn = event['SecretId']\n    token = event['ClientRequestToken']\n    step = event['Step']\n\n    client = boto3.client('secretsmanager')\n\n    metadata = client.describe_secret(SecretId=secret_arn)\n    if not metadata.get('RotationEnabled'):\n        raise ValueError(f\"Secret {secret_arn} does not have rotation enabled\")\n\n    versions = metadata.get('VersionIdsToStages', {})\n    if token not in versions:\n        raise ValueError(f\"Secret version {token} has no stage for rotation\")\n\n    if step == \"createSecret\":\n        create_secret(client, secret_arn, token)\n    elif step == \"setSecret\":\n        set_secret(client, secret_arn, token)\n    elif step == \"testSecret\":\n        test_secret(client, secret_arn, token)\n    elif step == \"finishSecret\":\n        finish_secret(client, secret_arn, token)\n    else:\n        raise ValueError(f\"Invalid step: {step}\")\n\n\ndef create_secret(client, secret_arn, token):\n    \"\"\"Generate a new secret value.\"\"\"\n    current = client.get_secret_value(\n        SecretId=secret_arn, VersionStage=\"AWSCURRENT\"\n    )\n    current_dict = json.loads(current['SecretString'])\n\n    new_password = client.get_random_password(\n        PasswordLength=32,\n        ExcludeCharacters='\u002F@\"\\\\',\n        RequireEachIncludedType=True,\n    )['RandomPassword']\n\n    current_dict['password'] = new_password\n    client.put_secret_value(\n        SecretId=secret_arn,\n        ClientRequestToken=token,\n        SecretString=json.dumps(current_dict),\n        VersionStages=['AWSPENDING'],\n    )\n    logger.info(f\"createSecret: New secret version created for {secret_arn}\")\n\n\ndef set_secret(client, secret_arn, token):\n    \"\"\"Apply the new secret to the target database.\"\"\"\n    pending = client.get_secret_value(\n        SecretId=secret_arn, VersionId=token, VersionStage=\"AWSPENDING\"\n    )\n    pending_dict = json.loads(pending['SecretString'])\n\n    current = client.get_secret_value(\n        SecretId=secret_arn, VersionStage=\"AWSCURRENT\"\n    )\n    current_dict = json.loads(current['SecretString'])\n\n    conn = psycopg2.connect(\n        host=current_dict['host'],\n        port=current_dict.get('port', 5432),\n        user=current_dict['username'],\n        password=current_dict['password'],\n        dbname=current_dict.get('dbname', 'postgres'),\n    )\n    conn.autocommit = True\n    with conn.cursor() as cur:\n        cur.execute(\n            \"ALTER USER %s WITH PASSWORD %s\",\n            (pending_dict['username'], pending_dict['password']),\n        )\n    conn.close()\n    logger.info(f\"setSecret: Password updated in database for {secret_arn}\")\n\n\ndef test_secret(client, secret_arn, token):\n    \"\"\"Verify the new secret works.\"\"\"\n    pending = client.get_secret_value(\n        SecretId=secret_arn, VersionId=token, VersionStage=\"AWSPENDING\"\n    )\n    pending_dict = json.loads(pending['SecretString'])\n\n    conn = psycopg2.connect(\n        host=pending_dict['host'],\n        port=pending_dict.get('port', 5432),\n        user=pending_dict['username'],\n        password=pending_dict['password'],\n        dbname=pending_dict.get('dbname', 'postgres'),\n    )\n    conn.close()\n    logger.info(f\"testSecret: New credentials verified for {secret_arn}\")\n\n\ndef finish_secret(client, secret_arn, token):\n    \"\"\"Finalize the rotation by updating version stages.\"\"\"\n    metadata = client.describe_secret(SecretId=secret_arn)\n    versions = metadata.get('VersionIdsToStages', {})\n\n    current_version = None\n    for version_id, stages in versions.items():\n        if \"AWSCURRENT\" in stages:\n            if version_id == token:\n                logger.info(\"finishSecret: Version already marked AWSCURRENT\")\n                return\n            current_version = version_id\n            break\n\n    client.update_secret_version_stage(\n        SecretId=secret_arn,\n        VersionStage=\"AWSCURRENT\",\n        MoveToVersionId=token,\n        RemoveFromVersionId=current_version,\n    )\n    logger.info(f\"finishSecret: Rotation complete for {secret_arn}\")\n```\n\n### Rotation Lambda Terraform\n\n```hcl\nresource \"aws_lambda_function\" \"rotation\" {\n  filename         = \"rotation_function.zip\"\n  function_name    = \"secrets-rotation-postgresql\"\n  role             = aws_iam_role.rotation.arn\n  handler          = \"rotation_function.lambda_handler\"\n  runtime          = \"python3.11\"\n  timeout          = 60\n\n  vpc_config {\n    subnet_ids         = var.private_subnet_ids\n    security_group_ids = [aws_security_group.rotation.id]\n  }\n\n  environment {\n    variables = {\n      SECRETS_MANAGER_ENDPOINT = \"https:\u002F\u002Fsecretsmanager.${var.region}.amazonaws.com\"\n    }\n  }\n}\n\nresource \"aws_lambda_permission\" \"secrets_manager\" {\n  action        = \"lambda:InvokeFunction\"\n  function_name = aws_lambda_function.rotation.function_name\n  principal     = \"secretsmanager.amazonaws.com\"\n  statement_id  = \"AllowSecretsManager\"\n}\n\nresource \"aws_secretsmanager_secret_rotation\" \"db\" {\n  secret_id           = aws_secretsmanager_secret.db.id\n  rotation_lambda_arn = aws_lambda_function.rotation.arn\n  rotation_rules {\n    automatically_after_days = 30\n  }\n}\n```\n\n## Application Integration\n\n### Python SDK\n\n```python\nimport boto3\nimport json\nfrom functools import lru_cache\n\ndef get_secret(secret_name: str, region: str = \"us-east-1\") -> dict:\n    \"\"\"Retrieve and parse a secret from AWS Secrets Manager.\"\"\"\n    client = boto3.client(\"secretsmanager\", region_name=region)\n    response = client.get_secret_value(SecretId=secret_name)\n    if \"SecretString\" in response:\n        return json.loads(response[\"SecretString\"])\n    else:\n        import base64\n        return base64.b64decode(response[\"SecretBinary\"])\n\n@lru_cache(maxsize=32)\ndef get_cached_secret(secret_name: str) -> dict:\n    \"\"\"Cached secret retrieval. Clear cache on rotation events.\"\"\"\n    return get_secret(secret_name)\n\n# Usage\ncreds = get_secret(\"myapp\u002Fproduction\u002Fdatabase\")\nconnection_string = (\n    f\"postgresql:\u002F\u002F{creds['username']}:{creds['password']}\"\n    f\"@{creds['host']}:{creds['port']}\u002F{creds['dbname']}\"\n)\n```\n\n### ECS Task Definition\n\n```json\n{\n  \"containerDefinitions\": [\n    {\n      \"name\": \"myapp\",\n      \"image\": \"ghcr.io\u002Facme\u002Fmyapp:v1.0.0\",\n      \"secrets\": [\n        {\n          \"name\": \"DB_USERNAME\",\n          \"valueFrom\": \"arn:aws:secretsmanager:us-east-1:123456789:secret:myapp\u002Fproduction\u002Fdatabase:username::\"\n        },\n        {\n          \"name\": \"DB_PASSWORD\",\n          \"valueFrom\": \"arn:aws:secretsmanager:us-east-1:123456789:secret:myapp\u002Fproduction\u002Fdatabase:password::\"\n        },\n        {\n          \"name\": \"API_KEY\",\n          \"valueFrom\": \"arn:aws:secretsmanager:us-east-1:123456789:secret:myapp\u002Fproduction\u002Fapi-key\"\n        }\n      ]\n    }\n  ],\n  \"executionRoleArn\": \"arn:aws:iam::123456789:role\u002FecsTaskExecutionRole\"\n}\n```\n\n### EKS with External Secrets Operator\n\n```yaml\napiVersion: external-secrets.io\u002Fv1beta1\nkind: SecretStore\nmetadata:\n  name: aws-secrets-manager\n  namespace: production\nspec:\n  provider:\n    aws:\n      service: SecretsManager\n      region: us-east-1\n      auth:\n        jwt:\n          serviceAccountRef:\n            name: external-secrets-sa\n---\napiVersion: external-secrets.io\u002Fv1beta1\nkind: ExternalSecret\nmetadata:\n  name: db-credentials\n  namespace: production\nspec:\n  refreshInterval: 1h\n  secretStoreRef:\n    name: aws-secrets-manager\n    kind: SecretStore\n  target:\n    name: db-credentials\n    creationPolicy: Owner\n  data:\n    - secretKey: username\n      remoteRef:\n        key: myapp\u002Fproduction\u002Fdatabase\n        property: username\n    - secretKey: password\n      remoteRef:\n        key: myapp\u002Fproduction\u002Fdatabase\n        property: password\n```\n\n## Resource-Based Policy\n\n```bash\n# Restrict secret access to specific roles\naws secretsmanager put-resource-policy \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase \\\n  --resource-policy '{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n      {\n        \"Effect\": \"Allow\",\n        \"Principal\": {\n          \"AWS\": [\n            \"arn:aws:iam::123456789:role\u002Fmyapp-ecs-task-role\",\n            \"arn:aws:iam::123456789:role\u002Fmyapp-lambda-role\"\n          ]\n        },\n        \"Action\": [\n          \"secretsmanager:GetSecretValue\"\n        ],\n        \"Resource\": \"*\",\n        \"Condition\": {\n          \"StringEquals\": {\n            \"aws:RequestedRegion\": \"us-east-1\"\n          }\n        }\n      },\n      {\n        \"Effect\": \"Deny\",\n        \"Principal\": \"*\",\n        \"Action\": \"secretsmanager:GetSecretValue\",\n        \"Resource\": \"*\",\n        \"Condition\": {\n          \"StringNotEquals\": {\n            \"aws:PrincipalAccount\": \"123456789012\"\n          }\n        }\n      }\n    ]\n  }'\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `AccessDeniedException` on GetSecretValue | IAM policy missing permission | Add `secretsmanager:GetSecretValue` to the role; check resource-based policy |\n| Rotation fails with Lambda timeout | Lambda cannot reach database | Ensure Lambda is in same VPC with route to DB; check security groups |\n| Secret value is empty after rotation | createSecret step failed | Check Lambda CloudWatch logs; verify random password generation works |\n| ECS container fails to start | Secret ARN format incorrect | Use full ARN with `::` for JSON key extraction; verify secret exists |\n| Application uses old credentials after rotation | Client caching stale values | Implement cache invalidation on rotation; reduce cache TTL |\n| Rotation Lambda permission error | Missing `lambda:InvokeFunction` permission | Add `aws_lambda_permission` for secretsmanager.amazonaws.com principal |\n| KMS decrypt fails | Secret KMS key policy missing role | Add the accessing role to the KMS key policy's `kms:Decrypt` principals |\n\n## Best Practices\n\n- Enable automatic rotation with 30-day intervals minimum\n- Use resource-based policies in addition to IAM policies (defense in depth)\n- Encrypt secrets with customer-managed KMS keys (not default)\n- Implement least-privilege access (only the roles that need each secret)\n- Use secret versioning for safe rollback during rotation issues\n- Monitor secret access with CloudTrail and alert on unusual patterns\n- Structure secret names hierarchically: `{app}\u002F{env}\u002F{secret-type}`\n- Never log secret values; log only secret ARNs and access metadata\n- Test rotation in staging before enabling in production\n- Set up CloudWatch alarms for rotation failures\n\n## Related Skills\n\n- hashicorp-vault (`hashicorp-vault`) - Multi-cloud secrets\n- aws-iam (`aws-iam`) - IAM policies\n- azure-keyvault (`azure-keyvault`) - Azure secret management\n- gcp-secret-manager (`gcp-secret-manager`) - GCP secret management\n\n## Limitations\n\n- Apply guidance only within authorized scope; test destructive steps in non-production first.\n- Docs-only import: upstream scripts and templates not bundled.\n\n### Example\n\n```bash\n# Read-only first: inventory before any active step.\nwhich \u003Ctool> && \u003Ctool> --help | head -n 20\n```\n\n> Adapted from [BagelHole\u002FDevOps-Security-Agent-Skills](https:\u002F\u002Fgithub.com\u002FBagelHole\u002FDevOps-Security-Agent-Skills) (MIT); frontmatter, When to Use\u002FLimitations, and safety boundaries added for upstream compliance. Docs-only import: helper scripts and templates not bundled.\n","# AWS Secrets Manager\n\nSecurely store, manage, and rotate secrets in AWS.\n\n## When to Use This Skill\n\nUse this skill when:\n- Storing database credentials, API keys, or tokens in AWS\n- Implementing automatic credential rotation for RDS or other services\n- Replacing hardcoded secrets in application code or config files\n- Integrating secrets into ECS, EKS, or Lambda workloads\n- Meeting compliance requirements for secret management and rotation\n\n## Prerequisites\n\n- AWS account with appropriate IAM permissions\n- AWS CLI v2 installed and configured\n- IAM policy allowing `secretsmanager:*` actions (or scoped permissions)\n- For rotation: Lambda execution role and VPC access to target services\n- Python 3.9+ with `boto3` for SDK examples\n\n## Secret Creation and Management\n\n```bash\n# Create a secret with JSON structure\naws secretsmanager create-secret \\\n  --name myapp\u002Fproduction\u002Fdatabase \\\n  --description \"Production database credentials\" \\\n  --secret-string '{\"username\":\"dbadmin\",\"password\":\"S3cur3P@ssw0rd!\",\"engine\":\"postgres\",\"host\":\"db.internal.example.com\",\"port\":5432,\"dbname\":\"myapp\"}' \\\n  --tags '[{\"Key\":\"Environment\",\"Value\":\"production\"},{\"Key\":\"Team\",\"Value\":\"platform\"}]'\n\n# Create a secret with KMS encryption (custom key)\naws secretsmanager create-secret \\\n  --name myapp\u002Fproduction\u002Fapi-key \\\n  --description \"Third-party API key\" \\\n  --secret-string \"ak_live_xxxxxxxxxxxx\" \\\n  --kms-key-id alias\u002Fsecrets-key\n\n# Create a binary secret (certificates, keys)\naws secretsmanager create-secret \\\n  --name myapp\u002Fproduction\u002Ftls-cert \\\n  --secret-binary fileb:\u002F\u002Fserver.pfx\n\n# Get secret value\naws secretsmanager get-secret-value \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase \\\n  --query 'SecretString' --output text | jq .\n\n# Get a specific version\naws secretsmanager get-secret-value \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase \\\n  --version-stage AWSPREVIOUS\n\n# Update secret value\naws secretsmanager put-secret-value \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase \\\n  --secret-string '{\"username\":\"dbadmin\",\"password\":\"N3wS3cur3P@ss!\",\"engine\":\"postgres\",\"host\":\"db.internal.example.com\",\"port\":5432,\"dbname\":\"myapp\"}'\n\n# List all secrets\naws secretsmanager list-secrets \\\n  --filters Key=name,Values=myapp\u002Fproduction\n\n# Delete secret (with recovery window)\naws secretsmanager delete-secret \\\n  --secret-id myapp\u002Fproduction\u002Fold-key \\\n  --recovery-window-in-days 7\n\n# Restore a deleted secret\naws secretsmanager restore-secret \\\n  --secret-id myapp\u002Fproduction\u002Fold-key\n\n# Tag a secret\naws secretsmanager tag-resource \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase \\\n  --tags '[{\"Key\":\"RotationEnabled\",\"Value\":\"true\"}]'\n```\n\n## Automatic Rotation\n\n### Enable Rotation\n\n```bash\n# Enable rotation with an existing Lambda function\naws secretsmanager rotate-secret \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase \\\n  --rotation-lambda-arn arn:aws:lambda:us-east-1:123456789012:function:SecretsManagerRDSPostgreSQLRotation \\\n  --rotation-rules '{\"AutomaticallyAfterDays\":30,\"ScheduleExpression\":\"rate(30 days)\"}'\n\n# Trigger immediate rotation\naws secretsmanager rotate-secret \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase\n\n# Check rotation status\naws secretsmanager describe-secret \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase \\\n  --query '{RotationEnabled:RotationEnabled,RotationLambdaARN:RotationLambdaARN,RotationRules:RotationRules,LastRotatedDate:LastRotatedDate}'\n```\n\n### Lambda Rotation Function\n\n```python\n\"\"\"rotation_function.py - Custom rotation Lambda for database credentials.\"\"\"\n\nimport boto3\nimport json\nimport logging\nimport psycopg2\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\ndef lambda_handler(event, context):\n    \"\"\"Secrets Manager rotation handler.\n\n    The rotation process has four steps:\n    1. createSecret - Generate new secret value\n    2. setSecret - Apply the new secret to the target service\n    3. testSecret - Verify the new secret works\n    4. finishSecret - Mark rotation complete\n    \"\"\"\n    secret_arn = event['SecretId']\n    token = event['ClientRequestToken']\n    step = event['Step']\n\n    client = boto3.client('secretsmanager')\n\n    metadata = client.describe_secret(SecretId=secret_arn)\n    if not metadata.get('RotationEnabled'):\n        raise ValueError(f\"Secret {secret_arn} does not have rotation enabled\")\n\n    versions = metadata.get('VersionIdsToStages', {})\n    if token not in versions:\n        raise ValueError(f\"Secret version {token} has no stage for rotation\")\n\n    if step == \"createSecret\":\n        create_secret(client, secret_arn, token)\n    elif step == \"setSecret\":\n        set_secret(client, secret_arn, token)\n    elif step == \"testSecret\":\n        test_secret(client, secret_arn, token)\n    elif step == \"finishSecret\":\n        finish_secret(client, secret_arn, token)\n    else:\n        raise ValueError(f\"Invalid step: {step}\")\n\n\ndef create_secret(client, secret_arn, token):\n    \"\"\"Generate a new secret value.\"\"\"\n    current = client.get_secret_value(\n        SecretId=secret_arn, VersionStage=\"AWSCURRENT\"\n    )\n    current_dict = json.loads(current['SecretString'])\n\n    new_password = client.get_random_password(\n        PasswordLength=32,\n        ExcludeCharacters='\u002F@\"\\\\',\n        RequireEachIncludedType=True,\n    )['RandomPassword']\n\n    current_dict['password'] = new_password\n    client.put_secret_value(\n        SecretId=secret_arn,\n        ClientRequestToken=token,\n        SecretString=json.dumps(current_dict),\n        VersionStages=['AWSPENDING'],\n    )\n    logger.info(f\"createSecret: New secret version created for {secret_arn}\")\n\n\ndef set_secret(client, secret_arn, token):\n    \"\"\"Apply the new secret to the target database.\"\"\"\n    pending = client.get_secret_value(\n        SecretId=secret_arn, VersionId=token, VersionStage=\"AWSPENDING\"\n    )\n    pending_dict = json.loads(pending['SecretString'])\n\n    current = client.get_secret_value(\n        SecretId=secret_arn, VersionStage=\"AWSCURRENT\"\n    )\n    current_dict = json.loads(current['SecretString'])\n\n    conn = psycopg2.connect(\n        host=current_dict['host'],\n        port=current_dict.get('port', 5432),\n        user=current_dict['username'],\n        password=current_dict['password'],\n        dbname=current_dict.get('dbname', 'postgres'),\n    )\n    conn.autocommit = True\n    with conn.cursor() as cur:\n        cur.execute(\n            \"ALTER USER %s WITH PASSWORD %s\",\n            (pending_dict['username'], pending_dict['password']),\n        )\n    conn.close()\n    logger.info(f\"setSecret: Password updated in database for {secret_arn}\")\n\n\ndef test_secret(client, secret_arn, token):\n    \"\"\"Verify the new secret works.\"\"\"\n    pending = client.get_secret_value(\n        SecretId=secret_arn, VersionId=token, VersionStage=\"AWSPENDING\"\n    )\n    pending_dict = json.loads(pending['SecretString'])\n\n    conn = psycopg2.connect(\n        host=pending_dict['host'],\n        port=pending_dict.get('port', 5432),\n        user=pending_dict['username'],\n        password=pending_dict['password'],\n        dbname=pending_dict.get('dbname', 'postgres'),\n    )\n    conn.close()\n    logger.info(f\"testSecret: New credentials verified for {secret_arn}\")\n\n\ndef finish_secret(client, secret_arn, token):\n    \"\"\"Finalize the rotation by updating version stages.\"\"\"\n    metadata = client.describe_secret(SecretId=secret_arn)\n    versions = metadata.get('VersionIdsToStages', {})\n\n    current_version = None\n    for version_id, stages in versions.items():\n        if \"AWSCURRENT\" in stages:\n            if version_id == token:\n                logger.info(\"finishSecret: Version already marked AWSCURRENT\")\n                return\n            current_version = version_id\n            break\n\n    client.update_secret_version_stage(\n        SecretId=secret_arn,\n        VersionStage=\"AWSCURRENT\",\n        MoveToVersionId=token,\n        RemoveFromVersionId=current_version,\n    )\n    logger.info(f\"finishSecret: Rotation complete for {secret_arn}\")\n```\n\n### Rotation Lambda Terraform\n\n```hcl\nresource \"aws_lambda_function\" \"rotation\" {\n  filename         = \"rotation_function.zip\"\n  function_name    = \"secrets-rotation-postgresql\"\n  role             = aws_iam_role.rotation.arn\n  handler          = \"rotation_function.lambda_handler\"\n  runtime          = \"python3.11\"\n  timeout          = 60\n\n  vpc_config {\n    subnet_ids         = var.private_subnet_ids\n    security_group_ids = [aws_security_group.rotation.id]\n  }\n\n  environment {\n    variables = {\n      SECRETS_MANAGER_ENDPOINT = \"https:\u002F\u002Fsecretsmanager.${var.region}.amazonaws.com\"\n    }\n  }\n}\n\nresource \"aws_lambda_permission\" \"secrets_manager\" {\n  action        = \"lambda:InvokeFunction\"\n  function_name = aws_lambda_function.rotation.function_name\n  principal     = \"secretsmanager.amazonaws.com\"\n  statement_id  = \"AllowSecretsManager\"\n}\n\nresource \"aws_secretsmanager_secret_rotation\" \"db\" {\n  secret_id           = aws_secretsmanager_secret.db.id\n  rotation_lambda_arn = aws_lambda_function.rotation.arn\n  rotation_rules {\n    automatically_after_days = 30\n  }\n}\n```\n\n## Application Integration\n\n### Python SDK\n\n```python\nimport boto3\nimport json\nfrom functools import lru_cache\n\ndef get_secret(secret_name: str, region: str = \"us-east-1\") -> dict:\n    \"\"\"Retrieve and parse a secret from AWS Secrets Manager.\"\"\"\n    client = boto3.client(\"secretsmanager\", region_name=region)\n    response = client.get_secret_value(SecretId=secret_name)\n    if \"SecretString\" in response:\n        return json.loads(response[\"SecretString\"])\n    else:\n        import base64\n        return base64.b64decode(response[\"SecretBinary\"])\n\n@lru_cache(maxsize=32)\ndef get_cached_secret(secret_name: str) -> dict:\n    \"\"\"Cached secret retrieval. Clear cache on rotation events.\"\"\"\n    return get_secret(secret_name)\n\n# Usage\ncreds = get_secret(\"myapp\u002Fproduction\u002Fdatabase\")\nconnection_string = (\n    f\"postgresql:\u002F\u002F{creds['username']}:{creds['password']}\"\n    f\"@{creds['host']}:{creds['port']}\u002F{creds['dbname']}\"\n)\n```\n\n### ECS Task Definition\n\n```json\n{\n  \"containerDefinitions\": [\n    {\n      \"name\": \"myapp\",\n      \"image\": \"ghcr.io\u002Facme\u002Fmyapp:v1.0.0\",\n      \"secrets\": [\n        {\n          \"name\": \"DB_USERNAME\",\n          \"valueFrom\": \"arn:aws:secretsmanager:us-east-1:123456789:secret:myapp\u002Fproduction\u002Fdatabase:username::\"\n        },\n        {\n          \"name\": \"DB_PASSWORD\",\n          \"valueFrom\": \"arn:aws:secretsmanager:us-east-1:123456789:secret:myapp\u002Fproduction\u002Fdatabase:password::\"\n        },\n        {\n          \"name\": \"API_KEY\",\n          \"valueFrom\": \"arn:aws:secretsmanager:us-east-1:123456789:secret:myapp\u002Fproduction\u002Fapi-key\"\n        }\n      ]\n    }\n  ],\n  \"executionRoleArn\": \"arn:aws:iam::123456789:role\u002FecsTaskExecutionRole\"\n}\n```\n\n### EKS with External Secrets Operator\n\n```yaml\napiVersion: external-secrets.io\u002Fv1beta1\nkind: SecretStore\nmetadata:\n  name: aws-secrets-manager\n  namespace: production\nspec:\n  provider:\n    aws:\n      service: SecretsManager\n      region: us-east-1\n      auth:\n        jwt:\n          serviceAccountRef:\n            name: external-secrets-sa\n---\napiVersion: external-secrets.io\u002Fv1beta1\nkind: ExternalSecret\nmetadata:\n  name: db-credentials\n  namespace: production\nspec:\n  refreshInterval: 1h\n  secretStoreRef:\n    name: aws-secrets-manager\n    kind: SecretStore\n  target:\n    name: db-credentials\n    creationPolicy: Owner\n  data:\n    - secretKey: username\n      remoteRef:\n        key: myapp\u002Fproduction\u002Fdatabase\n        property: username\n    - secretKey: password\n      remoteRef:\n        key: myapp\u002Fproduction\u002Fdatabase\n        property: password\n```\n\n## Resource-Based Policy\n\n```bash\n# Restrict secret access to specific roles\naws secretsmanager put-resource-policy \\\n  --secret-id myapp\u002Fproduction\u002Fdatabase \\\n  --resource-policy '{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n      {\n        \"Effect\": \"Allow\",\n        \"Principal\": {\n          \"AWS\": [\n            \"arn:aws:iam::123456789:role\u002Fmyapp-ecs-task-role\",\n            \"arn:aws:iam::123456789:role\u002Fmyapp-lambda-role\"\n          ]\n        },\n        \"Action\": [\n          \"secretsmanager:GetSecretValue\"\n        ],\n        \"Resource\": \"*\",\n        \"Condition\": {\n          \"StringEquals\": {\n            \"aws:RequestedRegion\": \"us-east-1\"\n          }\n        }\n      },\n      {\n        \"Effect\": \"Deny\",\n        \"Principal\": \"*\",\n        \"Action\": \"secretsmanager:GetSecretValue\",\n        \"Resource\": \"*\",\n        \"Condition\": {\n          \"StringNotEquals\": {\n            \"aws:PrincipalAccount\": \"123456789012\"\n          }\n        }\n      }\n    ]\n  }'\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `AccessDeniedException` on GetSecretValue | IAM policy missing permission | Add `secretsmanager:GetSecretValue` to the role; check resource-based policy |\n| Rotation fails with Lambda timeout | Lambda cannot reach database | Ensure Lambda is in same VPC with route to DB; check security groups |\n| Secret value is empty after rotation | createSecret step failed | Check Lambda CloudWatch logs; verify random password generation works |\n| ECS container fails to start | Secret ARN format incorrect | Use full ARN with `::` for JSON key extraction; verify secret exists |\n| Application uses old credentials after rotation | Client caching stale values | Implement cache invalidation on rotation; reduce cache TTL |\n| Rotation Lambda permission error | Missing `lambda:InvokeFunction` permission | Add `aws_lambda_permission` for secretsmanager.amazonaws.com principal |\n| KMS decrypt fails | Secret KMS key policy missing role | Add the accessing role to the KMS key policy's `kms:Decrypt` principals |\n\n## Best Practices\n\n- Enable automatic rotation with 30-day intervals minimum\n- Use resource-based policies in addition to IAM policies (defense in depth)\n- Encrypt secrets with customer-managed KMS keys (not default)\n- Implement least-privilege access (only the roles that need each secret)\n- Use secret versioning for safe rollback during rotation issues\n- Monitor secret access with CloudTrail and alert on unusual patterns\n- Structure secret names hierarchically: `{app}\u002F{env}\u002F{secret-type}`\n- Never log secret values; log only secret ARNs and access metadata\n- Test rotation in staging before enabling in production\n- Set up CloudWatch alarms for rotation failures\n\n## Related Skills\n\n- hashicorp-vault (`hashicorp-vault`) - Multi-cloud secrets\n- aws-iam (`aws-iam`) - IAM policies\n- azure-keyvault (`azure-keyvault`) - Azure secret management\n- gcp-secret-manager (`gcp-secret-manager`) - GCP secret management\n\n## Limitations\n\n- Apply guidance only within authorized scope; test destructive steps in non-production first.\n- Docs-only import: upstream scripts and templates not bundled.\n\n### Example\n\n```bash\n# Read-only first: inventory before any active step.\nwhich \u003Ctool> && \u003Ctool> --help | head -n 20\n```\n\n> Adapted from [BagelHole\u002FDevOps-Security-Agent-Skills](https:\u002F\u002Fgithub.com\u002FBagelHole\u002FDevOps-Security-Agent-Skills) (MIT); frontmatter, When to Use\u002FLimitations, and safety boundaries added for upstream compliance. Docs-only import: helper scripts and templates not bundled.\n",{"name":5,"risk":29,"source":43,"license":14,"category":24,"metadata":44,"date_added":47,"description":7,"source_repo":48,"source_type":32,"compatibility":49,"license_source":50},"https:\u002F\u002Fgithub.com\u002FBagelHole\u002FDevOps-Security-Agent-Skills",{"author":45,"version":46},"devops-skills","1.0","2026-09-20","BagelHole\u002FDevOps-Security-Agent-Skills","Requires the relevant security tooling (scanners, vault CLIs) and an authorized scope for any active assessment. Docs-only; helper scripts and templates not bundled.","https:\u002F\u002Fgithub.com\u002FBagelHole\u002FDevOps-Security-Agent-Skills\u002Fblob\u002Fmain\u002FLICENSE","f3312ba749561b6159f477dbfc9313c875d40a56",".agents\u002Fskills_archive\u002Faws-secrets-manager","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612","2026-10-25 23:50:58",{"source":8,"skillName":5,"commands":57,"prompt":67,"zipAvailable":68},[58,61,64],{"tool":59,"command":60},"npx","npx skills add duc-duy-1612\u002FOnline-Delivery-Systems-Web --skill aws-secrets-manager",{"tool":62,"command":63},"bunx","bunx skills add duc-duy-1612\u002FOnline-Delivery-Systems-Web --skill aws-secrets-manager",{"tool":65,"command":66},"pnpm","pnpm dlx skills add duc-duy-1612\u002FOnline-Delivery-Systems-Web --skill aws-secrets-manager","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Faws-secrets-manager\u002FSKILL.md",true,[],[71,92,116,140,168,192],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":82,"publishedAt":38},"01M6Q0FA5FZ410Z33Z3TFQ4DBA","zero-trust","Implement zero-trust network architecture. Configure identity-based access, micro-segmentation, and continuous verification. Use when implementing modern security architectures.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fzero-trust\u002FSKILL.md",[77],{"categoryNo":78,"categoryName":79,"taxonomyType":80,"taxonomyTypeDesc":81},"01JBSEEDCAT000000000000011","运维与部署","SCENARIO","使用场景",[83,84,85,86,37,87,73,88,35,89,90,34,32,31,30,29,28,27,25,91],"ZeRO","trust","zero trust","architecture","verification","segmentation","access","configure","implementing",{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":38},"01M6Q0F1YZJW3KX5FBKEVZ8CV4","zcode-delegate","Delegate coding tasks to the Z.AI ZCode CLI only when the user explicitly requests it, while the orchestrator retains review and landing responsibility.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fzcode-delegate\u002FSKILL.md",[],[99,100,101,102,103,104,105,106,107,108,109,110,111,34,112,32,113,114,29,115],"delegate","zcode","zcode delegate","review","cli","orchestration","tasks","run","Bash","model","node","read","orchestrator","files","desktop app","app","agent-orchestration",{"skillNo":117,"name":118,"nameZh":6,"description":119,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":120,"categories":121,"keywords":122,"publishedAt":38},"01M6Q0ETK41VGNMYEXW0T00AJN","youtube-transcript","Fetch YouTube transcripts through DeepAPI or local fallback tooling and save clean text output.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-transcript\u002FSKILL.md",[],[123,124,125,126,127,128,129,36,130,131,132,133,134,32,31,135,136,137,138,139],"transcript","youtube transcript","youtube","safe","github","codex","research","https","text","fetch","tooling","clean","local","output","deepapi","youtube transcripts","blob",{"skillNo":141,"name":142,"nameZh":6,"description":143,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":144,"categories":145,"keywords":157,"publishedAt":38},"01M6Q0EPPH2PVMDW40017F8WX0","youtube-transcript-skills","Fetch YouTube video transcripts, search videos\u002Fchannels, browse channels, and extract playlists via the getyoutubetranscript.com API - free tier, no card required.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-transcript-skills\u002FSKILL.md",[146,149,152],{"categoryNo":147,"categoryName":148,"taxonomyType":80,"taxonomyTypeDesc":81},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":150,"categoryName":151,"taxonomyType":80,"taxonomyTypeDesc":81},"01JBSEEDCAT000000000000016","图像与多媒体",{"categoryNo":153,"categoryName":154,"taxonomyType":155,"taxonomyTypeDesc":156},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[123,124,125,158,126,159,127,128,36,160,161,162,163,132,164,32,31,165,166,167],"youtube transcript skills","gemini","search","api","Video","browse","api-integration","free","card","channels",{"skillNo":169,"name":170,"nameZh":6,"description":171,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":172,"categories":173,"keywords":178,"publishedAt":38},"01M6Q0EAB96PX83W5PTE8A0R8D","youtube-notetaker","Turn YouTube talks into local study notes with slides, transcripts, editable annotations, and a markdown-backed viewer.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-notetaker\u002FSKILL.md",[174,177],{"categoryNo":175,"categoryName":176,"taxonomyType":80,"taxonomyTypeDesc":81},"01JBSEEDCAT000000000000003","演示文稿",{"categoryNo":150,"categoryName":151,"taxonomyType":80,"taxonomyTypeDesc":81},[125,179,180,103,126,181,182,183,184,36,162,185,186,187,188,31,189,135,190,191],"youtube notetaker","notetaker","workflow","official","notes","code","markdown","slides","annotations","README","study","dair-academy","viewer",{"skillNo":193,"name":194,"nameZh":6,"description":195,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":196,"categories":197,"keywords":199,"publishedAt":38},"01M6Q0E55F0GW5MX48V8HXS8B5","youtube-full","Fetch YouTube transcripts, search videos, browse channels, and extract playlists via TranscriptAPI — no yt-dlp, no Google API key, works from any cloud server.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-full\u002FSKILL.md",[198],{"categoryNo":147,"categoryName":148,"taxonomyType":80,"taxonomyTypeDesc":81},[200,125,201,202,126,159,160,203,204,161,162,163,132,205,164,32,31,165,206,138],"youtube full","full","google","server","dlp","credits","automatic"]