Final
Tue Jul 16 2024 16:12:45 GMT+0000 (Coordinated Universal Time)
Saved by @vchiranjeeviak #python
import os
import requests
import json
from dotenv import load_dotenv
# Load env from .env file.
load_dotenv()
'''
Step 1: Get all env variables.
'''
url_to_get_all_envs = (
f"https://api.vercel.com/v9/projects/"
f"{os.getenv('PROJECT_ID')}/env"
)
payload = {
'decrypt': 'true',
'slug': os.getenv('SLUG'),
'source': 'vercel-cli:pull',
'teamId': os.getenv('TEAM_ID')
}
headers = {
'Authorization': f"Bearer {os.getenv('VERCEL_TOKEN')}",
'Content-Type': 'application/json'
}
all_env_vars = requests.get(
url_to_get_all_envs,
params=payload,
headers=headers
)
# Print the response in a safe environment if required.
all_env_vars = all_env_vars.json()['envs']
# Delete items which are not required for update endpoint from payload.
del payload['decrypt']
del payload['source']
for env in all_env_vars:
# Update only if production is one of the targets of the variable.
if 'production' in env['target'] and env['type'] != 'sensitive':
'''
Check if target array has development in it.
Because development target cant have sensitive variables.
'''
targets = env['target'][:]
if 'development' in targets:
targets.remove('development')
'''
Step 2: Get decrypted value of each env variable.
'''
url_to_get_or_update_env = (
f"https://api.vercel.com/v9/projects/"
f"{os.getenv('PROJECT_ID')}/env/{env['id']}"
)
decrypted_env_response = requests.get(
url_to_get_or_update_env,
params=payload,
headers=headers
)
decrypted_env = decrypted_env_response.json()
# Print the response in a safe environment if required.
'''
Step 3: Update all variables to be sensitive if it has production
target and also remove development target if exists.
'''
data = {
'key': env['key'],
'target': targets,
'type': 'sensitive',
'value': decrypted_env['value']
}
data = json.dumps(data)
response = requests.patch(
url_to_get_or_update_env,
params=payload,
headers=headers,
data=data
)
# Print the response in a safe environment if required.
'''
Step 4: Recreate the variable with development target
if it existed before updation in previous step.
'''
if 'development' in env['target']:
data = {
'key': env['key'],
'target': ['development'],
'type': 'encrypted',
'value': decrypted_env['value']
}
data = json.dumps(data)
url_to_create_env = (
f"https://api.vercel.com/v9/projects/"
f"{os.getenv('PROJECT_ID')}/env"
)
response = requests.post(
url_to_create_env,
params=payload,
headers=headers,
data=data
)
# Print the response in a safe environment if required.



Comments