diff --git a/setup_managed_node.sh b/setup_managed_node.sh index c261843..694b460 100644 --- a/setup_managed_node.sh +++ b/setup_managed_node.sh @@ -73,13 +73,43 @@ echo "==> Installing public key into authorized_keys" cat "${KEY_TMP_PATH}.pub" >> "${AUTHORIZED_KEYS}" -echo "==> Configuring sshd Match User ansible block" SSHD_CONFIG="/etc/ssh/sshd_config" if [[ ! -f /etc/ssh/sshd_config.ansible.bak ]]; then + echo "==> Backing up sshd_config" cp "${SSHD_CONFIG}" /etc/ssh/sshd_config.ansible.bak fi +set_sshd_global_option() { + local key="$1" + local value="$2" + + if grep -qE "^[#]*\s*${key}\s+" "${SSHD_CONFIG}"; then + # Update existing line (commented or not) + sed -i "s|^[#]*\s*${key}\s\+.*|${key} ${value}|" "${SSHD_CONFIG}" + else + # Insert before first Match block, or append if none exists + awk -v line="${key} ${value}" ' + BEGIN { inserted=0 } + /^Match / && !inserted { + print line + inserted=1 + } + { print } + END { + if (!inserted) print line + } + ' "${SSHD_CONFIG}" > "${SSHD_CONFIG}.ansible.tmp" + + mv "${SSHD_CONFIG}.ansible.tmp" "${SSHD_CONFIG}" + fi +} + +echo "==> Ensuring UsePAM is enabled globally" +set_sshd_global_option UsePAM yes + +echo "==> Configuring sshd Match User ansible block" + # Remove existing Match User ansible block sed -i '/^Match User ansible$/,/^Match /d' "${SSHD_CONFIG}" @@ -90,7 +120,6 @@ PubkeyAuthentication yes ChallengeResponseAuthentication no AuthenticationMethods publickey - UsePAM yes EOF echo "==> Restarting SSH daemon"