Skip to content

Commit

Permalink
feat: always restart proxy and load sample vars in vault
Browse files Browse the repository at this point in the history
  • Loading branch information
tushar5526 committed Dec 29, 2023
1 parent d4d79eb commit b0d5161
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
2 changes: 1 addition & 1 deletion server/sarthi/deployer.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def __init__(self, config: DeploymentConfig):
os.path.join(self._project_path, config.compose_file_location)
)
self._nginx_helper = NginxHelper(config)
self._secrets_helper = SecretsHelper(self._config.project_name, self._config.branch_name)
self._secrets_helper = SecretsHelper(self._config.project_name, self._config.branch_name, self._project_path)
self._outer_proxy_conf_location = (
os.environ.get("NGINX_PROXY_CONF_LOCATION") or "/etc/nginx/conf.d"
)
Expand Down
24 changes: 23 additions & 1 deletion server/sarthi/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import typing
from dataclasses import dataclass, fields
import requests
import json
from dotenv import dotenv_values

import yaml

Expand Down Expand Up @@ -39,6 +41,7 @@ class ComposeHelper:
services:
nginx:
image: nginx
restart: always
ports:
- '%s:80'
volumes:
Expand Down Expand Up @@ -260,17 +263,36 @@ def reload_nginx(self):
logger.info("Nginx reloaded successfully.")

class SecretsHelper:
def __init__(self, project_name, branch_name):
def __init__(self, project_name, branch_name, project_path):
self._project_path = project_path
self._secrets_namespace = f"{project_name}/{branch_name}"
self._secret_url = f"{os.environ.get('VAULT_BASE_URL')}/v1/kv/data/{self._secrets_namespace}"
self._headers = {
"X-Vault-Token": os.environ.get('VAULT_TOKEN')
}

def _create_env_placeholder(self):
sample_envs = {"key": "secret-value"}
# check for .env.sample in folder and load those sample .env vars in vault
sample_env_path = os.path.join(self._project_path, '.env.sample')
if os.path.exists(sample_env_path):
sample_envs = dotenv_values(sample_env_path)

sample_env_path = os.path.join(self._project_path, 'sample.env')
if os.path.exists(sample_env_path):
sample_envs = dotenv_values(sample_env_path)

response = requests.post(url=self._secret_url, headers=self._headers, data=json.dumps({
"data": {key: value for key, value in sample_envs.items()}
}))
response.raise_for_status()
logger.debug(f"Successfully loaded sample env vars in value {response.json()}")

def inject_env_variables(self, project_path):
response = requests.get(url=self._secret_url, headers=self._headers)
if response.status_code != 200:
logger.debug(f"No secrets found in vault for {self._secrets_namespace}")
self._create_env_placeholder()
return
logger.debug(f"Found secrets for {self._secrets_namespace}")
secret_data = response.json()
Expand Down

0 comments on commit b0d5161

Please sign in to comment.