From aa4b54958b9107163e519e5ebd8cfc17d24397c2 Mon Sep 17 00:00:00 2001
From: Evangelos Foutras <evangelos@foutrelis.com>
Date: Sat, 26 Feb 2022 09:55:54 +0200
Subject: [PATCH] tasks/sync-ssh-hostkeys: use blocks for shell cmds

Do the same for the hostkeys/known_hosts templates and disable fact
gathering.
---
 playbooks/tasks/sync-ssh-hostkeys.yml | 32 ++++++++++++++++++++++-----
 1 file changed, 27 insertions(+), 5 deletions(-)

diff --git a/playbooks/tasks/sync-ssh-hostkeys.yml b/playbooks/tasks/sync-ssh-hostkeys.yml
index 90850c73b..f4ce684e6 100644
--- a/playbooks/tasks/sync-ssh-hostkeys.yml
+++ b/playbooks/tasks/sync-ssh-hostkeys.yml
@@ -2,18 +2,29 @@
 
 - name: fetch ssh hostkeys
   hosts: all
+  gather_facts: false
   tasks:
     - name: fetch hostkey checksums
-      shell: "for type in sha256 md5; do for file in /etc/ssh/ssh_host_*.pub; do ssh-keygen -l -f $file -E $type; done; echo; done"
+      shell: |
+        for type in sha256 md5; do
+          for file in /etc/ssh/ssh_host_*.pub; do
+            ssh-keygen -l -f $file -E $type
+          done
+          echo
+        done
       register: ssh_hostkeys
       changed_when: ssh_hostkeys | length > 0
 
     - name: fetch known_hosts
-      shell: "set -o pipefail && ssh-keyscan 127.0.0.1 2>/dev/null | sed 's#^127.0.0.1#{{ inventory_hostname }}#' | sort"
+      shell: |
+        set -eo pipefail
+        ssh-keyscan 127.0.0.1 2>/dev/null \
+        | sed 's#^127.0.0.1#{{ inventory_hostname }}#' \
+        | sort
       environment:
         LC_COLLATE: C  # to ensure reproducible ordering
       args:
-        executable: /bin/bash  # required for repro3.pkgbuild.com which is ubuntu and has dash as default shell
+        executable: /bin/bash
       register: known_hosts
       changed_when: known_hosts | length > 0
 
@@ -23,13 +34,24 @@
     - name: store hostkeys
       copy:
         dest: "{{ playbook_dir }}/../../docs/ssh-hostkeys.txt"
-        content: "{% for host in query('inventory_hostnames', 'all,!localhost') | sort %}# {{ host }}\n{{ hostvars[host].ssh_hostkeys.stdout }}\n\n{% endfor %}"
+        content: |
+          {% for host in query('inventory_hostnames', 'all') | sort %}
+          # {{ host }}
+          {{ hostvars[host].ssh_hostkeys.stdout }}
+
+          {% endfor %}
         mode: preserve
 
     - name: store known_hosts
       blockinfile:
         path: "{{ playbook_dir }}/../../docs/ssh-known_hosts.txt"
-        block: "\n{% for host in query('inventory_hostnames', 'all,!localhost') | sort %}# {{ host }}\n{{ hostvars[host].known_hosts.stdout }}\n\n{% endfor %}"
+        block: |
+
+          {% for host in query('inventory_hostnames', 'all') | sort %}
+          # {{ host }}
+          {{ hostvars[host].known_hosts.stdout }}
+
+          {% endfor %}
 
 - name: upload known_hosts to all nodes
   hosts: all
-- 
GitLab