From 9dd2b71d043e89f9918fdf2ccda22674ef25a66a Mon Sep 17 00:00:00 2001
From: Art Win <art@make.lv>
Date: Sun, 14 Jul 2024 13:59:12 +0200
Subject: [PATCH] nsupdate: fix 'index out of range' error when changing NS
 records (#8614)

* nsupdate: fix 'index out of range' error when changing NS records

* add clog fragment

* Update changelogs/fragments/8614-nsupdate-index-out-of-range.yml

Co-authored-by: Felix Fontein <felix@fontein.de>

---------

Co-authored-by: Felix Fontein <felix@fontein.de>
---
 changelogs/fragments/8614-nsupdate-index-out-of-range.yml | 2 ++
 plugins/modules/nsupdate.py                               | 3 ++-
 2 files changed, 4 insertions(+), 1 deletion(-)
 create mode 100644 changelogs/fragments/8614-nsupdate-index-out-of-range.yml

diff --git a/changelogs/fragments/8614-nsupdate-index-out-of-range.yml b/changelogs/fragments/8614-nsupdate-index-out-of-range.yml
new file mode 100644
index 0000000000..00b6f8b974
--- /dev/null
+++ b/changelogs/fragments/8614-nsupdate-index-out-of-range.yml
@@ -0,0 +1,2 @@
+bugfixes:
+  - "nsupdate - fix 'index out of range' error when changing NS records by falling back to authority section of the response (https://github.com/ansible-collections/community.general/issues/8612, https://github.com/ansible-collections/community.general/pull/8614)."
diff --git a/plugins/modules/nsupdate.py b/plugins/modules/nsupdate.py
index 63750165ca..c9a6ba2133 100644
--- a/plugins/modules/nsupdate.py
+++ b/plugins/modules/nsupdate.py
@@ -370,7 +370,8 @@ class RecordManager(object):
             except (socket_error, dns.exception.Timeout) as e:
                 self.module.fail_json(msg='DNS server error: (%s): %s' % (e.__class__.__name__, to_native(e)))
 
-            entries_to_remove = [n.to_text() for n in lookup.answer[0].items if n.to_text() not in self.value]
+            lookup_result = lookup.answer[0] if lookup.answer else lookup.authority[0]
+            entries_to_remove = [n.to_text() for n in lookup_result.items if n.to_text() not in self.value]
         else:
             update.delete(self.module.params['record'], self.module.params['type'])