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:
@markuman I can't reproduce the issue when modifying the existing load balancer rule.
The only issue I can reproduce is when creating a new load balancer rule using both `UseExistingClientSecret=true` and `ClientSecret`

```
The error was: botocore.errorfactory.InvalidLoadBalancerActionException: An error occurred (InvalidLoadBalancerAction) when calling the CreateRule operation: You cannot both specify a client secret and set UseExistingClientSecret to true
```
However this has been fixed using #1956 

Could you please provide a full sequence on how to reproduce the issue ?
Here is the playbook I used to reproduce

```yaml
- name: Create an ALB with different listener by adding rule
  amazon.aws.elb_application_lb:
    name: sample-lb
    subnets: 
      - subnet-xxxxxxxxxxxxxxxxx
      - subnet-xxxxxxxxxxxxxxxxx
    security_groups: sg-xxxxxxxxxxxxxx
    state: present
    listeners:
      - Protocol: HTTPS
        Port: 443
        Certificates:
          - CertificateArn: arn:aws:iam::0123456789:server-certificate/ansible-test-xxxxxxxxxxx
        SslPolicy: ELBSecurityPolicy-TLS13-1-2-2021-06
        DefaultActions:
          - Type: forward
            TargetGroupName: test-target-01
        Rules:
          - Priority: 1
            Conditions:
              - Field: path-pattern
                Values:
                  - /test
            Actions:
              - TargetGroupName: test-target-01
                Type: forward
                Order: 2
              - Type: authenticate-oidc
                Order: 1
                AuthenticateOidcConfig:
                  Issuer: https://xxxxxxxxxxx
                  AuthorizationEndpoint: https://xxxxxxxxxxxxxx
                  TokenEndpoint: https://xxxxxxxxxxxxxx/oauth/token
                  UserInfoEndpoint: https://xxxxxxxxxxxxx/userinfo
                  ClientId: myclientid123645
                  ClientSecret: abcdefghigjth1233
                  UseExistingClientSecret: True
```



The modified rule is correct returned at line 1186: https://github.com/ansible-collections/amazon.aws/blob/main/plugins/module_utils/elbv2.py#L1186  
The key `ClientSecret` is popped, because `UseExistingClientSecret` is set to `True`.

To make it visible, I add some `q` debugging lines.

```diff
diff --git a/plugins/module_utils/elbv2.py b/plugins/module_utils/elbv2.py
index 429d5f7c..e69615f1 100644
--- a/plugins/module_utils/elbv2.py
+++ b/plugins/module_utils/elbv2.py
@@ -95,8 +95,12 @@ def _prune_ForwardConfig(action):
 # remove the client secret if UseExistingClientSecret, because aws won't return it
 # add default values when they are not requested
 def _prune_secret(action):
+    import q
+
     if action["Type"] != "authenticate-oidc":
         return action
+    else:
+        q(action)
 
     if not action["AuthenticateOidcConfig"].get("Scope", False):
         action["AuthenticateOidcConfig"]["Scope"] = "openid"
@@ -105,7 +109,9 @@ def _prune_secret(action):
         action["AuthenticateOidcConfig"]["SessionTimeout"] = 604800
 
     if action["AuthenticateOidcConfig"].get("UseExistingClientSecret", False):
+        q("must be popped")
         action["AuthenticateOidcConfig"].pop("ClientSecret", None)
+        q(action)
 
     return action
 
@@ -1131,7 +1137,7 @@ class ELBListenerRules:
 
         :return:
         """
-
+        import q
         rules_to_modify = []
         rules_to_delete = []
         rules_to_add = deepcopy(self.rules)
@@ -1147,6 +1153,7 @@ class ELBListenerRules:
                     if modified_rule:
                         modified_rule["Priority"] = int(current_rule["Priority"])
                         modified_rule["RuleArn"] = current_rule["RuleArn"]
+                        q("prune secret will be reverted here")
                         modified_rule["Actions"] = new_rule["Actions"]
                         modified_rule["Conditions"] = new_rule["Conditions"]
                         rules_to_modify.append(modified_rule)
@@ -1155,7 +1162,7 @@ class ELBListenerRules:
             # 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"]:
                 rules_to_delete.append(current_rule["RuleArn"])
-
+        q(rules_to_modify)
         return rules_to_add, rules_to_modify, rules_to_delete
```

And after that, in Line 1190, the modified rule, where the `ClientSecret` was popped (_because it is necessary_), it is reverted by taken the requested rule again. So the popped `ClientSecret` is in place again and both - `ClientSecret` And `UseExistingClientSecret: True` is requested against boto3.

```
 4.2s _prune_secret: 
      action={'AuthenticateOidcConfig': {'AuthorizationEndpoint': 'https://login.microsoftonline.com/123/oauth2/v2.0/authorize', 'ClientId': 'ABClientID', 'ClientSecret': 'xxx', 'Issuer': 'https://login.microsoftonline.com/123/v2.0', 'OnUnauthenticatedRequest': 'authenticate', 'SessionCookieName': 'AWSELBAuthSessionCookie', 'TokenEndpoint': 'https://login.microsoftonline.com/123/oauth2/v2.0/token', 'UseExistingClientSecret': True, 'UserInfoEndpoint': 'https://graph.microsoft.com/oidc/userinfo'}, 'Order': 1, 'Type': 'authenticate-oidc'}
 4.2s _prune_secret: "must be popped"='must be popped'
 4.2s _prune_secret: 
      action={'AuthenticateOidcConfig': {'AuthorizationEndpoint': 'https://login.microsoftonline.com/123/oauth2/v2.0/authorize', 'ClientId': 'ABClientID', 'Issuer': 'https://login.microsoftonline.com/123/v2.0', 'OnUnauthenticatedRequest': 'authenticate', 'Scope': 'openid', 'SessionCookieName': 'AWSELBAuthSessionCookie', 'SessionTimeout': 604800, 'TokenEndpoint': 'https://login.microsoftonline.com/123/oauth2/v2.0/token', 'UseExistingClientSecret': True, 'UserInfoEndpoint': 'https://graph.microsoft.com/oidc/userinfo'}, 'Order': 1, 'Type': 'authenticate-oidc'}
 4.2s compare_rules: 
      "prune secret will be reverted here"='prune secret will be reverted here'
 4.2s compare_rules: 
      "prune secret will be reverted here"='prune secret will be reverted here'
 4.2s compare_rules: 
      rules_to_modify=[{'Actions': [{'AuthenticateOidcConfig': {'AuthorizationEndpoint': 'https://login.microsoftonline.com/123/oauth2/v2.0/authorize', 'ClientId': 'ABClientID', 'ClientSecret': 'xxx', 'Issuer': 'https://login.microsoftonline.com/123/v2.0', 'OnUnauthenticatedRequest': 'authenticate', 'SessionCookieName': 'AWSELBAuthSessionCookie', 'TokenEndpoint': 'https://login.microsoftonline.com/123/oauth2/v2.0/token', 'UseExistingClientSecret': True, 'UserInfoEndpoint': 'https://graph.microsoft.com/oidc/userinfo'}, 'Order': 1, 'Type': 'authenticate-oidc'}, {'Order': 2, 'TargetGroupArn': 'arn:aws:elasticloadbalancing:eu-central-1:111:targetgroup/extern/c68839a5495', 'Type': 'forward'}], 'Conditions': [{'Field': 'host-header', 'Values': ['something1.lekker.de', 'something.lekker.de']}, {'Field': 'path-pattern', 'Values': ['/be.php/*']}], 'Priority': 25, 'RuleArn': 'arn:aws:elasticloadbalancing:eu-central-1:111:listener-rule/app/lekker/fba205cf17b1/c2a8d42098/7922f23be698'}, {'Actions': [{'TargetGroupArn': 'arn:aws:elasticloadbalancing:eu-central-1:111:targetgroup/ecs-energieladen-extern/dd40d9226b35', 'Type': 'forward'}], 'Conditions': [{'Field': 'path-pattern', 'Values': ['/wp-*']}], 'Priority': 47, 'RuleArn': 'arn:aws:elasticloadbalancing:eu-central-1:111:listener-rule/app/lekker/fba205cf17b9a51/c2a8420d798/eee95bdede5f529b'}]
```
Okey, the issue is a kind different.

The rule was detected as a modified rule, but it was a new one.  
Why? Because it was added somewhere in the middle fo the rules list and ansible just used the `priority` key to say if a rule is a modified or a new rule https://github.com/ansible-collections/amazon.aws/blob/main/plugins/module_utils/elbv2.py#L1182

This case is **not** solveable!

But when the rule is added at the end of the rules list, it becomes a new rule (_priority that does not exist yet_), the module runs into a hen-egg problem.   
You want to commit the rule with `UseExistingClientSecret: True`  to become immutable for multiple runs of your playbook, you'll run into the same error 

> "msg": "An error occurred (InvalidLoadBalancerAction) when calling the ModifyRule operation: You cannot both specify a client secret and set UseExistingClientSecret to true

When 

1. Rule is from action type `authenticate-oidc` **AND**
2. Rule is a new one (`rules_to_add`)
 
