From ad93c40d409076e1c2d01cf7e6bd1ffa21af5132 Mon Sep 17 00:00:00 2001
From: "patchback[bot]" <45432694+patchback[bot]@users.noreply.github.com>
Date: Thu, 28 Oct 2021 20:19:54 +0200
Subject: [PATCH] fix gitlab_deploy_key task in check mode (#3622) (#3629)

fixes #3621

* running check mode used to accidentally delete the existing
  ssh key; change it so deletion is skipped in check mode

(cherry picked from commit 8ba7fd5d617b8c9137ddd7c6975966d7c833da52)

Co-authored-by: Waldek Maleska <w.maleska@gmail.com>
---
 changelogs/fragments/3622-fix-gitlab-deploy-key-check-mode.yml | 2 ++
 plugins/modules/source_control/gitlab/gitlab_deploy_key.py     | 3 ++-
 2 files changed, 4 insertions(+), 1 deletion(-)
 create mode 100644 changelogs/fragments/3622-fix-gitlab-deploy-key-check-mode.yml

diff --git a/changelogs/fragments/3622-fix-gitlab-deploy-key-check-mode.yml b/changelogs/fragments/3622-fix-gitlab-deploy-key-check-mode.yml
new file mode 100644
index 0000000000..407ab8d77c
--- /dev/null
+++ b/changelogs/fragments/3622-fix-gitlab-deploy-key-check-mode.yml
@@ -0,0 +1,2 @@
+bugfixes:
+  - gitlab_deploy_key - fix the SSH Deploy Key being deleted accidentally while running task in check mode (https://github.com/ansible-collections/community.general/issues/3621, https://github.com/ansible-collections/community.general/pull/3622).
diff --git a/plugins/modules/source_control/gitlab/gitlab_deploy_key.py b/plugins/modules/source_control/gitlab/gitlab_deploy_key.py
index 09aa6820e9..c0c97d8c99 100644
--- a/plugins/modules/source_control/gitlab/gitlab_deploy_key.py
+++ b/plugins/modules/source_control/gitlab/gitlab_deploy_key.py
@@ -149,7 +149,8 @@ class GitLabDeployKey(object):
         #   GitLab REST API, so for that case we need to delete and
         #   than recreate the key
         if self.deployKeyObject and self.deployKeyObject.key != key_key:
-            self.deployKeyObject.delete()
+            if not self._module.check_mode:
+                self.deployKeyObject.delete()
             self.deployKeyObject = None
 
         # Because we have already call existsDeployKey in main()