LoginSignup
9
9

More than 5 years have passed since last update.

Ansibleで複数のサーバを操作する

Posted at

はじめに

Ansibleで複数のサーバを操作する方法を記述します。

環境

  • CentOS 6.5
  • Ansible 1.7

Ansibleのインストール

  • epelリポジトリの追加
$ curl -O http://ftp.riken.jp/Linux/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm
$ sudo yum localinstall epel-release-6-8.noarch.rpm
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: www.ftp.ne.jp
 * epel: ftp.tsukuba.wide.ad.jp
 * extras: www.ftp.ne.jp
 * updates: ftp.tsukuba.wide.ad.jp
repo id                 repo name                                                       status
base                    CentOS-6 - Base                                                  6,367
epel                    Extra Packages for Enterprise Linux 6 - x86_64                  11,105
extras                  CentOS-6 - Extras                                                   15
updates                 CentOS-6 - Updates                                               1,597
repolist: 19,084

$ rpm --import http://ftp.riken.jp/Linux/fedora/epel/RPM-GPG-KEY-EPEL-6
  • Ansibleのインストール
$ sudo yum install ansible
$ ansible --version
ansible 1.7

Ansibleでの操作

  • インベントリファイルを作成します。
~/ansible_hosts
[localhost]
127.0.0.1

[servers]
web001
web002
db001

[web]
web001
web002

[db]
db001
  • 全サーバでhostnameコマンドを実行します。
$ ansible -i ansible_hosts all -a "hostname"
web001 | success | rc=0 >>
web001

web002 | success | rc=0 >>
web002

db001 | success | rc=0 >>
db001

127.0.0.1 | success | rc=0 >>
client

※ 各サーバへのsshでのログインにパスワードが必要な場合は、 --ask-pass オプションを指定します。

$ ansible -i ansible_hosts all -a "hostname" --ask-pass
  • webサーバのみでhostnameコマンドを実行します。
$ ansible -i ansible_hosts web -a "hostname"
web001 | success | rc=0 >>
web001

web002 | success | rc=0 >>
web002

|(パイプ) などを使用したい場合は、 shell モジュールを利用します。
モジュールを指定しない場合は、 command モジュールが利用されます。

$ ansible -i ansible_hosts web -m shell -a "hostname | tr '[:lower:]' '[:upper:]'"
web001 | success | rc=0 >>
WEB001

web002 | success | rc=0 >>
WEB002
  • root権限でコマンドを実行したい場合は、--sudoオプションを指定します。
$ ansible -i ansible_hosts web -a "whoami" --sudo
web001 | success | rc=0 >>
root

web002 | success | rc=0 >>
root

※ sudoコマンドでパスワードが必要な場合は、--ask-sudo-passオプションを指定します。

$ ansible -i ansible_hosts web -a "whoami" --sudo --ask-sudo-pass
  • リモートサーバで別アカウントでコマンドを実行したい場合は、--sudo-userオプションを指定します。
$ ansible -i ansible_hosts web -a "whoami" --sudo --sudo-user admin
web001 | success | rc=0 >>
admin

web002 | success | rc=0 >>
admin

参考

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