Using environment variables when deploying Lambda containers
While building a simple application that pulls API location data for the International Space Station, I was running the ingestion and transformation script locally on my system, passing the necessary parameters to the CLI. Below is the code snippet of how I was going about this.
def main(params):
user = params.u
password = params.p
host = params.host
...
if __name__ == "__main__":
# Create the CLI parser
parser = argparse.ArgumentParser(description="Call ISS API and store current position in Amazon RDS")
# Create two CLI arguments to ask for username and password
parser.add_argument("-u", help="username for Postgres")
parser.add_argument("-p", help="password for Postgres")
parser.add_argument("--host", help="hostname for RDS Postgres server")
args = parser.parse_args()
main()
Realising this wasn't probably going to work when deploying the container using a Lambda function, simply because Lambda does not support passing CLI arguments directly to the container. My research pointed me to a better implementation using environment variables to pass the -u, -p, and --host parameters to the container.
def main():
# Read database credentials from environment variables
user = os.getenv("POSTGRES_USER")
password = os.getenv("POSTGRES_PASSWORD")
host = os.getenv("POSTGRES_HOST")
...
if __name__ == "__main__":
main()
The result: a more elegant solution that works with a Lambda function calling the container stored in ECR.