Repository: ansible-collections/amazon.aws

Issue:
elb_application_lb: unable to use authenticate-oidc
### Summary

In the past, you can set as rule 

```yml
            Actions:
              - Type: authenticate-oidc
                Order: 1
                AuthenticateOidcConfig:
                  ClientSecret: "{{ lookup('onepassword', 'abc123') }}"
                  UseExistingClientSecret: True
                  ....
```

and it worked. Because of this logic, it doesn't matter if the rule is a new one or an existing one.

Currently you get back the error from the past:

```
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.errorfactory.InvalidLoadBalancerActionException: An error occurred (InvalidLoadBalancerAction) when calling the ModifyRule operation: You cannot both specify a client secret and set UseExistingClientSecret to true
fatal: [localhost]: FAILED! => {"boto3_version": "1.28.73", "botocore_version": "1.31.85", "changed": false, "error": {"code": "InvalidLoadBalancerAction", "message": "You cannot both specify a client secret and set UseExistingClientSecret to true", "type": "Sender"}, "msg": "An error occurred (InvalidLoadBalancerAction) when calling the ModifyRule operation: You cannot both specify a client secret and set UseExistingClientSecret to true", "response_metadata": {"http_headers": {"connection": "close", "content-length": "352", "content-type": "text/xml", "date": "Thu, 23 Nov 2023 13:12:43 GMT", "x-amzn-requestid": "0b5b9a7b-e4f7-4c0e-9aae-cd3c4dfbe447"}, "http_status_code": 400, "request_id": "0b5b9a7b-e4f7-4c0e-9aae-cd3c4dfbe447", "retry_attempts": 0}}
```

>  You cannot both specify a client secret and set UseExistingClientSecret to true

once, fixed in https://github.com/ansible-collections/amazon.aws/pull/1270

When removing the `ClientSecret` key

```yml
            Actions:
              - Type: authenticate-oidc
                Order: 1
                AuthenticateOidcConfig:
                  #ClientSecret: "{{ lookup('onepassword', 'abc123') }}"
                  UseExistingClientSecret: True
                  ....
```

it comes to a new error

```
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: botocore.errorfactory.InvalidLoadBalancerActionException: An error occurred (InvalidLoadBalancerAction) when calling the ModifyRule operation: You can only set UseExistingClientSecret to true if the rule already has an authenticate-oidc action
fatal: [localhost]: FAILED! => {"boto3_version": "1.28.73", "botocore_version": "1.31.85", "changed": false, "error": {"code": "InvalidLoadBalancerAction", "message": "You can only set UseExistingClientSecret to true if the rule already has an authenticate-oidc action", "type": "Sender"}, "msg": "An error occurred (InvalidLoadBalancerAction) when calling the ModifyRule operation: You can only set UseExistingClientSecret to true if the rule already has an authenticate-oidc action", "response_metadata": {"http_headers": {"connection": "close", "content-length": "373", "content-type": "text/xml", "date": "Thu, 23 Nov 2023 13:14:45 GMT", "x-amzn-requestid": "f4532a2a-397b-4efb-a906-e6a42a5ba151"}, "http_status_code": 400, "request_id": "f4532a2a-397b-4efb-a906-e6a42a5ba151", "retry_attempts": 0}}
```

> You can only set UseExistingClientSecret to true if the rule already has an authenticate-oidc action

So something new has changed/gets broken ....

### Issue Type

Bug Report

### Component Name

elb_application_lb

### Ansible Version

```console (paste below)
ansible [core 2.15.5]
  config file = /home/m/git/lekker/iac/ansible.cfg
  configured module search path = ['/home/m/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/m/.local/lib/python3.10/site-packages/ansible
  ansible collection location = /home/m/.ansible/collections:/usr/share/ansible/collections
  executable location = /home/m/.local/bin/ansible
  python version = 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] (/usr/bin/python3)
  jinja version = 3.1.2
  libyaml = True
```


### Collection Versions

```console (paste below)
ansible-galaxy collection list

# /home/m/.ansible/collections/ansible_collections
Collection                     Version
------------------------------ -------
amazon.aws                     7.0.0  
ansible.netcommon              5.1.2  
ansible.posix                  1.5.4  
ansible.utils                  2.10.3 
ansible.windows                2.0.0  
community.aws                  7.0.0  
community.crypto               2.13.1 
community.general              7.4.0  
community.mysql                3.7.2  
community.postgresql           3.0.0  
community.zabbix               1.9.3  
devsec.hardening               8.7.0  
markuman.nessus                0.0.6  
markuman.nextcloud             26.0.0 
opitzconsulting.ansible_oracle 3.9.0  

# /home/m/.local/lib/python3.10/site-packages/ansible_collections
Collection                     Version
------------------------------ -------
amazon.aws                     6.5.0  
ansible.netcommon              5.2.0  
ansible.posix                  1.5.4  
ansible.utils                  2.11.0 
ansible.windows                1.14.0 
arista.eos                     6.1.2  
awx.awx                        22.7.0 
azure.azcollection             1.18.1 
check_point.mgmt               5.1.1  
chocolatey.chocolatey          1.5.1  
cisco.aci                      2.7.0  
cisco.asa                      4.0.2  
cisco.dnac                     6.7.5  
cisco.intersight               1.0.27 
cisco.ios                      4.6.1  
cisco.iosxr                    5.0.3  
cisco.ise                      2.5.16 
cisco.meraki                   2.16.5 
cisco.mso                      2.5.0  
cisco.nso                      1.0.3  
cisco.nxos                     4.4.0  
cisco.ucs                      1.10.0 
cloud.common                   2.1.4  
cloudscale_ch.cloud            2.3.1  
community.aws                  6.3.0  
community.azure                2.0.0  
community.ciscosmb             1.0.6  
community.crypto               2.15.1 
community.digitalocean         1.24.0 
community.dns                  2.6.2  
community.docker               3.4.9  
community.fortios              1.0.0  
community.general              7.5.0  
community.google               1.0.0  
community.grafana              1.5.4  
community.hashi_vault          5.0.0  
community.hrobot               1.8.1  
community.libvirt              1.3.0  
community.mongodb              1.6.3  
community.mysql                3.7.2  
community.network              5.0.0  
community.okd                  2.3.0  
community.postgresql           2.4.3  
community.proxysql             1.5.1  
community.rabbitmq             1.2.3  
community.routeros             2.10.0 
community.sap                  1.0.0  
community.sap_libs             1.4.1  
community.skydive              1.0.0  
community.sops                 1.6.6  
community.vmware               3.10.0 
community.windows              1.13.0 
community.zabbix               2.1.0  
containers.podman              1.10.3 
cyberark.conjur                1.2.2  
cyberark.pas                   1.0.23 
dellemc.enterprise_sonic       2.2.0  
dellemc.openmanage             7.6.1  
dellemc.powerflex              1.9.0  
dellemc.unity                  1.7.1  
f5networks.f5_modules          1.26.0 
fortinet.fortimanager          2.2.1  
fortinet.fortios               2.3.2  
frr.frr                        2.0.2  
gluster.gluster                1.0.2  
google.cloud                   1.2.0  
grafana.grafana                2.2.3  
hetzner.hcloud                 1.16.0 
hpe.nimble                     1.1.4  
ibm.qradar                     2.1.0  
ibm.spectrum_virtualize        1.12.0 
infinidat.infinibox            1.3.12 
infoblox.nios_modules          1.5.0  
inspur.ispim                   1.3.0  
inspur.sm                      2.3.0  
junipernetworks.junos          5.3.0  
kubernetes.core                2.4.0  
lowlydba.sqlserver             2.2.1  
microsoft.ad                   1.3.0  
netapp.aws                     21.7.0 
netapp.azure                   21.10.0
netapp.cloudmanager            21.22.0
netapp.elementsw               21.7.0 
netapp.ontap                   22.7.0 
netapp.storagegrid             21.11.1
netapp.um_info                 21.8.0 
netapp_eseries.santricity      1.4.0  
netbox.netbox                  3.14.0 
ngine_io.cloudstack            2.3.0  
ngine_io.exoscale              1.1.0  
ngine_io.vultr                 1.1.3  
openstack.cloud                2.1.0  
openvswitch.openvswitch        2.1.1  
ovirt.ovirt                    3.2.0  
purestorage.flasharray         1.21.0 
purestorage.flashblade         1.14.0 
purestorage.fusion             1.6.0  
sensu.sensu_go                 1.14.0 
servicenow.servicenow          1.0.6  
splunk.es                      2.1.0  
t_systems_mms.icinga_director  1.33.1 
telekom_mms.icinga_director    1.34.1 
theforeman.foreman             3.14.0 
vmware.vmware_rest             2.3.1  
vultr.cloud                    1.10.0 
vyos.vyos                      4.1.0  
wti.remote                     1.0.5  
```


### AWS SDK versions

```console (paste below)
WARNING: Package(s) not found: boto
Name: boto3
Version: 1.28.73
Summary: The AWS SDK for Python
Home-page: https://github.com/boto/boto3
Author: Amazon Web Services
Author-email: 
License: Apache License 2.0
Location: /home/m/.local/lib/python3.10/site-packages
Requires: botocore, jmespath, s3transfer
Required-by: awslogs
---
Name: botocore
Version: 1.31.85
Summary: Low-level, data-driven core of boto 3.
Home-page: https://github.com/boto/botocore
Author: Amazon Web Services
Author-email: 
License: Apache License 2.0
Location: /home/m/.local/lib/python3.10/site-packages
Requires: jmespath, python-dateutil, urllib3
Required-by: awscli, boto3, s3transfer
```


### Configuration

```console (paste below)
CONFIG_FILE() = /home/m/git/lekker/iac/ansible.cfg
DEFAULT_ROLES_PATH(/home/m/git/lekker/iac/ansible.cfg) = ['/home/m/.ansible/roles']
INTERPRETER_PYTHON(/home/m/git/lekker/iac/ansible.cfg) = /usr/bin/python3

```


### OS / Environment

Ubuntu 22.04

### Steps to Reproduce

see in summary


### Expected Results

rules are set, doens't matter if both keys `UseExistingClientSecret: True` and `ClientSecret`  are set

### Actual Results

see summary


### Code of Conduct

- [X] I agree to follow the Ansible Code of Conduct


Discussion:

Resolving patch:
diff --git a/plugins/module_utils/elbv2.py b/plugins/module_utils/elbv2.py
--- a/plugins/module_utils/elbv2.py
+++ b/plugins/module_utils/elbv2.py
@@ -107,6 +107,12 @@ def _prune_secret(action):
     if action["AuthenticateOidcConfig"].get("UseExistingClientSecret", False):
         action["AuthenticateOidcConfig"].pop("ClientSecret", None)
 
+    if not action["AuthenticateOidcConfig"].get("OnUnauthenticatedRequest", False):
+        action["AuthenticateOidcConfig"]["OnUnauthenticatedRequest"] = "authenticate"
+
+    if not action["AuthenticateOidcConfig"].get("SessionCookieName", False):
+        action["AuthenticateOidcConfig"]["SessionCookieName"] = "AWSELBAuthSessionCookie"
+
     return action
 
 
@@ -1010,10 +1016,7 @@ def __init__(self, connection, module, elb_arn, listener_rules, listener_port):
 
         # Get listener based on port so we can use ARN
         self.current_listener = get_elb_listener(connection, module, elb_arn, listener_port)
-        self.listener_arn = self.current_listener["ListenerArn"]
-        self.rules_to_add = deepcopy(self.rules)
-        self.rules_to_modify = []
-        self.rules_to_delete = []
+        self.listener_arn = self.current_listener.get("ListenerArn")
 
         # If the listener exists (i.e. has an ARN) get rules for the listener
         if "ListenerArn" in self.current_listener:
@@ -1141,8 +1144,9 @@ def _compare_rule(self, current_rule, new_rule):
         if len(current_rule["Actions"]) == len(new_rule["Actions"]):
             # if actions have just one element, compare the contents and then update if
             # they're different
+            copy_new_rule = deepcopy(new_rule)
             current_actions_sorted = _sort_actions(current_rule["Actions"])
-            new_actions_sorted = _sort_actions(new_rule["Actions"])
+            new_actions_sorted = _sort_actions(copy_new_rule["Actions"])
 
             new_current_actions_sorted = [_append_use_existing_client_secretn(i) for i in current_actions_sorted]
             new_actions_sorted_no_secret = [_prune_secret(i) for i in new_actions_sorted]
@@ -1175,10 +1179,41 @@ def compare_rules(self):
         rules_to_modify = []
         rules_to_delete = []
         rules_to_add = deepcopy(self.rules)
+        rules_to_set_priority = []
+
+        # List rules to update priority, 'Actions' and 'Conditions' remain the same
+        # only the 'Priority' has changed
+        current_rules = deepcopy(self.current_rules)
+        remaining_rules = []
+        while current_rules:
+            current_rule = current_rules.pop(0)
+            # Skip the default rule, this one can't be modified
+            if current_rule.get("IsDefault", False):
+                continue
+            to_keep = True
+            for new_rule in rules_to_add:
+                modified_rule = self._compare_rule(current_rule, new_rule)
+                if not modified_rule:
+                    # The current rule has been passed with the same properties to the module
+                    # Remove it for later comparison
+                    rules_to_add.remove(new_rule)
+                    to_keep = False
+                    break
+                if modified_rule and list(modified_rule.keys()) == ["Priority"]:
+                    # if only the Priority has changed
+                    modified_rule["Priority"] = int(new_rule["Priority"])
+                    modified_rule["RuleArn"] = current_rule["RuleArn"]
+
+                    rules_to_set_priority.append(modified_rule)
+                    to_keep = False
+                    rules_to_add.remove(new_rule)
+                    break
+            if to_keep:
+                remaining_rules.append(current_rule)
 
-        for current_rule in self.current_rules:
+        for current_rule in remaining_rules:
             current_rule_passed_to_module = False
-            for new_rule in self.rules[:]:
+            for new_rule in rules_to_add:
                 if current_rule["Priority"] == str(new_rule["Priority"]):
                     current_rule_passed_to_module = True
                     # Remove what we match so that what is left can be marked as 'to be added'
@@ -1189,14 +1224,24 @@ def compare_rules(self):
                         modified_rule["RuleArn"] = current_rule["RuleArn"]
                         modified_rule["Actions"] = new_rule["Actions"]
                         modified_rule["Conditions"] = new_rule["Conditions"]
+                        # You cannot both specify a client secret and set UseExistingClientSecret to true
+                        for action in modified_rule.get("Actions", []):
+                            if action.get("AuthenticateOidcConfig", {}).get("ClientSecret", False):
+                                action["AuthenticateOidcConfig"]["UseExistingClientSecret"] = False
                         rules_to_modify.append(modified_rule)
                     break
 
             # If the current rule was not matched against passed rules, mark for removal
-            if not current_rule_passed_to_module and not current_rule["IsDefault"]:
+            if not current_rule_passed_to_module and not current_rule.get("IsDefault", False):
                 rules_to_delete.append(current_rule["RuleArn"])
 
-        return rules_to_add, rules_to_modify, rules_to_delete
+        # For rules to create 'UseExistingClientSecret' should be set to False
+        for rule in rules_to_add:
+            for action in rule.get("Actions", []):
+                if action.get("AuthenticateOidcConfig", {}).get("UseExistingClientSecret", False):
+                    action["AuthenticateOidcConfig"]["UseExistingClientSecret"] = False
+
+        return rules_to_add, rules_to_modify, rules_to_delete, rules_to_set_priority
 
 
 class ELBListenerRule:
@@ -1251,3 +1296,21 @@ def delete(self):
             self.module.fail_json_aws(e)
 
         self.changed = True
