๐Ÿ”’ Security

SOPS

Secrets OPerationS

An encrypted file editing tool: a Mozilla open-source tool that selectively encrypts YAML/JSON values for safe storage in Git

๐Ÿ“– Detailed Explanation

SOPS (Secrets OPerationS) is an encrypted file editing tool developed by Mozilla. Its distinguishing feature is that, in YAML, JSON, ENV, and INI files, it keeps keys in plaintext and selectively encrypts only the values. Thanks to this, the structure of an encrypted file can still be understood, which makes code review, diff, and merge conflict resolution possible.

SOPS supports a variety of key management systems (KMS). It supports cloud KMS such as AWS KMS, Google Cloud KMS, and Azure Key Vault, as well as HashiCorp Vault, age, and PGP, and multiple keys can be used at the same time. For example, you can configure it so that the development team decrypts with an age key, while production CI/CD decrypts with AWS KMS. Since having just one of the multiple keys is enough to decrypt, it is also flexible when rotating keys or when team members change.

A major advantage of SOPS is its editor integration. When you open a file with the `sops secrets.yaml` command, the editor opens with the file automatically decrypted, and when you save and close it, the file is encrypted again. Therefore, you can manage secrets with the same workflow as editing a regular file. There are also Vim and VS Code plugins, so you can edit directly in your IDE.

In GitOps environments, SOPS integrates natively with Flux and ArgoCD. Flux's kustomize-controller automatically decrypts SOPS-encrypted secret files and applies them to the cluster. ArgoCD also processes encrypted manifests through a SOPS plugin. This allows the entire infrastructure, including Kubernetes secrets, to be managed with Git.

๐Ÿ’ป Code Example

SOPS Installation and Initial Setup

# macOS ์„ค์น˜
brew install sops

# Linux ์„ค์น˜
wget https://github.com/getsops/sops/releases/download/v3.8.1/sops-v3.8.1.linux.amd64
chmod +x sops-v3.8.1.linux.amd64
sudo mv sops-v3.8.1.linux.amd64 /usr/local/bin/sops

# age ํ‚ค ์ƒ์„ฑ (๊ฐ„๋‹จํ•œ ๋กœ์ปฌ ์•”ํ˜ธํ™”์šฉ)
# age ์„ค์น˜: brew install age
age-keygen -o ~/.sops/age/keys.txt
# ์ถœ๋ ฅ ์˜ˆ: AGE-SECRET-KEY-1QFSMEH... (์ด๊ฒƒ์ด ๋น„๊ณต๊ฐœํ‚ค)
# ๊ณต๊ฐœํ‚ค: age1... (์ด๊ฒƒ์œผ๋กœ ์•”ํ˜ธํ™”)

# AWS KMS ํ‚ค ์‚ฌ์šฉ ์‹œ IAM ๊ถŒํ•œ ํ•„์š”
# aws kms create-key --description "SOPS encryption key"

.sops.yaml Configuration File (Project Root)

# .sops.yaml - ํ”„๋กœ์ ํŠธ ๋ฃจํŠธ์— ์œ„์น˜
# ๊ฒฝ๋กœ ํŒจํ„ด๋ณ„๋กœ ๋‹ค๋ฅธ ์•”ํ˜ธํ™” ํ‚ค ์ ์šฉ

creation_rules:
  # ๊ฐœ๋ฐœ ํ™˜๊ฒฝ - age ํ‚ค ์‚ฌ์šฉ
  - path_regex: secrets/development/.*\.yaml$
    age: >-
      age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p

  # ์Šคํ…Œ์ด์ง• ํ™˜๊ฒฝ - AWS KMS ์‚ฌ์šฉ
  - path_regex: secrets/staging/.*\.yaml$
    kms: arn:aws:kms:ap-northeast-2:123456789:key/abc-def-123

  # ํ”„๋กœ๋•์…˜ ํ™˜๊ฒฝ - AWS KMS + age (๋‘˜ ์ค‘ ํ•˜๋‚˜๋กœ ๋ณตํ˜ธํ™” ๊ฐ€๋Šฅ)
  - path_regex: secrets/production/.*\.yaml$
    kms: arn:aws:kms:ap-northeast-2:123456789:key/prod-key-456
    age: >-
      age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p

  # Kubernetes ์‹œํฌ๋ฆฟ - ํŠน์ • ํ‚ค๋งŒ ์•”ํ˜ธํ™”
  - path_regex: k8s/.*secrets?\.yaml$
    kms: arn:aws:kms:ap-northeast-2:123456789:key/k8s-secrets-key
    encrypted_regex: ^(data|stringData)$

  # Terraform ๋ณ€์ˆ˜ - .tfvars ํŒŒ์ผ
  - path_regex: terraform/.*\.tfvars$
    age: >-
      age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p

Encrypting and Decrypting Files

# ์ƒˆ ํŒŒ์ผ ์•”ํ˜ธํ™” (์ƒ์„ฑ๊ณผ ๋™์‹œ์—)
# .sops.yaml์˜ creation_rules๊ฐ€ ์ž๋™ ์ ์šฉ๋จ
sops secrets/production/database.yaml
# ํŽธ์ง‘๊ธฐ๊ฐ€ ์—ด๋ฆฌ๊ณ , ์ €์žฅ ํ›„ ๋‹ซ์œผ๋ฉด ์•”ํ˜ธํ™”๋จ

# ๊ธฐ์กด ํ‰๋ฌธ ํŒŒ์ผ์„ ์•”ํ˜ธํ™”
sops -e secrets.yaml > secrets.enc.yaml

# ์•”ํ˜ธํ™”๋œ ํŒŒ์ผ์„ ํ‰๋ฌธ์œผ๋กœ ๋ณตํ˜ธํ™” (stdout์œผ๋กœ ์ถœ๋ ฅ)
sops -d secrets.enc.yaml

# ์•”ํ˜ธํ™”๋œ ํŒŒ์ผ์„ ์ œ์ž๋ฆฌ์—์„œ ๋ณตํ˜ธํ™” (ํŒŒ์ผ ๋ฎ์–ด์“ฐ๊ธฐ)
sops -d -i secrets.enc.yaml

# ํŠน์ • ํ‚ค๋กœ ๋ช…์‹œ์  ์•”ํ˜ธํ™”
sops --age age1ql3z7hjy54pw3... -e secrets.yaml > secrets.enc.yaml

# AWS KMS๋กœ ์•”ํ˜ธํ™”
sops --kms arn:aws:kms:ap-northeast-2:123456789:key/my-key -e secrets.yaml

# ํŽธ์ง‘ ๋ชจ๋“œ๋กœ ์—ด๊ธฐ (๋ณตํ˜ธํ™” โ†’ ํŽธ์ง‘ โ†’ ์žฌ์•”ํ˜ธํ™”)
sops secrets.enc.yaml

# ํŠน์ • ๊ฐ’๋งŒ ์ถ”์ถœ (jq์ฒ˜๋Ÿผ)
sops -d --extract '["database"]["password"]' secrets.enc.yaml

Encrypted File Example

# secrets/production/database.yaml (์•”ํ˜ธํ™” ํ›„)
# ํ‚ค๋Š” ํ‰๋ฌธ, ๊ฐ’๋งŒ ์•”ํ˜ธํ™”๋จ
database:
    host: ENC[AES256_GCM,data:Mj3p...,iv:...,tag:...,type:str]
    port: ENC[AES256_GCM,data:NjQ=,iv:...,tag:...,type:int]
    username: ENC[AES256_GCM,data:YWRt...,iv:...,tag:...,type:str]
    password: ENC[AES256_GCM,data:c3Vw...,iv:...,tag:...,type:str]

redis:
    host: ENC[AES256_GCM,data:cmVk...,iv:...,tag:...,type:str]
    password: ENC[AES256_GCM,data:cmVk...,iv:...,tag:...,type:str]

sops:
    kms:
        - arn: arn:aws:kms:ap-northeast-2:123456789:key/prod-key-456
          created_at: "2024-01-15T10:30:00Z"
          enc: AQICAHj...
    age:
        - recipient: age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p
          enc: |
            -----BEGIN AGE ENCRYPTED FILE-----
            YWdlLWVuY3J5cHRpb24...
            -----END AGE ENCRYPTED FILE-----
    lastmodified: "2024-01-15T10:30:00Z"
    mac: ENC[AES256_GCM,data:...,tag:...,type:str]
    version: 3.8.1

