2
votes

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.

2
If you add some print statements, run the Lambda, then look at CloudWatch Logs, you will see what code is executing when.jarmod

2 Answers

6
votes

You need to access the environment variables as a dictionary not as a function call.

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

4
votes

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.