From 56833b4be4214537139626967de9b8e814be6875 Mon Sep 17 00:00:00 2001
From: Benjamin Gandon <bgandon@users.noreply.github.com>
Date: Tue, 9 Jan 2024 16:35:11 +0100
Subject: [PATCH] Fix 404 errors when creating key with misspelled service
 account

---
 changelogs/fragments/fix-sa-key-create.yml     | 4 ++++
 plugins/modules/gcp_iam_service_account_key.py | 6 +++++-
 2 files changed, 9 insertions(+), 1 deletion(-)
 create mode 100644 changelogs/fragments/fix-sa-key-create.yml

diff --git a/changelogs/fragments/fix-sa-key-create.yml b/changelogs/fragments/fix-sa-key-create.yml
new file mode 100644
index 0000000..8f80405
--- /dev/null
+++ b/changelogs/fragments/fix-sa-key-create.yml
@@ -0,0 +1,4 @@
+bugfixes:
+  - gcp_iam_service_account_key - properly raise an error with context when no
+    service account of the specified name exists, instead of failing with a
+    stacktrace.
diff --git a/plugins/modules/gcp_iam_service_account_key.py b/plugins/modules/gcp_iam_service_account_key.py
index a34718d..11359b4 100644
--- a/plugins/modules/gcp_iam_service_account_key.py
+++ b/plugins/modules/gcp_iam_service_account_key.py
@@ -255,7 +255,11 @@ def main():
 
 def create(module):
     auth = GcpSession(module, 'iam')
-    json_content = return_if_object(module, auth.post(self_link(module), resource_to_request(module)))
+    response = auth.post(self_link(module), resource_to_request(module))
+    if response.status_code == 404:
+        name = replace_resource_dict(module.params['service_account'], 'name')
+        module.fail_json(msg="No such Service Account: %s" % name)
+    json_content = return_if_object(module, response)
     with open(module.params['path'], 'w') as f:
         private_key_contents = to_native(base64.b64decode(json_content['privateKeyData']))
         f.write(private_key_contents)