試纏

ためしてまとめる〜色々なトピックやテーマについて試してみたり、まとめてみたりするブログです。

書籍『Ansible実践ガイド』を実践してみた - 第2章 Ansibleの基礎(その1.Ansibleのインストールとansibleコマンドの実践)

f:id:shinyaa31:20170116194242p:plain:w200

書籍『Ansible実践ガイド』の読解&実践シリーズ、第2章。ここからいよいよAnsibleを実際に導入し、触ってみるパートに入ります。

Ansible実践ガイド

Ansible実践ガイド

読書メモ

まずは読書パートのメモ。Ansibleの仕組み、制御の部分について。

  • コントロールノードからターゲットノードにSSH経由でタスクを送信
  • コントロールノードにAnsibleをインストール、InventoryとPlaybookを用意で完了
  • Inventory(インベントリ):ターゲットノードのリスト
  • Playbook(プレイブック):ターゲット側で実行したい処理を記載
  • Ansibleの実行処理、実際はPythonに変換されて動いている。
  • ターゲットノードにはPython実行環境が必要。また状況によっては特権ユーザーや事前のユーザー作成も必要
  • Ansibleのコンポーネント
    • モジュール:コアカテゴリ/エクストラカテゴリ
    • プレイブック
    • インベントリ
    • プラグイン:コア機能を拡張、追加機能を提供。種類は様々
    • Python API:プログラムからAnsibleを制御可能
    • Ansible CLI

インストール周りで言及されている内容。

  • 利用要件:
    • コントロールノード:Python2.6 or 2.7以上
    • ターゲットノード:Python2.4以上
      • AnsibleでSSH接続を行うため、sshdプロセスの起動が必要
      • Connection Type Pluginsを利用する場合は上記の限りでは無い、らしい
  • インストールの実施

説明が終わったところでインストールの説明に入ります。第2章では以下2ケースの実践について解説されていますが、今回は3環境を全てVagrant上に用意して進めてみたいと思います。

  • コントロールノード自体でのAnsibleのインストール及び動作確認
  • コントロールノードとターゲットノード(計2つ)をそれぞれ作成し(環境的には併せて3つ)、コントロール→ターゲットの連携で動作を確認

実践メモ

コントロールノードの環境準備

まずはboxにCentOSの新しめのイメージファイルを追加します。

CentOSを選んだのは特に理由は無く、比較的慣れ親しんでいるyumコマンドを使えるから。

Vagrantは下記エントリにてmacOS(Sierra)に導入していたものを使います。

$ vagrant box add centos_for_ansible_controller https://github.com/tommy-muehle/puppet-vagrant-boxes/releases/download/1.1.0/centos-7.0-x86_64.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'centos_for_ansible_controller' (v0) for provider: 
    box: Downloading: https://github.com/tommy-muehle/puppet-vagrant-boxes/releases/download/1.1.0/centos-7.0-x86_64.box
==> box: Successfully added box 'centos_for_ansible_controller' (v0) for 'virtualbox'!

コントロールノード用のディレクトリを作成と初期化の実施。

$ mkdir CentOS
$ cd CentOS/
$ mkdir CentOS_for_ansible_controller
$ cd CentOS_for_ansible_controller/
$ vagrant init centos_for_ansible_controller
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

サーバーのIPアドレスは以下の体系で進めます。

$ ls
Vagrantfile
$ vi Vagrantfile 
  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  # config.vm.network "private_network", ip: "192.168.33.10"
  config.vm.network "private_network", ip: "192.168.123.101"

vagrant upコマンドで環境を起動。

$ vagrant up

ssh設定に関する内容の確認。

$ vagrant ssh-config
Host default
  HostName 127.0.0.1
  User vagrant
  Port 2201
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile /Users/shinyaa31/Vagrant/CentOS/CentOS_for_ansible_controller/.vagrant/machines/default/virtualbox/private_key
  IdentitiesOnly yes
  LogLevel FATAL

SSHログイン実行。実行ユーザーがvagrantである事などが確認出来ます。

$ vagrant ssh
Last login: Thu Jul 16 08:48:31 2015 from 10.0.2.2
Welcome to your Vagrant-built virtual machine.

[vagrant@localhost ~]$ cat /etc/redhat-release
CentOS Linux release 7.1.1503 (Core) 
[vagrant@localhost ~]$ arch
x86_64
[vagrant@localhost ~]$ uname -a
Linux localhost.localdomain 3.10.0-229.el7.x86_64 #1 SMP Fri Mar 6 11:36:42 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
[vagrant@localhost ~]$ whoami
vagrant

Ansibleのインストール

Ansible導入に必要な環境及びAnsibleをインストール。ちなみに書籍では諸々の都合を考慮して一般ユーザーを作成し、必要に応じて特権ユーザーにて作業を行うのが良い、との記載がありました。当初はその手法に倣おうかなと思ったのですがいまいち設定・連携が上手く行かず時間を食ってしまったのでとりあえずは環境作成時のvagrantユーザーで進めて行こうと思います。現行バージョンVagrant環境下での一般ユーザー作成とログイン設定周りについてはエントリを改める形でどこかのタイミングでチャレンジ&まとめておきたいと思います。