+
+    def set_rule_priorities(self):
+        """
+        Sets the priorities of the specified rules.
+
+        :return:
+        """
+
+        try:
+            rules = [self.rule]
+            if isinstance(self.rule, list):
+                rules = self.rule
+            rule_priorities = [{"RuleArn": rule["RuleArn"], "Priority": rule["Priority"]} for rule in rules]
+            AWSRetry.jittered_backoff()(self.connection.set_rule_priorities)(RulePriorities=rule_priorities)
+        except (BotoCoreError, ClientError) as e:
+            self.module.fail_json_aws(e)
+
+        self.changed = True
diff --git a/plugins/modules/elb_application_lb.py b/plugins/modules/elb_application_lb.py
--- a/plugins/modules/elb_application_lb.py
+++ b/plugins/modules/elb_application_lb.py
@@ -680,12 +680,22 @@ def create_or_update_alb(alb_obj):
             rules_obj = ELBListenerRules(
                 alb_obj.connection, alb_obj.module, alb_obj.elb["LoadBalancerArn"], listener["Rules"], listener["Port"]
             )
-            rules_to_add, rules_to_modify, rules_to_delete = rules_obj.compare_rules()
+            rules_to_add, rules_to_modify, rules_to_delete, rules_to_set_priority = rules_obj.compare_rules()
 
             # Exit on check_mode
-            if alb_obj.module.check_mode and (rules_to_add or rules_to_modify or rules_to_delete):
+            if alb_obj.module.check_mode and (
+                rules_to_add or rules_to_modify or rules_to_delete or rules_to_set_priority
+            ):
                 alb_obj.module.exit_json(changed=True, msg="Would have updated ALB if not in check mode.")
 
+            # Set rules priorities
+            if rules_to_set_priority:
+                rule_obj = ELBListenerRule(
+                    alb_obj.connection, alb_obj.module, rules_to_set_priority, rules_obj.listener_arn
+                )
+                rule_obj.set_rule_priorities()
+                alb_obj.changed |= rule_obj.changed
+
             # Delete rules
             if alb_obj.module.params["purge_rules"]:
                 for rule in rules_to_delete:


