Home > Back-end >  AWS Lambda Python boto3 EC2 instances starting - "errorType": "UnboundLocalError"
AWS Lambda Python boto3 EC2 instances starting - "errorType": "UnboundLocalError"

Time:09-08

My intent of this program is to start ec2 instances based on the event.

It doesn't like the following 2 lines of code for each_scheduled_instance in ec2_console_resource.instances.all(): each_scheduled_instance.start() This is the program.

    {
        "errorMessage": "local variable 'each_scheduled_instance' referenced before 
      assignment",
       "errorType": "UnboundLocalError",
        "requestId": "3054209f-5cf7-429e-bcc7-7109a3b28a29",
        "stackTrace": [
             "  File \"/var/task/lambda_function.py\", line 19, in lambda_handler\n    return 
              dealwithec2instances(event)\n",
             "  File \"/var/task/lambda_function.py\", line 25, in dealwithec2instances\n    
               return ec2_instances_start(event)\n",
             "  File \"/var/task/lambda_function.py\", line 40, in ec2_instances_start\n    
              each_scheduled_instance.wait_until_running()\n"
        ]
     }

This the code

    import boto3
    import logging
    import os
    from pprint import pprint

    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

   def lambda_handler(event, context):
        
       varbotname = event['bot']['name']
       #print(vareventname)
       logger.info('bot name is '  str(varbotname))

      return dealwithec2instances(event)

   def dealwithec2instances(event):
        print('in dealwithec2instances')
        intentname = event['currentIntent']['name']
        if intentname == 'StartInstances':
        return ec2_instances_start(event)
  
   def ec2_instances_start(event):
      print('in ec2 instances method')
      aws_mgmt_console = boto3.session.Session()
      ec2_console_resource = aws_mgmt_console.resource('ec2')
      ec2_console_client = aws_mgmt_console.client('ec2')

      waiter=ec2_console_client.get_waiter('instance_running')

      for each_scheduled_instance in  ec2_console_resource.instances.all():
            each_scheduled_instance.start()
   
      each_scheduled_instance.wait_until_running()    

      return 'success'
   

CodePudding user response:

You have indentation issue. It should be:

      for each_scheduled_instance in  ec2_console_resource.instances.all():
            each_scheduled_instance.start()   
            each_scheduled_instance.wait_until_running()  
  • Related