Python Forum
Can I Limit Value used by python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can I Limit Value used by python
#1
Hello everyone
New user here and VERY new to Python so still learning a lot on it.

In my code below I use this to call an Api using 'Method' and 'Value' parameters. The URL basically acts as the frontend for the user to edit the Min, Max or capcity size of an AutoScaling Group.

For example on the URL they use to call the Api they enter Method3=Min and Value3=2 This works fine and allows the user to input whatever they want into Value2 so they can change the settings of an AutoScaling Group.

If the user makes a mistake and inputs Value as 100 instead of 10 in the URL for example Value3=100, I would not want the Autoscaling Group Max size to change to 100. Therefore is there of editing my script so I can stop that Max size from changing to 100? Like some sort of max size value in the script itself?

To invoke the Api I use PowerShell command lwith the URL

invoke-webrequest -Uri 'https://name-of-api.amazonaws.com/?TagKey=tag-key-name&TagValue=tag-value-name&Method1=Capacity&Value1=1&Method2=Min&Value2=1&Method3=Max&Value3=4' -Headers @{"X-Api-Key"="name-of-api-key"}

As you can see the user has the power to change 'Method3=Max' to have a 'Value3' of 100 if they want

Thanks

import boto3
import botocore
import os
import json
import logging

# Set up logger.
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Set up clients.
client = boto3.client('autoscaling')


def handler(event, context):
# Step one: get all AutoScaling Groups.
    response = client.describe_auto_scaling_groups(
        MaxRecords=100
    )

    # Make an empty list for ASG info storage.
    allAutoScaling = [] # empty list of no items.

    # Get the initial results and posts them to CloudWatch logs
    allAutoScaling.append(response['AutoScalingGroups'])
    logger.info(allAutoScaling)

    # If 'Marker' is present in the response, we have more to get.
    while 'Marker' in response:
        old_marker = response['Marker']
        response = client.describe_auto_scaling_groups(
            MaxRecords=100,
            Marker = old_marker
        )
        allAutoScaling.append(response['AutoScalingGroups'])
    
        # Cycles back up to repeat the pagination.

    # Now to find the tags specified in the Api Uri
    for autoscaling in allAutoScaling:
        for key in autoscaling:
           for tag in key['Tags']:
               if tag['Key'] == event['TagKey'] and tag['Value'] == event['TagValue']:
       
                if event['Method2'] == "Min":
                     if event['Value2']: 
                        Value2 = int(event['Value2'])
                        response = client.update_auto_scaling_group(
                        AutoScalingGroupName=key['AutoScalingGroupName'],    
                        MinSize=Value2
                        )
                else:
                    print('Min already at required level')
                    
                
                
                if event['Method3'] == "Max":
                     if event['Value3']: 
                        Value3 = int(event['Value3'])
                        response = client.update_auto_scaling_group(
                        AutoScalingGroupName=key['AutoScalingGroupName'],    
                        MaxSize=Value3
                        )
                else:
                    print('Max already at required level')
                    
                if event['Method1'] == "Capacity":
                      if event['Value1']: 
                         Value1 = int(event['Value1'])
                         response = client.set_desired_capacity(
                         AutoScalingGroupName=key['AutoScalingGroupName'],
                         DesiredCapacity=Value1
                         )
                else:
                    print('Capacity already at required level')
Reply
#2
cross-posted at StackOverflow

If you cross-post, please, always share a link
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
This is what I tried and as expected it wont let me edit the Max value higher than 3 which is what I wanted. Although it errors at the last else

for autoscaling in allAutoScaling:
        for key in autoscaling:
           for tag in key['Tags']:
               if tag['Key'] == event['TagKey'] and tag['Value'] == event['TagValue']:
       
               try:
                     Value = int(event['Value3'])
               except ValueError:
                     print (f"{event['Value3']} is not a valid integer")
               else:
                     if 1 <= Value <= 3:
                        response = client.update_auto_scaling_group(
                        AutoScalingGroupName=key['AutoScalingGroupName'],    
                        MaxSize=Value3
                        )
               else:
                       print(f'Value must be between 1 and 3')
