Last active
June 3, 2021 01:06
-
-
Save monkut/cd16a8c532694bac4383d53978a47373 to your computer and use it in GitHub Desktop.
Command-line script to get/set environment variables and list existing aws lambda functions
This file contains 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
""" | |
Get/Set lambda environment variables | |
""" | |
import os | |
import pprint | |
from pathlib import Path | |
from typing import Tuple, List | |
from enum import Enum | |
import boto3 | |
AWS_PROFILE = os.getenv("AWS_PROFILE", None) | |
AWS_REGION = os.getenv("AWS_DEFAULT_REGION", "ap-northeast-1") | |
DEFAULT_BOTO3_LAMBDA_CLIENT_ENDPOINT = f"https://lambda.{AWS_REGION}.amazonaws.com" | |
BOTO3_LAMBDA_CLIENT_ENDPOINT = os.getenv("BOTO3_LAMBDA_CLIENT_ENDPOINT", DEFAULT_BOTO3_LAMBDA_CLIENT_ENDPOINT) | |
LAMBDA_CLIENT = boto3.client("lambda", region_name=AWS_REGION, endpoint_url=BOTO3_LAMBDA_CLIENT_ENDPOINT) | |
DEFAULT_OUTPUT_DIRECTORY = Path(__file__).absolute().parent | |
def list_functions() -> List[str]: | |
response = LAMBDA_CLIENT.list_functions() | |
function_names = [] | |
for function_info in response["Functions"]: | |
function_name = function_info["FunctionName"] | |
function_names.append(function_name) | |
return sorted(function_names) | |
def get_envars(funcname: str, output_filepath: Path) -> Path: | |
# lambda get-function-configuration | |
response = LAMBDA_CLIENT.get_function_configuration(FunctionName=funcname) | |
with output_filepath.open("w") as out: | |
for key, value in sorted(response["Environment"]["Variables"].items()): | |
line = f"{key}={value}\n" | |
out.write(line) | |
return output_filepath | |
def set_envars(funcname: str, source_filepath: Path) -> Path: | |
assert source_filepath.exists() | |
# read-in environment variables file | |
with source_filepath.open("r") as in_file: | |
variables = {} | |
for line in in_file: | |
if line.strip() and "=" in line: | |
key, value = line.strip().split("=") | |
variables[key.strip()] = value.strip() | |
if not variables: | |
raise ValueError(f"No variables defined in: {source_filepath}") | |
pprint.pprint(variables) | |
# lambda update-function-configuration | |
response = LAMBDA_CLIENT.update_function_configuration( | |
FunctionName=funcname, | |
Environment={"Variables": variables} | |
) | |
return response | |
def filepath(value: str) -> Path: | |
return Path(value).absolute() | |
class ValidCommands(str, Enum): | |
GET = "get" | |
SET = "set" | |
LIST = "list" | |
@classmethod | |
def values(cls) -> Tuple[str, str, str]: | |
return cls.GET.value, cls.SET.value, cls.LIST.value | |
if __name__ == "__main__": | |
import argparse | |
parser = argparse.ArgumentParser(description=__doc__) | |
parser.add_argument("command", type=ValidCommands, choices=ValidCommands.values(), help="(get|set) Lambda Environment Variables") | |
parser.add_argument("-f", "--function-name", dest="function_name", default=None, help="Lambda Function Name") | |
parser.add_argument("-e", "--envar-filepath", dest="envar_filepath", type=filepath, help="DEFAULT=./{funcname}.env") | |
args = parser.parse_args() | |
print(f"AWS_PROFILE={AWS_PROFILE}") | |
if args.command in (ValidCommands.SET, ValidCommands.GET): | |
if not args.function_name: | |
raise parser.error("Required argument missing: --function-name") | |
if not args.envar_filepath: | |
output_filepath = DEFAULT_OUTPUT_DIRECTORY / f"{args.function_name}.env" | |
else: | |
output_filepath = args.envar_filepath | |
if not output_filepath.parent.exists(): | |
raise parser.error(f"--envar-filepath parent directory does not exist: {args.envar_filepath}") | |
if args.command == ValidCommands.SET: | |
if not args.envar_filepath.exists(): | |
raise parser.error(f"--envar-filepath does not exist: {args.envar_filepath}") | |
result = set_envars(args.function_name, source_filepath=args.envar_filepath) | |
elif args.command == ValidCommands.GET: | |
result = get_envars(args.function_name, output_filepath=output_filepath) | |
print(result) | |
elif args.command == ValidCommands.LIST: | |
result = list_functions() | |
print("\n".join(result)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment