EC2にログインするときにsshの鍵を使う。通常はAWSに鍵をつくらせて、秘密鍵をダウンロードする。この方法は楽な方法ではあるのだが、全リージョン別の鍵になってしまうので時に面倒という問題がある。そんなときに楽なのは手元にある鍵をimportしてしまう方法。
鍵の作成とJSONの準備
- ssh-keygenつかって公開鍵と秘密鍵を作成
- 作成した鍵を含むJSONを作成
sshkey.json
{
"DryRun": true,
"KeyName": "mykey",
"PublicKeyMaterial": "ssh-rsa AAAA.....(略) user@local"
}
という具合になる。PublicKeyMaterial
には、作成した公開鍵をそのままcatかなんかでいれればOK.
いざ登録
aws ec2 import-key-pair --cli-input-json file://sshkey.json --no-dry-run
という具合で登録すればOK.
全リージョンまとめて登録
まとめて登録するために楽をすることにして、aws ec2 describe-regions
をつかったスクリプトがこんな具合
aws-ssh-import.sh
# !/bin/bash
aws ec2 describe-regions |jq '.Regions | .[].RegionName' | while read line
do
hoge=`echo $line | cut -d"\"" -f2 | cut -d"\"" -f1`
aws ec2 import-key-pair --cli-input-json file://sshkey.json --no-dry-run --region $hoge
done