$ sudo yum -y update
$ sudo yum -y install epel-release
$ sudo yum -y install sshpass
$ sudo yum -y install ansible
$ ansible --version
ansible 2.2.0.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides

公開鍵&秘密鍵設定も書籍に倣う形で実施。

$ 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:
xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx vagrant@localhost.localdomain
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|       . o       |
| (中略)          |
|         . + o . |
|          . .    |
+-----------------+

ssh-copy-idコマンドで公開鍵を作成した環境に登録。

$ ssh-copy-id -o StrictHostKeyChecking=no -i $HOME/.ssh/id_rsa.pub localhost
/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@localhost's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh -o 'StrictHostKeyChecking=no' 'localhost'"
and check to make sure that only the key(s) you wanted were added.

Ansible実践

以下は書籍の内容に倣って実践したコマンドのまとめとなります。

作業用フォルダの作成

$ mkdir -vp effective_ansible/section02/inventory/
mkdir: ディレクトリ `effective_ansible' を作成しました
mkdir: ディレクトリ `effective_ansible/section02' を作成しました
mkdir: ディレクトリ `effective_ansible/section02/inventory/' を作成しました

設定ファイルの確認

設定ファイル:ansible.cfgについては、幾つか場所候補があり、読み込みの優先順位があるとの事。また、OSパッケージマネージャでインストールした場合は/etc/ansible/に生成されるようになっています。今回はyumでインストールしたのでこれに当てはまるはず。実際に確かめてみたらちゃんとありました。

[vagrant@localhost ansible]$ cd /etc/ansible/
[vagrant@localhost ansible]$ ls
ansible.cfg  hosts  roles

以下4点の設定値を書き換えて動かす事にしてみます。ログファイルのパスについては初期設定値の/var/log/ansible.logがrootユーザー権限で(vagrantユーザーでは)アクセス出来なかったのでアクセス可能なパスに変更しています。

# some basic default values...
:
forks           = 15
# logging is off by default unless this path is defined
# if so defined, consider logrotate
#log_path = /var/log/ansible.log
log_path = /home/vagrant/ansible.log
# uncomment this to disable SSH key host checking
host_key_checking = False
# plays will gather facts by default, which contain information about
# the remote system.
#
# smart - gather by default, but don't regather if already gathered
# implicit - gather by default, turn off with gather_facts: False
# explicit - do not gather by default, must say gather_facts: True
gathering = smart

Ansible実行(ansibleコマンド)

Pingモジュールを使ったホストへの接続確認。

$ ansible -i /home/vagrant/effective_ansible/section02/inventory/test01_inventory.ini test_servers -m ping
Enter passphrase for key '/home/vagrant/.ssh/id_rsa': (パスワード入力:vagrant)
localhost | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

fileモジュールを使ったファイル作成。

$ ansible -i /home/vagrant/effective_ansible/section02/inventory/test01_inventory.ini test_servers -m file -a \
> 'path=/home/vagrant/hello-ansible.txt state=touch mode=644'
Enter passphrase for key '/home/vagrant/.ssh/id_rsa': 
localhost | SUCCESS => {
    "changed": true, 
    "dest": "/home/vagrant/hello-ansible.txt", 
    "gid": 1000, 
    "group": "vagrant", 
    "mode": "0644", 
    "owner": "vagrant", 
    "size": 0, 
    "state": "file", 
    "uid": 1000
}

[vagrant@localhost var]$ ll /home/vagrant/
合計 28
-rw-rw-r-- 1 vagrant vagrant 1052  118 15:37 ansible.log
-rwxr-xr-x 1 vagrant vagrant  450  716  2015 base.sh
-rwxr-xr-x 1 vagrant vagrant  118  716  2015 cleanup.sh
drwxrwxr-x 3 vagrant vagrant   22  118 15:14 effective_ansible
-rw-r--r-- 1 vagrant vagrant    0  118 15:37 hello-ansible.txt
-rwxr-xr-x 1 vagrant vagrant  360  716  2015 puppet.sh
-rwxr-xr-x 1 vagrant vagrant  674  716  2015 vagrant.sh
-rwxr-xr-x 1 vagrant vagrant  260  716  2015 virtualbox.sh
-rwxr-xr-x 1 vagrant vagrant  105  716  2015 zerodisk.sh

まとめ

という訳で、単一仮想環境を用意してAnsibleを実行(ansibleコマンド)してみるところまで出来ました。この次ではansible-playbookコマンドを使った処理実行に触れているのですが、関連情報を読んで行くと複数の仮想マシンを一度に立てて連携させる方法がちゃんとあるらしい、というところまで分かったところで良い区切りとなったので、別エントリにて続きを試してみたいと思います。