close

How to access an AWS Lambda environment variable from Python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to access an AWS Lambda environment variable from Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to access an AWS Lambda environment variable from Python?

  1. How to access an AWS Lambda environment variable from Python?

    I used this code; it includes both cases, setting the variable from the handler and setting it from outside the handler.

  2. access an AWS Lambda environment variable from Python

    I used this code; it includes both cases, setting the variable from the handler and setting it from outside the handler.

Method 1

Both

import os
os.getenv('MY_ENV_VAR')

And

os.environ['MY_ENV_VAR']

are feasible solutions, just make sure in the lambda GUI that the ENV variables are actually there.

Method 2

I used this code; it includes both cases, setting the variable from the handler and setting it from outside the handler.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Trying new lambda stuff"""
import os
import configparser

class BqEnv(object):
    """Env and self variables settings"""
    def __init__(self, service_account, configfile=None):
        config = self.parseconfig(configfile)
        self.env = config
        self.service_account = service_account

    @staticmethod
    def parseconfig(configfile):
        """Connection and conf parser"""
        config = configparser.ConfigParser()
        config.read(configfile)
        env = config.get('BigQuery', 'env')
        return env

    def variable_tests(self):
        """Trying conf as a lambda variable"""
        my_env_var = os.environ['MY_ENV_VAR']
        print my_env_var
        print self.env
        return True

def lambda_handler(event, context):
    """Trying env variables."""
    print event
    configfile = os.environ['CONFIG_FILE']
    print configfile
    print type(str(configfile))
    bqm = BqEnv('some-json.json', configfile)
    bqm.variable_tests()
    return True

I tried this with a demo config file that has this:

[BigQuery]
env = prod

And the setting on lambda was the following: 

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read