Test patch:
diff --git a/tests/unit/module_utils/elbv2/test_listener_rules.py b/tests/unit/module_utils/elbv2/test_listener_rules.py
new file mode 100644
--- /dev/null
+++ b/tests/unit/module_utils/elbv2/test_listener_rules.py
@@ -0,0 +1,740 @@
+#
+# (c) 2024 Red Hat Inc.
+#
+# This file is part of Ansible
+# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
+
+from unittest.mock import MagicMock
+
+import pytest
+
+from ansible_collections.amazon.aws.plugins.module_utils import elbv2
+
+example_arn = "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/nlb-123456789abc/abcdef0123456789"
+example_arn2 = "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/nlb-0123456789ab/0123456789abcdef"
+
+
+test_rules = [
+    (
+        {
+            "Actions": [
+                {
+                    "AuthenticateOidcConfig": {
+                        "AuthorizationEndpoint": "https://samples.auth0.com/authorize",
+                        "ClientId": "kbyuFDidLLm280LIwVFiazOqjO3ty8KH",
+                        "Issuer": "https://samples.auth0.com",
+                        "Scope": "openid",
+                        "SessionTimeout": 604800,
+                        "TokenEndpoint": "https://samples.auth0.com/oauth/token",
+                        "UserInfoEndpoint": "https://samples.auth0.com/userinfo",
+                        "OnUnauthenticatedRequest": "authenticate",
+                        "SessionCookieName": "AWSELBAuthSessionCookie",
+                    },
+                    "Order": 1,
+                    "Type": "authenticate-oidc",
+                }
+            ],
+            "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+            "Priority": 2,
+        },
+        {
+            "Actions": [
+                {
+                    "AuthenticateOidcConfig": {
+                        "AuthorizationEndpoint": "https://samples.auth0.com/authorize",
+                        "ClientId": "kbyuFDidLLm280LIwVFiazOqjO3ty8KH",
+                        "Issuer": "https://samples.auth0.com",
+                        "Scope": "openid",
+                        "SessionTimeout": 604800,
+                        "TokenEndpoint": "https://samples.auth0.com/oauth/token",
+                        "UseExistingClientSecret": True,
+                        "UserInfoEndpoint": "https://samples.auth0.com/userinfo",
+                    },
+                    "Order": 1,
+                    "Type": "authenticate-oidc",
+                }
+            ],
+            "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+            "Priority": 2,
+        },
+        {},
+    ),
+    (
+        {
+            "Actions": [
+                {
+                    "AuthenticateOidcConfig": {
+                        "AuthorizationEndpoint": "https://samples.auth0.com/authorize",
+                        "ClientId": "kbyuFDidLLm280LIwVFiazOqjO3ty8KH",
+                        "Issuer": "https://samples.auth0.com",
+                        "Scope": "openid",
+                        "SessionTimeout": 604800,
+                        "TokenEndpoint": "https://samples.auth0.com/oauth/token",
+                        "UserInfoEndpoint": "https://samples.auth0.com/userinfo",
+                        "OnUnauthenticatedRequest": "authenticate",
+                        "SessionCookieName": "AWSELBAuthSessionCookie",
+                    },
+                    "Order": 1,
+                    "Type": "authenticate-oidc",
+                }
+            ],
+            "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+            "Priority": 2,
+        },
+        {
+            "Actions": [
+                {
+                    "AuthenticateOidcConfig": {
+                        "AuthorizationEndpoint": "https://samples.auth0.com/authorize",
+                        "ClientId": "kbyuFDidLLm280LIwVFiazOqjO3ty8KH",
+                        "Issuer": "https://samples.auth0.com",
+                        "Scope": "openid",
+                        "SessionTimeout": 604800,
+                        "TokenEndpoint": "https://samples.auth0.com/oauth/token",
+                        "UseExistingClientSecret": True,
+                        "UserInfoEndpoint": "https://samples.auth0.com/userinfo",
+                        "OnUnauthenticatedRequest": "authenticate",
+                    },
+                    "Order": 1,
+                    "Type": "authenticate-oidc",
+                }
+            ],
+            "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+            "Priority": 2,
+        },
+        {},
+    ),
+    (
+        {
+            "Actions": [
+                {
+                    "AuthenticateOidcConfig": {
+                        "AuthorizationEndpoint": "https://samples.auth0.com/authorize",
+                        "ClientId": "kbyuFDidLLm280LIwVFiazOqjO3ty8KH",
+                        "Issuer": "https://samples.auth0.com",
+                        "Scope": "openid",
+                        "SessionTimeout": 604800,
+                        "TokenEndpoint": "https://samples.auth0.com/oauth/token",
+                        "UserInfoEndpoint": "https://samples.auth0.com/userinfo",
+                        "OnUnauthenticatedRequest": "authenticate",
+                        "SessionCookieName": "AWSELBAuthSessionCookie",
+                    },
+                    "Order": 1,
+                    "Type": "authenticate-oidc",
+                }
+            ],
+            "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+            "Priority": 2,
+        },
+        {
+            "Actions": [
+                {
+                    "AuthenticateOidcConfig": {
+                        "AuthorizationEndpoint": "https://samples.auth0.com/authorize",
+                        "ClientId": "kbyuFDidLLm280LIwVFiazOqjO3ty8KH",
+                        "Issuer": "https://samples.auth0.com",
+                        "Scope": "openid",
+                        "SessionTimeout": 604800,
+                        "TokenEndpoint": "https://samples.auth0.com/oauth/token",
+                        "UseExistingClientSecret": True,
+                        "UserInfoEndpoint": "https://samples.auth0.com/userinfo",
+                        "OnUnauthenticatedRequest": "deny",
+                    },
+                    "Order": 1,
+                    "Type": "authenticate-oidc",
+                }
+            ],
+            "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+            "Priority": 2,
+        },
+        {
+            "Actions": [
+                {
+                    "AuthenticateOidcConfig": {
+                        "AuthorizationEndpoint": "https://samples.auth0.com/authorize",
+                        "ClientId": "kbyuFDidLLm280LIwVFiazOqjO3ty8KH",
+                        "Issuer": "https://samples.auth0.com",
+                        "Scope": "openid",
+                        "SessionTimeout": 604800,
+                        "TokenEndpoint": "https://samples.auth0.com/oauth/token",
+                        "UseExistingClientSecret": True,
+                        "UserInfoEndpoint": "https://samples.auth0.com/userinfo",
+                        "OnUnauthenticatedRequest": "deny",
+                    },
+                    "Order": 1,
+                    "Type": "authenticate-oidc",
+                }
+            ],
+        },
+    ),
+    (
+        {
+            "Actions": [{"TargetGroupName": "my_target_group", "Type": "forward"}],
+            "Conditions": [{"Field": "path-pattern", "Values": ["/test", "/prod"]}],
+            "Priority": 2,
+        },
+        {
+            "Actions": [{"TargetGroupName": "my_target_group", "Type": "forward"}],
+            "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+            "Priority": 2,
+        },
+        {
+            "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+        },
+    ),
+]
+
+
+@pytest.mark.parametrize("current_rule,new_rule,modified_rule", test_rules)
+def test__compare_rule(mocker, current_rule, new_rule, modified_rule):
+    mocker.patch(
+        "ansible_collections.amazon.aws.plugins.module_utils.elbv2.ELBListenerRules._get_elb_listener_rules"
+    ).return_value = MagicMock()
+    mocker.patch(
+        "ansible_collections.amazon.aws.plugins.module_utils.elbv2.get_elb_listener"
+    ).return_value = MagicMock()
+    module = MagicMock()
+    connection = MagicMock()
+    elb_arn = MagicMock()
+
+    elb_listener_rules = elbv2.ELBListenerRules(connection, module, elb_arn, [], [])
+
+    assert modified_rule == elb_listener_rules._compare_rule(current_rule, new_rule)
+
+
+test_listeners_rules = [
+    (
+        [
+            {
+                "Priority": "1",
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/abc",
+            },
+            {
+                "Priority": "2",
+                "Conditions": [{"Field": "host-header", "Values": ["yolo.rocks"]}],
+                "Actions": [{"TargetGroupName": "target2", "Type": "forward"}],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/123",
+            },
+        ],
+        [
+            {
+                "Priority": 2,
+                "Conditions": [{"Field": "host-header", "Values": ["yolo.rocks"]}],
+                "Actions": [{"TargetGroupName": "target2", "Type": "forward"}],
+            },
+            {
+                "Priority": 1,
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+            },
+        ],
+        {},
+    ),
+    (
+        [
+            {
+                "Priority": "1",
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/abc",
+            },
+            {
+                "Priority": "2",
+                "Conditions": [{"Field": "host-header", "Values": ["yolo.rocks"]}],
+                "Actions": [{"TargetGroupName": "target2", "Type": "forward"}],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/123",
+            },
+        ],
+        [
+            {
+                "Priority": 1,
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+            },
+            {
+                "Priority": 2,
+                "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+                "Actions": [
+                    {"TargetGroupName": "oidc-target-01", "Type": "forward", "Order": 2},
+                    {
+                        "Type": "authenticate-oidc",
+                        "Order": 1,
+                        "AuthenticateOidcConfig": {
+                            "Issuer": "https://sample.oauth.com/issuer",
+                            "AuthorizationEndpoint": "https://sample.oauth.com",
+                            "TokenEndpoint": "https://sample.oauth.com/oauth/token",
+                            "UserInfoEndpoint": "https://sample.oauth.com/userinfo",
+                            "ClientId": "id123645",
+                            "ClientSecret": "testSecret123!@#$",
+                            "UseExistingClientSecret": True,
+                        },
+                    },
+                ],
+            },
+            {
+                "Priority": 3,
+                "Conditions": [{"Field": "host-header", "Values": ["yolo.rocks"]}],
+                "Actions": [{"TargetGroupName": "target2", "Type": "forward"}],
+            },
+        ],
+        {
+            "to_set_priority": [
+                {
+                    "Priority": 3,
+                    "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/123",
+                }
+            ],
+            "to_add": [
+                {
+                    "Priority": 2,
+                    "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+                    "Actions": [
+                        {"TargetGroupName": "oidc-target-01", "Type": "forward", "Order": 2},
+                        {
+                            "Type": "authenticate-oidc",
+                            "Order": 1,
+                            "AuthenticateOidcConfig": {
+                                "Issuer": "https://sample.oauth.com/issuer",
+                                "AuthorizationEndpoint": "https://sample.oauth.com",
+                                "TokenEndpoint": "https://sample.oauth.com/oauth/token",
+                                "UserInfoEndpoint": "https://sample.oauth.com/userinfo",
+                                "ClientId": "id123645",
+                                "ClientSecret": "testSecret123!@#$",
+                                "UseExistingClientSecret": False,
+                            },
+                        },
+                    ],
+                },
+            ],
+        },
+    ),
+    (
+        [
+            {
+                "Priority": "2",
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/abc",
+            },
+            {
+                "Priority": "1",
+                "Conditions": [{"Field": "host-header", "Values": ["yolo.rocks"]}],
+                "Actions": [{"TargetGroupName": "target2", "Type": "forward"}],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/123",
+            },
+        ],
+        [
+            {
+                "Priority": 2,
+                "Conditions": [{"Field": "host-header", "Values": ["yolo.rocks"]}],
+                "Actions": [{"TargetGroupName": "target2", "Type": "forward"}],
+            },
+            {
+                "Priority": 1,
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+            },
+        ],
+        {
+            "to_set_priority": [
+                {
+                    "Priority": 2,
+                    "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/123",
+                },
+                {
+                    "Priority": 1,
+                    "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/abc",
+                },
+            ]
+        },
+    ),
+    (
+        [
+            {
+                "Priority": "1",
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/abc",
+            },
+            {
+                "Priority": "2",
+                "Conditions": [{"Field": "host-header", "Values": ["yolo.rocks"]}],
+                "Actions": [{"TargetGroupName": "target2", "Type": "forward"}],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/123",
+            },
+        ],
+        [
+            {
+                "Priority": 1,
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+            },
+            {
+                "Priority": 2,
+                "Conditions": [{"Field": "host-header", "Values": ["yolo.rocks"]}],
+                "Actions": [{"TargetGroupName": "target2", "Type": "forward"}],
+            },
+            {
+                "Priority": 3,
+                "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+                "Actions": [
+                    {"TargetGroupName": "oidc-target-01", "Type": "forward", "Order": 2},
+                    {
+                        "Type": "authenticate-oidc",
+                        "Order": 1,
+                        "AuthenticateOidcConfig": {
+                            "Issuer": "https://sample.oauth.com/issuer",
+                            "AuthorizationEndpoint": "https://sample.oauth.com",
+                            "TokenEndpoint": "https://sample.oauth.com/oauth/token",
+                            "UserInfoEndpoint": "https://sample.oauth.com/userinfo",
+                            "ClientId": "id123645",
+                            "ClientSecret": "testSecret123!@#$",
+                            "UseExistingClientSecret": True,
+                        },
+                    },
+                ],
+            },
+        ],
+        {
+            "to_add": [
+                {
+                    "Priority": 3,
+                    "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+                    "Actions": [
+                        {"TargetGroupName": "oidc-target-01", "Type": "forward", "Order": 2},
+                        {
+                            "Type": "authenticate-oidc",
+                            "Order": 1,
+                            "AuthenticateOidcConfig": {
+                                "Issuer": "https://sample.oauth.com/issuer",
+                                "AuthorizationEndpoint": "https://sample.oauth.com",
+                                "TokenEndpoint": "https://sample.oauth.com/oauth/token",
+                                "UserInfoEndpoint": "https://sample.oauth.com/userinfo",
+                                "ClientId": "id123645",
+                                "ClientSecret": "testSecret123!@#$",
+                                "UseExistingClientSecret": False,
+                            },
+                        },
+                    ],
+                },
+            ]
+        },
+    ),
+    (
+        [
+            {
+                "Priority": "1",
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/abc",
+            },
+        ],
+        [
+            {
+                "Priority": 1,
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+            },
+            {
+                "Priority": 2,
+                "Conditions": [{"Field": "host-header", "Values": ["yolo.rocks"]}],
+                "Actions": [{"TargetGroupName": "target2", "Type": "forward"}],
+            },
+        ],
+        {
+            "to_add": [
+                {
+                    "Priority": 2,
+                    "Conditions": [{"Field": "host-header", "Values": ["yolo.rocks"]}],
+                    "Actions": [{"TargetGroupName": "target2", "Type": "forward"}],
+                },
+            ]
+        },
+    ),
+    (
+        [
+            {
+                "Priority": "1",
+                "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+                "Actions": [
+                    {"TargetGroupName": "oidc-target-01", "Type": "forward", "Order": 2},
+                    {
+                        "Type": "authenticate-oidc",
+                        "Order": 1,
+                        "AuthenticateOidcConfig": {
+                            "Issuer": "https://sample.oauth.com/issuer",
+                            "AuthorizationEndpoint": "https://sample.oauth.com",
+                            "TokenEndpoint": "https://sample.oauth.com/oauth/token",
+                            "UserInfoEndpoint": "https://sample.oauth.com/userinfo",
+                            "ClientId": "id123645",
+                        },
+                    },
+                ],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/oidc",
+            },
+        ],
+        [
+            {
+                "Priority": 1,
+                "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+                "Actions": [
+                    {"TargetGroupName": "oidc-target-01", "Type": "forward", "Order": 2},
+                    {
+                        "Type": "authenticate-oidc",
+                        "Order": 1,
+                        "AuthenticateOidcConfig": {
+                            "Issuer": "https://sample.oauth.com/issuer",
+                            "AuthorizationEndpoint": "https://sample.oauth.com",
+                            "TokenEndpoint": "https://sample.oauth.com/oauth/token",
+                            "UserInfoEndpoint": "https://sample.oauth.com/userinfo",
+                            "ClientId": "id123645",
+                            "ClientSecret": "testSecret123!@#$",
+                            "UseExistingClientSecret": True,
+                        },
+                    },
+                ],
+            }
+        ],
+        {
+            "to_modify": [
+                {
+                    "Priority": 1,
+                    "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+                    "Actions": [
+                        {"TargetGroupName": "oidc-target-01", "Type": "forward", "Order": 2},
+                        {
+                            "Type": "authenticate-oidc",
+                            "Order": 1,
+                            "AuthenticateOidcConfig": {
+                                "Issuer": "https://sample.oauth.com/issuer",
+                                "AuthorizationEndpoint": "https://sample.oauth.com",
+                                "TokenEndpoint": "https://sample.oauth.com/oauth/token",
+                                "UserInfoEndpoint": "https://sample.oauth.com/userinfo",
+                                "ClientId": "id123645",
+                                "ClientSecret": "testSecret123!@#$",
+                                "UseExistingClientSecret": False,
+                            },
+                        },
+                    ],
+                    "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/oidc",
+                },
+            ]
+        },
+    ),
+    (
+        [
+            {
+                "Priority": "1",
+                "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+                "Actions": [
+                    {
+                        "Type": "authenticate-oidc",
+                        "Order": 1,
+                        "AuthenticateOidcConfig": {
+                            "Issuer": "https://sample.oauth.com/issuer",
+                            "AuthorizationEndpoint": "https://sample.oauth.com",
+                            "TokenEndpoint": "https://sample.oauth.com/oauth/token",
+                            "UserInfoEndpoint": "https://sample.oauth.com/userinfo",
+                            "ClientId": "kbyuFDidLLm280LIwVFiazOqjO3ty8KH",
+                        },
+                    },
+                ],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/oidc",
+            },
+        ],
+        [
+            {
+                "Priority": 1,
+                "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+                "Actions": [
+                    {
+                        "Type": "authenticate-oidc",
+                        "Order": 1,
+                        "AuthenticateOidcConfig": {
+                            "Issuer": "https://sample.oauth.com/issuer",
+                            "AuthorizationEndpoint": "https://sample.oauth.com",
+                            "TokenEndpoint": "https://sample.oauth.com/oauth/token",
+                            "UserInfoEndpoint": "https://sample.oauth.com/userinfo",
+                            "ClientId": "kbyuFDidLLm280LIwVFiazOqjO3ty8KH",
+                            "ClientSecret": "testSecret123!@#$",
+                        },
+                    },
+                ],
+            }
+        ],
+        {
+            "to_modify": [
+                {
+                    "Priority": 1,
+                    "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+                    "Actions": [
+                        {
+                            "Type": "authenticate-oidc",
+                            "Order": 1,
+                            "AuthenticateOidcConfig": {
+                                "Issuer": "https://sample.oauth.com/issuer",
+                                "AuthorizationEndpoint": "https://sample.oauth.com",
+                                "TokenEndpoint": "https://sample.oauth.com/oauth/token",
+                                "UserInfoEndpoint": "https://sample.oauth.com/userinfo",
+                                "ClientId": "kbyuFDidLLm280LIwVFiazOqjO3ty8KH",
+                                "ClientSecret": "testSecret123!@#$",
+                                "UseExistingClientSecret": False,
+                            },
+                        },
+                    ],
+                    "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/oidc",
+                },
+            ]
+        },
+    ),
+    (
+        [
+            {
+                "Priority": "1",
+                "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+                "Actions": [
+                    {
+                        "Type": "authenticate-oidc",
+                        "Order": 1,
+                        "AuthenticateOidcConfig": {
+                            "AuthorizationEndpoint": "https://samples.auth0.com/authorize",
+                            "ClientId": "abcdef1234567890",
+                            "Issuer": "https://samples.auth0.com/",
+                            "OnUnauthenticatedRequest": "authenticate",
+                            "Scope": "openid",
+                            "SessionCookieName": "AWSELBAuthSessionCookie",
+                            "SessionTimeout": 604800,
+                            "TokenEndpoint": "https://samples.auth0.com/oauth/token",
+                            "UserInfoEndpoint": "https://samples.auth0.com/oauth/userinfo",
+                        },
+                    },
+                ],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/oidc",
+            },
+        ],
+        [
+            {
+                "Priority": 1,
+                "Conditions": [{"Field": "path-pattern", "Values": ["/test"]}],
+                "Actions": [
+                    {
+                        "Type": "authenticate-oidc",
+                        "Order": 1,
+                        "AuthenticateOidcConfig": {
+                            "AuthorizationEndpoint": "https://samples.auth0.com/authorize",
+                            "ClientId": "abcdef1234567890",
+                            "Issuer": "https://samples.auth0.com/",
+                            "OnUnauthenticatedRequest": "authenticate",
+                            "Scope": "openid",
+                            "TokenEndpoint": "https://samples.auth0.com/oauth/token",
+                            "UserInfoEndpoint": "https://samples.auth0.com/oauth/userinfo",
+                            "UseExistingClientSecret": True,
+                        },
+                    },
+                ],
+            }
+        ],
+        {},
+    ),
+    (
+        [
+            {
+                "Priority": "default",
+                "IsDefault": True,
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/default",
+            },
+            {
+                "Priority": "1",
+                "IsDefault": False,
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/rule-1",
+            },
+        ],
+        [
+            {
+                "Priority": 1,
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "another_target", "Type": "forward"}],
+            },
+        ],
+        {
+            "to_modify": [
+                {
+                    "Priority": 1,
+                    "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                    "Actions": [{"TargetGroupName": "another_target", "Type": "forward"}],
+                    "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/rule-1",
+                },
+            ]
+        },
+    ),
+    (
+        [
+            {
+                "Priority": "default",
+                "IsDefault": True,
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/default",
+            },
+            {
+                "Priority": "1",
+                "IsDefault": False,
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+                "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/rule-1",
+            },
+        ],
+        [
+            {
+                "Priority": 2,
+                "Conditions": [{"Field": "host-header", "Values": ["bla.tld"]}],
+                "Actions": [{"TargetGroupName": "target1", "Type": "forward"}],
+            },
+        ],
+        {
+            "to_set_priority": [
+                {
+                    "Priority": 2,
+                    "RuleArn": "arn:aws:elasticloadbalancing:::listener-rule/app/ansible-test/rule-1",
+                },
+            ]
+        },
+    ),
+]
+
+
+@pytest.mark.parametrize("current_rules,rules,expected", test_listeners_rules)
+def test_compare_rules(mocker, current_rules, rules, expected):
+    mocker.patch(
+        "ansible_collections.amazon.aws.plugins.module_utils.elbv2.get_elb_listener"
+    ).return_value = MagicMock()
+    mocker.patch(
+        "ansible_collections.amazon.aws.plugins.module_utils.elbv2.ELBListenerRules._ensure_rules_action_has_arn"
+    ).return_value = rules
+    mocker.patch(
+        "ansible_collections.amazon.aws.plugins.module_utils.elbv2.ELBListenerRules._get_elb_listener_rules"
+    ).return_value = current_rules
+    module = MagicMock()
+    connection = MagicMock()
+    elb_arn = MagicMock()
+
+    elb_listener_rules = elbv2.ELBListenerRules(connection, module, elb_arn, rules, 8009)
+    elb_listener_rules.current_rules = current_rules
+    rules_to_add, rules_to_modify, rules_to_delete, rules_to_set_priority = elb_listener_rules.compare_rules()
+
+    assert sorted(rules_to_add, key=lambda x: x.get("Priority", 0)) == sorted(
+        expected.get("to_add", []), key=lambda x: x.get("Priority", 0)
+    )
+    assert sorted(rules_to_modify, key=lambda x: x.get("Priority", 0)) == sorted(
+        expected.get("to_modify", []), key=lambda x: x.get("Priority", 0)
+    )
+    assert sorted(rules_to_set_priority, key=lambda x: x.get("Priority", 0)) == sorted(
+        expected.get("to_set_priority", []), key=lambda x: x.get("Priority", 0)
+    )
+    assert sorted(rules_to_delete) == sorted(expected.get("to_delete", []))
diff --git a/tests/unit/module_utils/elbv2/test_prune.py b/tests/unit/module_utils/elbv2/test_prune.py
--- a/tests/unit/module_utils/elbv2/test_prune.py
+++ b/tests/unit/module_utils/elbv2/test_prune.py
@@ -153,6 +153,8 @@
         Scope="openid",
         SessionTimeout=604800,
         UseExistingClientSecret=True,
+        OnUnauthenticatedRequest="authenticate",
+        SessionCookieName="AWSELBAuthSessionCookie",
     ),
 )
 oidc_actions = [