Created
November 23, 2021 22:37
-
-
Save 1k-off/3abdfa5e200a6428d202703f3cfb3536 to your computer and use it in GitHub Desktop.
Build ansible inventory from SSH config
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
keybasepath="$HOME/.ssh/" | |
cat $HOME/.ssh/config | awk -v RS= -v FS=\\n -v IGNORECASE=1 -v keybasepath="$keybasepath" ' | |
{ | |
ip = "" | |
alias = "" | |
id_file = "" | |
username = "" | |
port = "" | |
result = "" | |
for (j = 1; j <= NF; ++j) { | |
split($j, tmp, " ") | |
if (tmp[1] == "Host") { alias = tmp[2] } | |
if (tmp[1] == "Hostname") { ip = tmp[2] } | |
if (tmp[1] == "IdentityFile") { id_file = substr(tmp[2], 8) } | |
if (tmp[1] == "User") { username = tmp[2] } | |
if (tmp[1] == "Port") { port = tmp[2] } | |
} | |
if (ip || alias && alias != "*") { | |
result = sprintf("%-35s ansible_host=%-25s ",alias,ip) | |
if (username) result = sprintf("%s ansible_user=%-20s",result,username) | |
if (port) result = sprintf("%s ansible_port=%-5s",result,port) | |
if (id_file) result = sprintf("%s ansible_ssh_private_key_file=%s%s",result,keybasepath,id_file) | |
printf "%s\n",result | |
} | |
} | |
' > hosts.txt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment