Stop/Start EC2 Instances With AWS Lambda Function

Поділитися
Вставка
  • Опубліковано 29 гру 2024

КОМЕНТАРІ • 5

  • @madhusudankunder4730
    @madhusudankunder4730 2 роки тому

    Hello Sir i write the code as per the instruction but shows error.
    import json
    import boto3
    client = boto3.client('ec2')
    def lambda_handler(event, context):
    response = client.describe_instances(
    Filters=[
    {
    'Name': 'tag:weekend',
    'values': [
    '9-22',
    ]
    },
    ],
    )
    instances = []
    length = len(response['Reservations'])
    for i in range(length):
    instanceID = response['Reservations'][i]['instances'][0]['instanceId']
    instances.append(instanceID)
    if not instances:
    print("No instance found")
    else:
    response = client.stop_instances(
    InstanceIDs=instances,
    )
    Error :
    est Event Name
    test
    Response
    {
    "errorMessage": "Syntax error in module 'lambda_function': unindent does not match any outer indentation level (lambda_function.py, line 26)",
    "errorType": "Runtime.UserCodeSyntaxError",
    "requestId": "3fb2d140-ff44-4fd9-8d9f-3dba03170939",
    "stackTrace": [
    " File \"/var/task/lambda_function.py\" Line 26
    if not instances:
    "
    ]
    }

    • @devopsAvenue
      @devopsAvenue  2 роки тому

      There's an indentation error for your if/else block. You shouldn't have space in front if/else statements. I would suggest selecting the code below and hit shift+tab.
      if not instances:
      print("No instance found")
      else:
      response = client.stop_instances(
      InstanceIDs=instances,
      )
      Hope this helps.

    • @madhusudankunder4730
      @madhusudankunder4730 2 роки тому +1

      @@devopsAvenue Thanks a Lot for your Quick Reply Gurlal ji 🙂

  • @umeshyadav-tl8qp
    @umeshyadav-tl8qp 2 роки тому

    Hi, Thanks for this video but after executing above python script i am getting error as
    {
    "errorMessage": "name 'response' is not defined",
    "errorType": "NameError",
    "requestId": "",
    "stackTrace": [
    " File \"/var/lang/lib/python3.9/importlib/__init__.py\", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
    ",
    " File \"\", line 1030, in _gcd_import
    ",
    " File \"\", line 1007, in _find_and_load
    ",
    " File \"\", line 986, in _find_and_load_unlocked
    ",
    " File \"\", line 680, in _load_unlocked
    ",
    " File \"\", line 850, in exec_module
    ",
    " File \"\", line 228, in _call_with_frames_removed
    ",
    " File \"/var/task/lambda_function.py\", line 21, in
    length = len(response['Reservations'])
    "
    ]
    }

    • @devopsAvenue
      @devopsAvenue  2 роки тому

      looks like you may have modified function name?