SOPS
An encrypted file editing tool: a Mozilla open-source tool that selectively encrypts YAML/JSON values for safe storage in Git
An encrypted file editing tool: a Mozilla open-source tool that selectively encrypts YAML/JSON values for safe storage in Git
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.
# 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 - ํ๋ก์ ํธ ๋ฃจํธ์ ์์น
# ๊ฒฝ๋ก ํจํด๋ณ๋ก ๋ค๋ฅธ ์ํธํ ํค ์ ์ฉ
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
# ์ ํ์ผ ์ํธํ (์์ฑ๊ณผ ๋์์)
# .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
# 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-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
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"
)
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free