目的
- Virtual Box上に構築したCentOSからさくらVPS上に構築したCentOSへのSSH接続の設定を行う
- Virtual Box上に構築したCentOSのAnsibleを動かす
- さくらVPS上に構築したCentOSに対してAnsibleで疎通確認をする
関連サイト
公式サイト
参考サイト
ダウンロードソフトウェア
- なし
環境
ホストマシン
- Windows 7 Home Premium
- Vagrant 1.7.2
- VirtualBox 4.3.26-98988
ゲストマシン
- CentOS7
- Python 2.7.5
- Ansible 1.9.1
ターゲットマシン
- さくらVPS
- CentOS7
手順
- ターゲットマシンにvagrantユーザを追加する
- ゲストマシンで秘密鍵・公開鍵を作成する
- ターゲットマシンに公開鍵を配置する
- ゲストマシンでAnsibleのhostsファイルを作成する
- Ansibleコマンドでゲストマシンからターゲットマシンの疎通を確認する
ターゲットマシンにvagrantユーザを追加する
ゲストマシンからターゲットマシンに接続し、Ansibleで処理をする際のユーザとしてvagrant
ユーザを作成する。
ターゲットマシンで以下のコマンドを実行する。
# useradd vagrant
# passwd vagrant
Changing passwd for user vagrant.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
#
ゲストマシンで秘密鍵・公開鍵を作成する
ゲストマシンからターゲットマシンにSSH接続する際に公開鍵認証方式で実行するために、秘密鍵・公開鍵を作成する。
ゲストマシンで以下のコマンドを実行する。
$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/vagrant/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/vagrant/.ssh/id_rsa.
Your public key has been saved in /home/vagrant/.ssh/id_rsa.pub.
The key fingerprint is:
:
$
ターゲットマシンに公開鍵を配置する
先の手順で作成した秘密鍵・公開鍵のうち、公開鍵をターゲットマシンに配置する。これにはssh-copy-id
コマンドを使用する。以下のとおり実行する。
途中、ターゲットマシンのvagrant
ユーザのパスワードを求められるので入力する。
-i
の後には配置する公開鍵のパスを、その後にはターゲットマシンのユーザ名とIPアドレスを@
で結合した文字列となる。
$ ssh-copy-id -i .ssh/id_rsa.pub vagrant@XXX.XXX.XXX.XXX
The authenticity of host 'XXX.XXX.XXX.XXX (XXX.XXX.XXX.XXX)' can't be established.
ECDSA key fingerprint is ZZ:ZZ:ZZ:ZZ:ZZ:ZZ:ZZ:ZZ:ZZ:ZZ:ZZ:ZZ:ZZ:ZZ:ZZ:ZZ.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
vagrant@XXX.XXX.XXX.XXX's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'vagrant@XXX.XXX.XXX.XXX'"
and check to make sure that only the key(s) you wanted were added.
$
ゲストマシンでAnsibleのインベントリファイルを作成する
Ansibleは接続先の情報を記載したファイル、インベントリファイルを参照する。これはデフォルトで/etc/ansible/hosts
となる。
ゲストマシンにて/etc/ansible/hosts
ファイルを作成する。記載するのはターゲットマシンのIPアドレスである。
# mkdir /etc/ansible
# vi /etc/ansible/hosts
XXX.XXX.XXX.XXX
Ansibleコマンドでゲストマシンからターゲットマシンの疎通を確認する
Ansibleはコマンドに対してモジュールと呼ばれる機能を付与することで、様々な処理を行う。ここでは、疎通確認を行うためにping
モジュールを使用する。以下のコマンドを実行し、疎通を確認する。
$ ansible XXX.XXX.XXX.XXX -m ping
Enter passphrase for key '/home/vagrant/.ssh/id_rsa':
XXX.XXX.XXX.XXX | success >> {
"changed": false,
"ping": "pong"
}
以上