Flux GitOps Integration

# flux-system/gotk-sync.yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: infrastructure
  namespace: flux-system
spec:
  interval: 10m
  path: ./infrastructure
  prune: true
  sourceRef:
    kind: GitRepository
    name: flux-system
  # SOPS ๋ณตํ˜ธํ™” ํ™œ์„ฑํ™”
  decryption:
    provider: sops
    secretRef:
      name: sops-age  # age ๋น„๊ณต๊ฐœํ‚ค๋ฅผ ๋‹ด์€ Secret

---
# SOPS age ํ‚ค๋ฅผ Kubernetes Secret์œผ๋กœ ์ €์žฅ
# kubectl create secret generic sops-age \
#   --namespace=flux-system \
#   --from-file=age.agekey=~/.sops/age/keys.txt

apiVersion: v1
kind: Secret
metadata:
  name: sops-age
  namespace: flux-system
type: Opaque
data:
  age.agekey: QUdFLVNFQ1JFVC1LRVkt...  # base64 encoded age key

Reading SOPS Files in Python

import subprocess
import yaml
import json
from pathlib import Path
from typing import Any, Optional
import os

class SOPSClient:
    """SOPS ์•”ํ˜ธํ™”๋œ ํŒŒ์ผ์„ ๋‹ค๋ฃจ๋Š” Python ํด๋ผ์ด์–ธํŠธ"""

    def __init__(self, age_key_file: Optional[str] = None):
        """
        Args:
            age_key_file: age ๋น„๊ณต๊ฐœํ‚ค ํŒŒ์ผ ๊ฒฝ๋กœ (ํ™˜๊ฒฝ๋ณ€์ˆ˜ SOPS_AGE_KEY_FILE๋กœ๋„ ์„ค์ • ๊ฐ€๋Šฅ)
        """
        if age_key_file:
            os.environ['SOPS_AGE_KEY_FILE'] = age_key_file

    def decrypt_file(self, file_path: str) -> dict:
        """SOPS ํŒŒ์ผ์„ ๋ณตํ˜ธํ™”ํ•˜์—ฌ dict๋กœ ๋ฐ˜ํ™˜"""
        result = subprocess.run(
            ['sops', '-d', file_path],
            capture_output=True,
            text=True
        )

        if result.returncode != 0:
            raise RuntimeError(f"SOPS decryption failed: {result.stderr}")

        file_ext = Path(file_path).suffix.lower()
        if file_ext in ['.yaml', '.yml']:
            return yaml.safe_load(result.stdout)
        elif file_ext == '.json':
            return json.loads(result.stdout)
        else:
            return {'content': result.stdout}

    def encrypt_data(self, data: dict, output_path: str,
                     file_type: str = 'yaml') -> None:
        """dict๋ฅผ SOPS๋กœ ์•”ํ˜ธํ™”ํ•˜์—ฌ ํŒŒ์ผ๋กœ ์ €์žฅ"""
        if file_type == 'yaml':
            content = yaml.dump(data, default_flow_style=False)
            input_type = '--input-type=yaml'
            output_type = '--output-type=yaml'
        else:
            content = json.dumps(data, indent=2)
            input_type = '--input-type=json'
            output_type = '--output-type=json'

        result = subprocess.run(
            ['sops', '-e', input_type, output_type, '/dev/stdin'],
            input=content,
            capture_output=True,
            text=True
        )

        if result.returncode != 0:
            raise RuntimeError(f"SOPS encryption failed: {result.stderr}")

        Path(output_path).write_text(result.stdout)

    def get_value(self, file_path: str, key_path: str) -> Any:
        """์•”ํ˜ธํ™”๋œ ํŒŒ์ผ์—์„œ ํŠน์ • ๊ฐ’ ์ถ”์ถœ"""
        # key_path ์˜ˆ: "database.password" ๋˜๋Š” '["database"]["password"]'
        json_path = ''.join(f'["{k}"]' for k in key_path.split('.'))

        result = subprocess.run(
            ['sops', '-d', '--extract', json_path, file_path],
            capture_output=True,
            text=True
        )

        if result.returncode != 0:
            raise RuntimeError(f"SOPS extraction failed: {result.stderr}")

        return result.stdout.strip()

    def update_value(self, file_path: str, key_path: str, value: Any) -> None:
        """์•”ํ˜ธํ™”๋œ ํŒŒ์ผ์˜ ํŠน์ • ๊ฐ’ ์—…๋ฐ์ดํŠธ"""
        # ๋ณตํ˜ธํ™”
        data = self.decrypt_file(file_path)

        # ์ค‘์ฒฉ๋œ ํ‚ค ์—…๋ฐ์ดํŠธ
        keys = key_path.split('.')
        current = data
        for key in keys[:-1]:
            current = current[key]
        current[keys[-1]] = value

        # ์žฌ์•”ํ˜ธํ™”
        file_ext = Path(file_path).suffix.lower()
        file_type = 'yaml' if file_ext in ['.yaml', '.yml'] else 'json'
        self.encrypt_data(data, file_path, file_type)


