How to insert a new elbv2 rule on top of listener rules if the first rule Priority is already set to '1' using elbv2 create_rule?

Viewed 1694

I'm writing a script that will insert a new elbv2 listener rule on top of the listener rules already in the alb.

    response = elbv2_client.create_rule(
        ListenerArn=listener_arn,
        Priority=1,
        Conditions=[
            {
                'Field': 'http-request-method',
                'HttpRequestMethodConfig': {
                    'Values': ['GET']
                }

            }

        ],
        Actions=[
            {
                'Type': 'fixed-response',
                'FixedResponseConfig':
                    {
                        'ContentType': 'text/html',
                        'MessageBody': html_object,
                        'StatusCode': '504'
                    }
            }
        ]
    )

Just as you would do on the AWS console when you insert a new rule on top and the rules automatically renumber themselves.

Problem is the rule['Priority'] number is not the same as the one being shown in the AWS console (as stated in the note here: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/listener-update-rules.html)

Note: The console displays a relative sequence number for each rule, not the rule priority. You can get the priority of a rule by describing it using the AWS CLI or the Elastic Load Balancing API.

And when I use elbv2 create_rule(), it gives me this error if the top most rule is set to Priority = 1.

botocore.errorfactory.PriorityInUseException: An error occurred (PriorityInUse) when calling the CreateRule operation: Priority '1' is currently in use

TIA!

1 Answers

My solution to this was from @jordanm's idea above.

Basically to create 2 functions: One for reindexing the Rule Priorities by adding +1 before adding new rules which will automatically end on the top place. If I'm reverting to the old rules, I have another function that reindexes the Priority rules by subracting -1.

def reindex_forward(elbv2_client, listener_rules):
    for rule in reversed(listener_rules):
        if rule['Priority'] != 'default':
            new_priority = int(rule['Priority']) + 1
            elbv2_client.set_rule_priorities(
            RulePriorities=[
                {
                    'RuleArn': rule['RuleArn'],
                    'Priority': new_priority
                }
            ]
        )
    return


def reindex_back(elbv2_client, listener_rules):
    for index, rule in enumerate(listener_rules, start=1):
        if rule['Priority'] != 'default':
            elbv2_client.set_rule_priorities(
            RulePriorities=[
                {
                    'RuleArn': rule['RuleArn'],
                    'Priority': index
                }
            ]
        )
        else:
            return
    return

Related