Fragments of verbose memory

冗長な記憶の断片 - Web技術のメモをほぼ毎日更新(準備中)

Jan 13, 2021 - 日記

~/.ssh/configを分割して管理する ver2

管理するサーバが増減するたびに変更を加えるOpenSSHの設定ファイル~/.ssh/config

長くなりすぎて管理しづらくなると何とかこれを分割したくなりますね?ファイルが分割できれば、gitで管理したり、一部をメンバーとプロジェクトで共有できたりできて便利そうです。ここでは私が利用している~/.ssh/configの分割方法をご紹介します。

本編は以前Qiitaに似たような記事 を書きましたが、そのパワーアップ?バージョンです。

sshconfのインストール

以下のシェルスクリプトをsshconfと言う名前で保存して、実行権限つけて(chmod +x sshconf)どこかPATHの通ったところに置いてください。

#!/bin/bash
command=$1
ssh_config_dir=~/.ssh
ssh_configs_dir=${ssh_config_dir}/conf.d
ssh_config_file=${ssh_config_dir}/config
ssh_base_config_file=${ssh_configs_dir}/config
function usage()
{
echo "Usage: `basename $0` [update [go]] [add user@ipaddress alias]"
}
function generate()
{
cat ${ssh_base_config_file} ${ssh_configs_dir}/*.conf > ${ssh_config_file}.new
}
function diff_w_new()
{
diff -uN ${ssh_config_file} ${ssh_config_file}.new
}
function update()
{
cp ${ssh_config_file} ${ssh_config_file}.old
cp ${ssh_config_file}.new ${ssh_config_file}
}
if [ -z "$command" ]; then
generate
diff_w_new && exit
while true; do
read -p "Do you wish to overwrite ${ssh_config_file}? [Y] " yn
case $yn in
[Yy]* ) update; break;;
* ) exit;;
esac
done
exit
fi
case $command in
update)
generate
update
;;
*)
usage
;;
esac
view raw sshconf hosted with ❤ by GitHub

既存の設定の退避(重要)

sshconf~/.ssh/configを上書きしますので、コピーして既存の設定を残すようにします。

$ cp ~/.ssh/config ~/.ssh/base_config

サーバの追加

接続先のサーバを追加するには以下のコマンドを実行してください

$ sshconf add user@ipaddress alias

ユーザalisbob.example.comssh bobで繋げるようにするには以下のようになります。

$ sshconf add alis@bob.example.com bob

このコマンドにより、以下のファイルが作られます。

~/.ssh/conf.d/bob.conf

Host bob
  User alis
  HostName bob.example.com

また、~/.ssh/conf.d/bob.confの内容が~/.ssh/base_configとマージされて~/.ssh/configに上書きされます。

これによりssh bobとすることで、alis@bob.example.comへのsshを実現しています。

sshオプションの変更

~/.ssh/conf.d/bob.confにsshオプションを追加したい場合はファイルを直接変更して、sshconf updateを実行してください。

例えば、sshポートを10022に変えたい場合、以下のように直接ファイルを修正

~/.ssh/conf.d/bob.conf

Host bob
  User alis
  HostName bob.example.com
  Port 10022

そして、sshconf updateを実行

$ sshconf update

これで~/.ssh/configが更新されます。