LoginSignup
39
39

More than 5 years have passed since last update.

ベストプラクティスからはじめるAnsible

Last updated at Posted at 2016-10-24

対象

Ansibleに興味があり、
実際にAnsibleを使用してサーバー構成管理を体験してみたい人。

はじめに

今回はAnsibleの公式ページで公開されているDirectory Layoutをもとに実際にAnsibleを動かすハンズオンを行う。

Ansibleのベストプラクティスについて

まずはハンズオンの前に下記のスライドをご覧下さい。

ハンズオン

環境準備

Github

仮想環境構築

$ git clone https://github.com/yukihirai0505/ansible-best-practice-hands-on
$ cd ansible-best-practice-hands-on
$ vagrant up

ここで一旦

ansible-best-practice-hands-on/httpdStore

の中身を覗いてみる。

今回のイメージ

  • ステージング
  • プロダクション

の環境にそれぞれNginxをインストールし、
簡単なhtmlファイルを表示するところまでやってみる。

オプションでローカルホストの構成管理もやってみる。

Inventoryについて

下記ファイルがInventoryファイルにあたる。

  • localhost
  • stage
  • production

どのサーバーを管理するかを書いていくファイル。

ここにはipやホスト名,ステージごとの変数などを記述していく。

Playbookについて

下記ファイルがPlaybookにあたる

  • site.yml
  • fooapp.yml
  • localhost.yml
  • rolesディレクトリ配下

ここではNginxをインストールする,テンプレートファイルを転送するなどのサーバーに対しての構成を記述していく。

コマンドについて

  • ansible
  • ansible-playbook
  • ansible-galaxy

ansibleについて

ansible all -m ping

簡単にansibleの挙動を確認できる。

ansible-playbookについて

指定したInventoryにPlaybookを実行することができる。

ansible-playbook -i [inventory] [playbook].yml

またドライランを実行することもできる。

ansible-playbook -i [inventory] [playbook].yml --check

ansible-galaxyについて

Ansible 初心者なら、まずは Ansible Galaxy から始めてみよう
という記事もあるように、
galaxyにある設定を読むのもansibleの勉強になります。

モジュールについて

実際に動かしてみる

hostサーバーでansibleの設定

まずは今回ansibleを実行するサーバーで
ansibleのインストールと
sshの設定を行います。

  • ansibleのインストール
$ vagrant ssh host
vagrant@host$ wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
vagrant@host$ sudo rpm -Uvh epel-release-6-8.noarch.rpm
vagrant@host$ sudo yum -y install ansible
# ansible2系が入っているか確認
vagrant@host$ ansible --version
vagrant@host$ touch ~/.ssh/config
  • sshの設定
Host stage
 HostName 192.168.43.52
Host production
 HostName 192.168.43.53
vagrant@host$ chmod 600 .ssh/config
vagrant@host$ ssh-keygen -t rsa
vagrant@host$ ssh-copy-id stage
# Enter yes,vagrant
vagrant@host$ ssh-copy-id production
# Enter yes,vagrant

これでansileを実行できる環境は整いました。

次にhostサーバーで /var/www/html ディレクトリに移動します。

vagrant@host$ cd /var/www/html

それぞれのPlaybookを使用することができます。

ステージング向け

vagrant@host$ ansible-playbook -i stage site.yml

プロダクション向け

vagrant@host$ ansible-playbook -i production site.yml

これでそれぞれのIPにアクセスすれば index.html の内容が確認できます。

Host stage
 HostName 192.168.43.52
Host production
 HostName 192.168.43.53

ローカル環境での実行

ホストサーバー向けに構成管理を行うこともできる。

まずはansible-galaxyを使用してjava用のroleをインストールします。

ansible-galaxy install -p ./roles geerlingguy.java

次にlocalhost用のplaybookを実行します。

vagrant@host$ ansible-playbook -i localhost localhost.yml

実際にホストサーバーに java が入ったことが確認できる。

java -version
39
39
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
39
39