Meet101 Meet101 - 3 months ago 18
Python Question

Don't understand cause of exception

Here is my code:

import boto3
import json

client = boto3.client('elasticbeanstalk')
code_pipeline = boto3.client('codepipeline')

def put_job_success(job, message):
print "Putting job success"
print (message)
code_pipeline.put_job_success_result(jobId=job)

def put_job_failure(job, message):
print('Putting job failure')
print(message)
code_pipeline.put_job_failure_result(jobId=job, failureDetails={'message': message, 'type': 'JobFailed'})

def get_user_params(job_data):
user_parameters = job_data['actionConfiguration']['configuration']['UserParameters']
decoded_parameters = json.loads(user_parameters)
print user_parameters

def lambda_handler(event, context):
try:
# Extract the Job ID
job_id = event['CodePipeline.job']['id']

# Extract the Job Data
job_data = event['CodePipeline.job']['data']

# Extract the params
params = get_user_params(job_data)

# Get the list of artifacts passed to the function
artifacts = job_data['inputArtifacts']

put_job_success(job_id, 'successfuly done')

except Exception as e:

# If any other exceptions which we didn't expect are raised
# then fail the job and log the exception message.
print('Function failed due to exception.')
print(e)
put_job_failure(job_id, 'Function exception: ' + str(e))

print('Function complete.')
return "Complete."


Getting Error:

traceback (most recent call last):
File "/var/task/lambda_function.py", line 48, in lambda_handler
put_job_failure(job_id, 'Function exception: ' + str(e))
UnboundLocalError: local variable 'job_id' referenced before assignment


Please help!

Answer

Nothing in your try block is guaranteed to run once you hit the except block. This includes the job_id assignment. If you want to get rid of the error, you can try:

def lambda_handler(event, context):  
    job_id = None
    try:  
        # Extract the Job ID  
        job_id = event['CodePipeline.job']['id']  

        # Extract the Job Data    
        job_data = event['CodePipeline.job']['data']   

        # Extract the params  
        params = get_user_params(job_data)  

        # Get the list of artifacts passed to the function  
        artifacts = job_data['inputArtifacts']  

        put_job_success(job_id, 'successfuly done')  

    except Exception as e:  

        # If any other exceptions which we didn't expect are raised  
        # then fail the job and log the exception message.  
        print('Function failed due to exception.')   
        print(e)  
        put_job_failure(job_id, 'Function exception: ' + str(e))  
Comments