簡體   English   中英

AWS Lambda Python boto3 EC2 實例開始 - “errorType”:“UnboundLocalError”,

[英]AWS Lambda Python boto3 EC2 instances starting - "errorType": "UnboundLocalError",

這個程序的目的是根據事件啟動 ec2 實例。

它不喜歡 ec2_console_resource.instances.all() 中 each_scheduled_instance 的以下 2 行代碼: each_scheduled_instance.start() 這是程序。

    {
        "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"
        ]
     }

這是代碼

    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'
   

你有縮進問題。 它應該是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM