Rails6の開発環境をAWS上に自動構築する③

Rails6の開発環境をAWS上に自動構築する③

Rails6の開発環境をAnsibleで自動構築する準備をします。

お試しで、自動構築対象のEC2にコマンドが通るかテストしてみます。

toshioshimo.hatenablog.com

f:id:TOSHIOSHIMO:20191215222807p:plain

Ansibleで操作する対象のホストを設定する

Ansibleは、/etc/ansible/hostsに記述されたホストを参照してくれます。

# cd /etc
# mkdir ansible
# cd ansible
# sudo vi hosts

hostsファイルに対象のEC2インスタンスIPアドレスまたはホスト名記述します。

ホスト名を記述する際は、名前解決できるようにしておきましょう。

[Web]
xxx.xxx.xxx.xxx (自動構築対象のローカルIP)

 ここで、[web]を記載がありますが、無くても動作します。

これは「グループ」という概念で、Ansible実行時に対象のIPを分けることができます。

"all"と指定した場合は、全て実行されます。

Ansibleを実行してみる

ホームディレクトリに戻り、ansibleコマンドを実行してみます。

# ansible all -m command -a "date" --private-key=(SSHキーの場所)
[WARNING]: Platform linux on host xxx.xxx.xxx.xxx is using the discovered Python interpreter at /usr/bin/python, but future installation of another Python
interpreter could change the meaning of that path. See https://docs.ansible.com/ansible/2.10/reference_appendices/interpreter_discovery.html for more
information.
xxx.xxx.xxx.xxx | CHANGED | rc=0 >>
2020年 10月 10日 土曜日 00:47:28 UTC

 "date"コマンドの結果が返ってくれば成功です。自動構築対象のEC2でdateコマンドを実行し、その結果が返ってきたということです。

ansible all〜としていますが、このallは先程の/etc/ansible/hostsに記載されているホスト全て、グループ関係無く実行するという意味です。

WARNINGの行は、Ansible2.8から実装された機能で、ansibleが使用するPythonのインタラプタを検出する仕組みから出ているようです。

試しにAnsibleのバージョンを確認してみます。

# ansible --version
ansible 2.10.2
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/ec2-user/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.18 (default, Aug 27 2020, 21:22:52) [GCC 7.3.1 20180712 (Red Hat 7.3.1-9)]

使用するpythonに2.7.18が指定されています。

インストールされているpythonのバージョンを確認してみます、

# ls -la python*
lrwxrwxrwx 1 root root 7 9月 21 21:11 python -> python2
lrwxrwxrwx 1 root root 14 9月 21 21:11 python-config -> python2-config
lrwxrwxrwx 1 root root 9 9月 21 21:11 python2 -> python2.7
lrwxrwxrwx 1 root root 16 9月 21 21:11 python2-config -> python2.7-config
-rwxr-xr-x 1 root root 7048 8月 27 21:23 python2.7
-rwxr-xr-x 1 root root 1846 8月 27 21:23 python2.7-config

Amazon Linux2のデフォルトでは、Python3系が入っていないようです。

このWARNINGを非表示とするにはansible.cfgファイルでインタラプタを設定する、インベントリファイルで設定するなどやり方はあるのですが、今回のテストの本筋から逸れますし、動作に支障が無いので無視しておきます。

今回のまとめ

Ansibleの実行に最低限の設定をして、構築対象(下図左のインスタンス)にリモートでコマンドを実行されることを確認しました。AnsibleではPlaybookというファイルに沿って、順番にコマンドを実行していくことで、自動構築を実現しています。

f:id:TOSHIOSHIMO:20201010104455p:plain