0
0

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 3 years have passed since last update.

Ansibleの初期設定をシェルスクリプトで自動化してみた

Posted at

やったこと

Ansible使うぞ!と思ってもキーを出して実行されるサーバー側にキーを設定してとか、hostsファイルにIPアドレスを記載してとか色々設定がめんどくさい。。。。
そこで、Ansibleの初期設定をシェルスクリプトにして自動化しました!
↓のシェルスクリプトを使えばほんの10数秒でAnisbleが使用できるようになりますので、ぜひご覧くださいませ。

シェルスクリプトの内容/解説

以下のようにシェルスクリプトを作りました。

amazon-linux-extras install -y ansible2
ssh-keygen -N ""
chmod 777 /root/.ssh/id_rsa.pub
ssh -i <秘密鍵> ユーザー名@$1 'sudo chmod 777 /root ; sudo chmod 777 /root/.ssh'
scp -i <秘密鍵> /root/.ssh/id_rsa.pub ユーザー@${1}:/root/.ssh/
ssh -i <秘密鍵> ユーザー名@$1 'sudo chmod 777 /root/.ssh/authorized_keys'
ssh -i <秘密鍵> ユーザー名@$1 ' cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys '
ssh -i <秘密鍵> ユーザー名@$1 'sudo chmod 550 /root ; sudo chmod 550 /root/.ssh ; sudo chmod 550 /root/.ssh/authorized_keys '
if [ `cat /etc/ansible/hosts|grep $1` = "$1" ]
then
echo OK
else
echo $1 >> /etc/ansible/hosts
fi
echo interpreter_python=/usr/bin/python >> /etc/ansible/ansible.cfg

流れとしては以下のようになります。

ansibleをインストール

権限を開いて実行される側のサーバーのauthorized_keysにid_rsa.pubの中身をコピー

権限を閉じる

if文で実行される側のサーバーのアドレスを/etc/ansible/hostsに記載
※すでに記載されている場合であれば実行されずOKを表示

ansible.cfgに「interpreter_python=/usr/bin/python」を記載

最後に

上記のスクリプトを使えば楽に初期設定ができるようになりました。
実行する際も下記コマンドを使えばOK

sh (ファイル名).sh IPアドレス

これで簡単に初期設定が行えます!

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?