LoginSignup
19
17

More than 5 years have passed since last update.

Ansibleでシェル芸をいつもより多く回してみる

Last updated at Posted at 2015-05-17

下準備

適宜パッケージマネージャで ansible パッケージをインストール

cygwin環境の場合は gcc-core, openssh, python, python-setuptools を
インストールした上で easy_install pip; pip install ansible を実行

~/.bashrc に export ANSIBLE_SSH_ARGS="-o ControlMaster=no" を追記し反映

sshの接続先設定は ~/.ssh/config に以下のように記述しておく

~/.ssh/config
Host server1
 HostName nnn.nnn.nnn.nnn
 IdentityFile ~/.ssh/keys/server1.pem
 User user1

ansibleの設定は ~/.ansible.cfg を作成すると自動で読み込まれるので
下記の様に対象ホスト、ホストグループの設定ファイルパスなどを設定しておく

~/.ansible.cfg
[defaults]
hostfile = ~/.ansible_hosts

~/.ansible_hosts に記述した対象ホスト、ホストグループが操作可能になる

~/.ansible_hosts
#対象ホスト記述
server1

#ホストグループ記述
[group1]
server1
server2
server3

#対象ホスト記述には sshの接続パラメータなども指定可能
server1 ansible_ssh_user=xxx ansible_ssh_pass=xxx ansible_ssh_port=nnnn

やってみる

ホストグループ group1 全ホストで uname -a を実行し結果を取得
% ansible -a "uname -a" group1

デフォルトのcommandモジュールだと、パイプリダイレクトが使えないので shellモジュールを使用
% ansible -m shell -a "uname -a | cut -d' ' -f 3" group1
※エイリアス定義しておくと良いかもしれない

-oオプションで、出力結果をホストごとに 1行にして出力
% ansible -m shell -a "uname -a | cut -d' ' -f 3" group1 -o

-tオプションで、ディレクトリを作成し、ホスト名のファイルに出力
% ansible -m shell -a "uname -a | cut -d' ' -f 3" group1 -t dir
※JSONフォーマットなので jqコマンドなどを使って、好きに料理する

他にユーザ指定や並列度のオプションなどがあるが、必要ならここを参照

対象ホスト指定にはワイルドカードや :で区切っての複数条件指定が行える
% ansible --list-hosts server*
% ansible --list-hosts group1:group2
% ansible --list-hosts group1:!excluded:&required
※ --list-hostsオプションで処理を実行せず、対象ホストの一覧のみ出力している

モジュールは上記以外にも多数用意されていて、使いこなせばシステム管理作業などが捗る
% ansible -m ping group1
% ansible -m copy -a "src=~/hoge.conf dest=/etc/httpd/conf.d/hoge.conf" group1
% ansible -m service -a "name=httpd state=restarted" group1

おまけ

コマンドラインからホスト、パラメータを指定して実行する playbookテンプレート

hoge.yml
--- # usage: ansible-playbook hoge.yml -e "hosts=server1 param1=aaa"
- hosts: "{{ hosts }}"
  tasks:
    - action: "hoge param1={{ param1 }}"

も少し高度な条件判断や処理の構造化をしたい場合は playbookの構文を覚えると良い

19
17
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
19
17