简体   繁体   中英

AWS Lambda is not reading environment variables

I am writing a python script to query the Qualys API for vulnerability metadata. I am executing it as a lambda function in AWS. I have set my environment variables in the console, but when I execute my function, I am getting the following error:

module initialization error: name 'QUALYS_USERNAME' is not defined

I am using this os module to call them in my code in my handler function:

import os
import requests
import time
import lxml
import tinys3
from lxml import etree

def lambda_handler(event, context):
    QUALYS_USERNAME = os.environ('QUALYS_USERNAME')
    QUALYS_PASSWORD = os.environ('QUALYS_PASSWORD')
    ACCESS_KEY = os.environ('ACCESS_KEY')
    SECRET_KEY = os.environ('SECRET_KEY')

s = requests.Session()
s.headers.update({'X-Requested-With':QUALYS_USERNAME})

def login(s):
    payload = {'action':'login', 'username':QUALYS_USERNAME, 
    'password':QUALYS_PASSWORD}

    r = s.post('https://qualysapi.qualys.com/api/2.0/fo/session/', 
    data=payload)

def launchReport(s, polling_delay=120):
    payload = {'action':'launch', 'template_id':'X', 
    'output_format':'xml', 'report_title':'X'}

    r = s.post('https://qualysapi.qualys.com/api/2.0/fo/report/', data=payload)
    global extract_id
    extract_id = etree.fromstring(r.content).find('.//VALUE').text
    print("Report ID = %s" % extract_id)
    time.sleep(polling_delay)
    return extract_id

def bucket_upload(s):
    conn = tinys3.Connection(ACCESS_KEY,SECRET_KEY)
    payload = {'action': 'fetch', 'id': extract_id}
    r = s.post('https://qualysapi.qualys.com/api/2.0/fo/report/', 
    data=payload)

    os.chdir('/tmp')
    with open(extract_id + '.xml', 'w') as file:
        file.write(r.content)
    f = open(extract_id + '.xml','rb')
    conn.upload(extract_id + '.xml',f,'X-bucket')

login(s)
launchReport(s)
bucket_upload(s)

Here are my defined environment variables in Lambda:

Env Variables Console

I am not sure why I am getting this error.

Potential cause: the inline code, outside of the functions, is running before the event handler.

Unrelated: rather than use environment variables for credentials, you should use IAM roles for AWS credentials and use Parameter Store for other, non-AWS, credentials.

您需要将环境变量作为字典访问,而不是作为函数调用。

QUALYS_USERNAME = os.environ["QUALYS_USERNAME"] QUALYS_PASSWORD = os.environ["QUALYS_PASSWORD"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM