14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

aws cliをつかって全リージョンにssh公開鍵をimportする

Last updated at Posted at 2015-05-18

EC2にログインするときにsshの鍵を使う。通常はAWSに鍵をつくらせて、秘密鍵をダウンロードする。この方法は楽な方法ではあるのだが、全リージョン別の鍵になってしまうので時に面倒という問題がある。そんなときに楽なのは手元にある鍵をimportしてしまう方法。

鍵の作成とJSONの準備

  1. ssh-keygenつかって公開鍵と秘密鍵を作成
  2. 作成した鍵を含む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
14
14
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?