Reply
#4
(Feb-09-2022, 02:50 PM)pajd Wrote: Although it errors at the last else
What error do you get? Please, share the full traceback. Fo start - check the indentation, it is a mess
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
By errors I mean the output that the value I entered wasnt correct
I get this in my CloudWatch logs

Value must be between 1 and 3


No mention of this output if I try a value larger than what is allowed

print (f"{event['Value3']} is not a valid integer")

The code works though as I cant change the ASG to more than is allowed (in this case 3).

Its just the
print (f"{event['Value3']} is not a valid integer")
doesn't return anything if I go over a value of 3
Reply
#6
(Feb-09-2022, 03:53 PM)pajd Wrote: Its just the
1 print (f"{event['Value3']} is not a valid integer") doesn't return anything if I go over a value of 3

This will not be printed if you pass e.g. 100. It will be printed if you pass e.g. spam - that is not convertible to int
pajd likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
Thanks for your help
Reply
#8
Ran into some issues again as my lambda with the python code was redployed and now its not working as it was yesterday.
Basically the code wont change the ASG Max size past 10 if I just call Method3=Max and Value3=11 using my Api URL which is what I want.

However if I call all 3 Methods like this

Method1=Capacity&Value1=1&Method2=Min&Value2=1&Method3=Max&Value3=11

Or call the Max value with either Desired capacity or Min Value then the Max value will change to whatever Desired or Min are set as. For example
Method2=Min&Value2=1&Method3=Max&Value3=11 then for some reason Method2 is changing the value of Method3 to a value of 1 also



Here is my code as Im not sure why this is happening. Could you help with this?

for autoscaling in allAutoScaling:
        for key in autoscaling:
           for tag in key['Tags']:
               if tag['Key'] == event['TagKey'] and tag['Value'] == event['TagValue']:
                   
                try:
                    Value = int(event['Value3'])
                except ValueError:
                    print (f"{event['Value3']} is not a valid integer")
                else:
                    if 1 <= Value <= 10:
                      if event['Method3'] == "Max":
                       if event['Value3']: 
                        Value3 = int(event['Value3'])
                        response = client.update_auto_scaling_group(
                        AutoScalingGroupName=key['AutoScalingGroupName'],    
                        MaxSize=Value3
                        )
                       else:
                           print(f'Value must be between 1 and 3, got {Value} instead')
                    
                    if event['Method2'] == "Min":
                     if event['Value2']: 
                        Value2 = int(event['Value2'])
                        response = client.update_auto_scaling_group(
                        AutoScalingGroupName=key['AutoScalingGroupName'],    
                        MaxSize=Value2
                        )
                    else:
                         print('Max already at required level')
                    
                    if event['Method1'] == "Capacity":
                      if event['Value1']: 
                         Value1 = int(event['Value1'])
                         response = client.set_desired_capacity(
                         AutoScalingGroupName=key['AutoScalingGroupName'],
                         DesiredCapacity=Value1
                         )
                    else:
                         print('Capacity already at required level')  
Edit: issue now resolved. Typo error for MaxSize=Value2 should be MinSize=Value2
Reply
#9
Note that on line 27 you have MaxSize=Value2 , not MinSize=Value2 like in the original code
Is it THAT HARD to debug an error like this?

Note that it is strange that you validate only valye3. Is it that any value for value is allowed? What if they supply something that cannot be converted to int - your script will crash.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#10
(Feb-10-2022, 03:24 PM)buran Wrote: Note that on line 27 you have MaxSize=Value2 , not MinSize=Value2 like in the original code
Is it THAT HARD to debug an error like this?

Note that it is strange that you validate only valye3. Is it that any value for value is allowed? What if they supply something that cannot be converted to int - your script will crash.

Anyone using this Api is fully aware that they need to use an integer. Also the Max value is the only value I need to restrict as I don't want users changing the Autoscaling group to more than 10 instances.

Thanks for your help
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I make this Python script add a limit to trades made with API? streetlaw 0 2,021 Oct-12-2018, 11:41 AM
Last Post: streetlaw
  Python - Limit Sentence Length to 10 Words - Text file dj99 2 5,207 Jul-21-2018, 02:24 PM
Last Post: dj99
  Error in Python 3.6 and how to limit decimal places Raptor88 6 9,883 Mar-18-2017, 05:02 AM
Last Post: Raptor88

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020