如何在提交到Git时使用ansible-vault加密文件

94次阅读
没有评论

问题描述

希望在将项目中的机密文件推送到Git之前,使用ansible-vault来保护这些文件的安全性。尽管有许多关于如何部分设置此功能的建议,但他发现所有的建议都是关于如何对比这些文件的差异,而不是如何在放入文件时对它们进行加密。他注意到最初提交这些文件时,需要手动使用ansible-vault进行加密。他想知道是否有一种在提交时自动进行加密的方法。

解决方案

以下方案可能涉及版本差异,请根据你的实际情况进行调整。

方案1 – 利用 Git Hooks 实现加密与校验

可以通过使用 Git Hooks 实现在提交时自动加密与校验。这样,每当你执行提交操作时,系统会自动检查未加密的文件并加密它们。

步骤

  1. 在你的项目根目录下,找到 .git/hooks/pre-commit 文件(如果不存在,可以创建它)。
  2. 将以下脚本添加到 pre-commit 文件中:
#!/bin/sh

# Ansible Vault Secrets Git Hook
# Hook to check if an un-encrypted FILE_PATTERN file is being committed.
# Put this file in .git/hooks/pre-commit

# Define the pattern for files that need to be encrypted
FILE_PATTERN="my_secrets_file.yaml\|vars/"
ENCRYPTED_PATTERN="\$ANSIBLE_VAULT"

is_encrypted() {
  local file=$1
  if ! git show :"$file" | grep --quiet "^${ENCRYPTED_PATTERN}"; then
    echo "Located a staged file that should be encrypted:\n> ${file}\n"
    echo "Please un-stage this file. If you are adding or updating this file, please encrypt it before staging."
    echo "Alternatively, you can git checkout the latest encrypted version of the file before committing."
    echo "Remember... Only YOU Can Prevent Secret Leakage."
    exit 1
  fi
}

echo "Running pre-commit checks..."
git diff --cached --name-only | grep "${FILE_PATTERN}" | while IFS= read -r line; do
  is_encrypted "${line}"
done

这个脚本将在提交前检查是否有未加密的文件。如果发现了未加密的文件,脚本会中止提交并给出相应的提示。

方案2 – 编写加密/解密脚本

如果你希望更进一步,可以编写脚本来实现文件的自动加密和解密。以下是一个简单的脚本示例,用于批量加密和解密文件:

#!/bin/bash

# Check if the correct number of arguments is provided
if [ $# -eq 0 ]; then
  echo "This script will encrypt or decrypt all files containing secrets."
  echo "Specify 'encrypt' or 'decrypt' as an argument."
  exit 1
fi

# Define the patterns for files that need to be encrypted
files=`find . -type f -name "my_secrets_file.yaml"`
files="$files vars/*"

# Determine whether to use vault password from a file or prompt for it
password_type=--ask-vault-password
if [ -f ".vault_password" ]; then
  if [ `stat -c %a .vault_password` != "600" ]; then
    echo ".vault_password file has bad permissions; fixing this to 600"
    chmod 600 .vault_password
  fi
  password_type="--vault-password-file .vault_password"
fi

# Perform encryption or decryption based on the provided argument
if [ $1 == "encrypt" ]; then
  ansible-vault encrypt $password_type $files
  for value in $files; do
    echo $value;
  done
elif [ $1 == "decrypt" ]; then
  ansible-vault decrypt $password_type $files
  for value in $files; do
    echo $value;
  done
else
  echo "Wrong argument supplied. Run without arguments to see allowed ones."
fi

这个脚本可以根据提供的参数来批量加密或解密文件。你可以在脚本中根据需要定义文件的模式,然后使用脚本来加密或解密这些文件。

总结

通过使用 Git Hooks 和编写自定义脚本,你可以实现在提交到 Git 时自动加密文件,从而确保机密信息的安全性。根据你的实际需求,选择适合的方案并进行相应的调整。

注意: 在实际操作之前,请确保对脚本进行充分的测试,以确保其适用于你的项目和环境。

正文完