then ` UseExistingClientSecret` must be set to `False`, no matter what was requested.

So to reproduce it you need to first apply this

```yml
- name: Create an ALB with different listener by adding rule
  amazon.aws.elb_application_lb:
    name: sample-lb
    subnets: 
      - subnet-xxxxxxxxxxxxxxxxx
      - subnet-xxxxxxxxxxxxxxxxx
    security_groups: sg-xxxxxxxxxxxxxx
    state: present
    listeners:
      - Protocol: HTTPS
        Port: 443
        Certificates:
          - CertificateArn: arn:aws:iam::0123456789:server-certificate/ansible-test-xxxxxxxxxxx
        SslPolicy: ELBSecurityPolicy-TLS13-1-2-2021-06
        DefaultActions:
          - Type: forward
            TargetGroupName: test-target-01
        Rules:
          - Priority: 1
            Conditions:
              - Field: host-header
                Values:
                  - bla.tld
            Actions:
              - TargetGroupName: somewhere
                Type: forward
          - Priority: 2
            Conditions:
              - Field: host-header
                Values:
                  - yolo.rocks
            Actions:
              - TargetGroupName: yeah
                Type: forward
```

and then modify it like that

```yml
- name: Create an ALB with different listener by adding rule
  amazon.aws.elb_application_lb:
    name: sample-lb
    subnets: 
      - subnet-xxxxxxxxxxxxxxxxx
      - subnet-xxxxxxxxxxxxxxxxx
    security_groups: sg-xxxxxxxxxxxxxx
    state: present
    listeners:
      - Protocol: HTTPS
        Port: 443
        Certificates:
          - CertificateArn: arn:aws:iam::0123456789:server-certificate/ansible-test-xxxxxxxxxxx
        SslPolicy: ELBSecurityPolicy-TLS13-1-2-2021-06
        DefaultActions:
          - Type: forward
            TargetGroupName: test-target-01
        Rules:
          - Priority: 1
            Conditions:
              - Field: host-header
                Values:
                  - bla.tld
            Actions:
              - TargetGroupName: somewhere
                Type: forward
          - Priority: 2
            Conditions:
              - Field: path-pattern
                Values:
                  - /test
            Actions:
              - TargetGroupName: test-target-01
                Type: forward
                Order: 2
              - Type: authenticate-oidc
                Order: 1
                AuthenticateOidcConfig:
                  Issuer: https://xxxxxxxxxxx
                  AuthorizationEndpoint: https://xxxxxxxxxxxxxx
                  TokenEndpoint: https://xxxxxxxxxxxxxx/oauth/token
                  UserInfoEndpoint: https://xxxxxxxxxxxxx/userinfo
                  ClientId: myclientid123645
                  ClientSecret: abcdefghigjth1233
                  UseExistingClientSecret: True
          - Priority: 3
            Conditions:
              - Field: host-header
                Values:
                  - yolo.rocks
            Actions:
              - TargetGroupName: yeah
                Type: forward
```
@markuman I have updated PR #1956 to fix this test case.
Could you please validate if it is working as expected using #1956? Thanks
> @markuman I have updated PR #1956 to fix this test case. Could you please validate if it is working as expected using #1956? Thanks

No, it does not solve the issue.  
When you add an new `authenticate-oidc` rule in the middle of your existing rules, .... the rule is still detected as a changed one (because comparison is based on priority number), but strictly speaking, it is a new one. 
> When
> 
>     1. Rule is from action type `authenticate-oidc` **AND**
> 
>     2. Rule is a new one (`rules_to_add`)
> 
> 
> then ` UseExistingClientSecret` must be set to `False`, no matter what was requested.

this still failed with your branch, when adding a new rule to existing ALB at the  end (priority number + 1).
@markuman I just realized that there is an API to update the Rule priority, this will be used when the rule has just changed the priority but all the other properties remain the same. This will fix the use case where an `authenticate-oidc` rule is inserted in the middle of existing rules.


> > When
> > ```
> > 1. Rule is from action type `authenticate-oidc` **AND**
> > 
> > 2. Rule is a new one (`rules_to_add`)
> > ```
> > 
> > 
> >     
> >       
> >     
> > 
> >       
> >     
> > 
> >     
> >   
> > then ` UseExistingClientSecret` must be set to `False`, no matter what was requested.
> 
> this still failed with your branch, when adding a new rule to existing ALB at the end (priority number + 1).

This has also been fixed.

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
 
 
@@ -970,10 +976,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:
@@ -1101,8 +1104,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]
@@ -1135,10 +1139,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'
@@ -1149,14 +1184,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:
@@ -1211,3 +1256,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
@@ -657,12 +657,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 = [