Skip to content

Commit 78c35a5

Browse files
authored
Merge pull request #50 from SanjaySinghRajpoot/rotateSecret
feat: Script Added to rotate secrets in `.env`
2 parents 075a265 + 5406492 commit 78c35a5

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

utils/rotate_secrets.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import os
2+
import argparse
3+
4+
def rotate_secret(env_file_path: str, variables: list[str]):
5+
# Open the specified .env file in read mode
6+
with open(env_file_path, 'r') as f:
7+
env_lines = f.readlines()
8+
9+
# Iterate over each line in the .env file
10+
for i in range(len(env_lines)):
11+
env_line = env_lines[i].strip()
12+
13+
# Check if the line is not a comment and contains a variable and a value
14+
if not env_line.startswith('#') and '=' in env_line:
15+
env_var, env_val = env_line.split('=', 1)
16+
17+
# Check if the variable is in the list of variables to be rotated
18+
if env_var in variables:
19+
# Replace the value of the variable with a new random value
20+
env_val = os.urandom(16).hex() # replace with your preferred method of generating new secrets
21+
env_lines[i] = f"{env_var}={env_val}\n"
22+
23+
# Write the updated lines back to the .env file
24+
with open(env_file_path, 'w') as f:
25+
f.writelines(env_lines)
26+
27+
if __name__ == '__main__':
28+
# Define the command-line arguments
29+
parser = argparse.ArgumentParser(description='Rotate secrets in a .env file')
30+
parser.add_argument('env_file', type=str, help='Path to .env file')
31+
parser.add_argument('--variables', type=str, nargs='+', help='List of variables to rotate secrets for')
32+
33+
# Parse the command-line arguments
34+
args = parser.parse_args()
35+
36+
# Call the rotate_secret function with the specified arguments
37+
rotate_secret(args.env_file, args.variables)

0 commit comments

Comments
 (0)