# ์‚ฌ์šฉ ์˜ˆ์‹œ
if __name__ == "__main__":
    # age ํ‚ค ํŒŒ์ผ ์ง€์ •
    sops = SOPSClient(age_key_file=os.path.expanduser("~/.sops/age/keys.txt"))

    # ์ „์ฒด ํŒŒ์ผ ๋ณตํ˜ธํ™”
    secrets = sops.decrypt_file("secrets/production/database.yaml")
    print(f"DB Host: {secrets['database']['host']}")
    print(f"DB User: {secrets['database']['username']}")

    # ํŠน์ • ๊ฐ’๋งŒ ์ถ”์ถœ
    db_password = sops.get_value(
        "secrets/production/database.yaml",
        "database.password"
    )
    print(f"DB Password: {db_password}")

    # ๊ฐ’ ์—…๋ฐ์ดํŠธ
    sops.update_value(
        "secrets/production/database.yaml",
        "database.password",
        "new_secure_password_123"
    )

๐Ÿ—ฃ๏ธ How It's Said in Practice

  • "If you encrypt secrets with SOPS, the key names remain visible, so you can code-review which values were changed in a PR."
  • "You can separate permissions by encrypting the development environment with an age key and production with AWS KMS."
  • "Flux natively supports SOPS, so you can commit secret manifests to Git as well and manage them with GitOps."
  • "If you define per-path rules in .sops.yaml, files that team members create are automatically encrypted with the right key."
  • "What are the pros and cons of SOPS encrypting only the values rather than the entire file?"
  • "Compare SOPS and Sealed Secrets, and explain which situations each is suited for."
  • "How would you handle key rotation in SOPS? Why are multiple keys used at the same time?"
  • "How would you manage permissions when integrating SOPS into a CI/CD pipeline?"

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

  • "This secret file is outside the scope of the .sops.yaml rules, so it was committed in plaintext. Please check the path."
  • "The SOPS metadata section has no age key. Developers can't decrypt locally."
  • "I set it to encrypt only the data key with encrypted_regex, but stringData needs to be added as well."
  • "For this sensitive configuration, managing it as a SOPS file is better than environment variables for tracking change history."

โš ๏ธ Cautions

  • Watch for missing .sops.yaml rules: If the path_regex in .sops.yaml does not match the file path, the file is stored in plaintext without encryption. When adding a new directory or file pattern, be sure to update .sops.yaml as well, and block plaintext secret commits with a pre-commit hook.
  • Key backup and recovery plan: If you lose an age or PGP private key, files encrypted only with that key can never be decrypted. Use a cloud KMS as the primary key and set the age key as a secondary. Key backups must be stored in a separate, secure location.
  • Beware of plaintext in Git history: Even if you encrypt a file after accidentally committing it in plaintext, the plaintext remains in the Git history. In such a case, clean up the history with git filter-branch or BFG Repo-Cleaner, and replace the exposed secrets immediately.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More