Issues Adjusting Auto-scaling Desired Capacity

Question:

I have this code that ran successfully locally, but not on AWS.

import boto3

client = boto3.client('autoscaling')

def set_desired_capacity(AutoScalingGroupName, DesiredCapacity):
    response = client.set_desired_capacity(
    AutoScalingGroupName='My_Auto_Scaling_Group',
    DesiredCapacity =2,
    HonorCooldown=True,

    )
    return response


def lambda_handler(event, context):
    
    Auto_scale = set_desired_capacity(AutoScalingGroupName, DesiredCapacity)

print('Executed successfuly')

I keep getting this error at the line inside the lambda handler function

"errorMessage": "name 'AutoScalingGroupName' is not defined",
  "errorType": "NameError",

I’m curious what could be wrong.

Asked By: charles klaus

||

Answers:

You have an error in your python code. You’re passing in "AutoScalingGroupName" to your function but you’ve hard coded your variables. It seems that you don’t have an ASG in that region named "My_Auto_Scaling_Group". I took your code and modified it to run locally, but it should port to lambda with no issues. This code works:

import boto3

session = boto3.session.Session()
client = session.client('autoscaling')


def set_desired_capacity(asg_name, desired_capacity):
    response = client.set_desired_capacity(
        AutoScalingGroupName=asg_name,
        DesiredCapacity=desired_capacity,
    )
    return response


def lambda_handler(event, context):
    asg_name = "test"
    desired_capacity = 2
    return set_desired_capacity(asg_name, desired_capacity)


if __name__ == '__main__':
    print(lambda_handler("", ""))
Answered By: Coin Graham