Last active
September 7, 2023 13:21
-
-
Save deej81/e86dc379e240c7c0e149e73c0c87603f to your computer and use it in GitHub Desktop.
Create a template .env file from a docker-compose.yml file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import re | |
| def extract_env_vars_from_docker_compose(compose_file_path): | |
| with open(compose_file_path, 'r') as file: | |
| content = file.read() | |
| return set(re.findall(r'\$\{(\w+)\}', content)) | |
| def load_existing_env_vars(env_file_path=".env"): | |
| env_vars = {} | |
| try: | |
| with open(env_file_path, 'r') as file: | |
| for line in file: | |
| match = re.match(r'(\w+)=(.*)', line) | |
| if match: | |
| env_vars[match.group(1)] = match.group(2) | |
| except FileNotFoundError: | |
| pass | |
| return env_vars | |
| def write_env_file(all_vars, existing_vars, env_file_path=".env"): | |
| with open(env_file_path, 'w') as file: | |
| for var in sorted(all_vars): | |
| value = existing_vars.get(var, "") | |
| file.write(f"{var}={value}\n") | |
| if __name__ == "__main__": | |
| docker_compose_path = "docker-compose.yml" | |
| env_file_path = ".env" | |
| extracted_vars = extract_env_vars_from_docker_compose(docker_compose_path) | |
| existing_vars = load_existing_env_vars(env_file_path) | |
| # Identify new variables and changed ones | |
| new_vars = extracted_vars - set(existing_vars.keys()) | |
| updated_vars = extracted_vars & set(existing_vars.keys()) # Intersection | |
| # Merge variables | |
| all_vars = set(existing_vars.keys()) | extracted_vars | |
| # Write to file | |
| write_env_file(all_vars, existing_vars, env_file_path) | |
| # Display summary | |
| print("Summary:") | |
| print("-" * 30) | |
| if new_vars: | |
| print("New variables added:") | |
| for var in sorted(new_vars): | |
| print(f"- {var}") | |
| else: | |
| print("No new variables added.") | |
| if updated_vars: | |
| print("\nVariables found in both .env and docker-compose (unchanged values):") | |
| for var in sorted(updated_vars): | |
| print(f"- {var}") | |
| else: | |
| print("\nNo matching variables found in both .env and docker-compose.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment