Skip to content

Instantly share code, notes, and snippets.

@ohing504
Last active July 28, 2020 17:13
Show Gist options
  • Save ohing504/25981d9eb98774193b09febee65d64cb to your computer and use it in GitHub Desktop.
Save ohing504/25981d9eb98774193b09febee65d64cb to your computer and use it in GitHub Desktop.
AWS ElasticBeanstalk sync environments from file.
#!/usr/bin/env python
import argparse
import subprocess
import questionary
class Color:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def get_envs_from_eb(environment=None):
try:
cmd = f'eb printenv {environment}' if environment else f'eb printenv'
stdout = subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError as e:
print(f'{Color.FAIL}{e.output.decode("utf-8").strip()}')
exit(e.returncode)
envs = stdout.decode('utf-8').strip()
return [env.strip().replace(' ', '') for env in envs.split('\n')[1:]]
def get_envs_from_file(filepath):
try:
with open(filepath, 'r') as f:
lines = f.readlines()
envs = [line.strip().replace('"', '') for line in lines if not line.startswith('#')]
except Exception as e:
print(f'{Color.FAIL}{e}')
exit(1)
return envs
def is_different_list(list1, list2):
if len(list1) != len(list2):
return True
sorted_list1 = sorted(list1)
sorted_list2 = sorted(list2)
for idx, value in enumerate(sorted_list1):
if sorted_list2[idx] != value:
return True
def print_diff(old_envs_dict, new_envs_dict):
keys = sorted(list(set(list(old_envs_dict.keys()) + list(new_envs_dict.keys()))))
for key in keys:
if key in old_envs_dict.keys() and key not in new_envs_dict.keys():
print(f'\t{Color.FAIL}deleted : {key} = {old_envs_dict[key]}')
elif key not in old_envs_dict.keys() and key in new_envs_dict.keys():
print(f'\t{Color.OKGREEN}new : {key} = {new_envs_dict[key]}')
elif old_envs_dict[key] != new_envs_dict[key]:
print(f'\t{Color.WARNING}modified: {key} = {old_envs_dict[key]} => {new_envs_dict[key]}')
def eb_setenv_diff(old_envs_dict, new_envs_dict, environment=None):
envs = [f'{k}="{v}"' for k, v in new_envs_dict.items()]
envs += [f'{key}=""' for key in old_envs_dict.keys() - new_envs_dict.keys()]
cmd = f'eb setenv {" ".join(envs)}' + (f' -e {environment}' if environment else '')
try:
subprocess.call(cmd, shell=True)
except subprocess.CalledProcessError as e:
print(f'{Color.FAIL}{e.output.decode("utf-8").strip()}')
exit(e.returncode)
def main(filepath, environment=None):
curr_envs = get_envs_from_eb(environment)
new_envs = get_envs_from_file(filepath)
if not is_different_list(curr_envs, new_envs):
print('\tAlready Synced!')
return
curr_envs_dict = {env.split('=')[0]: env.split('=', 1)[-1] for env in curr_envs}
new_envs_dict = {env.split('=')[0]: env.split('=', 1)[-1] for env in new_envs}
print_diff(curr_envs_dict, new_envs_dict)
answer = questionary.confirm('Do you want to continue?', default=False).ask()
if answer:
eb_setenv_diff(curr_envs_dict, new_envs_dict, environment)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Sync environment variables.')
parser.add_argument('-e', '--environment', metavar='ENVIRONMENT_NAME', type=str,
help='environment name')
parser.add_argument('filepath', help='environments filepath')
args = parser.parse_args()
main(**vars(args))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment