こんにちは! JQです。
前回は『OSS編~Ansible でサーバ構成管理 パート②~』と題して、AnsibleでPlaybookを試してみました。
今回は『OSS編~Ansible でサーバ構成管理 パート③~』と題して、AnsibleのPython APIを試してみたいと思います。
Python API
1.	基本的な使い方
Python APIは次のように実装する事が出来ます。
| 
					 1  | 
						import ansible.runner  | 
					
| 
					 1 2 3 4 5 6 7  | 
						runner = ansible.runner.Runner(    module_name='モジュール名',    module_args='モジュール引数',    pattern='対象グループ名(ワイルドカード利用可能)',    forks=並列数 ) datastructure = runner.run()  | 
					
結果は次のように帰ってきます。
「dark」と「contacted」で接続の正否でグループ分けがされます。
| 
					 1 2 3 4 5 6 7 8  | 
						{     "dark" : {        "web1.example.com" : "failure message"     }     "contacted" : {        "web2.example.com" : 1     } }  | 
					
2.	確認
実際に試して確認してみます。
テストグループにpingモジュールを行うスクリプトになります。
| 
					 1  | 
						#!/usr/bin/python  | 
					
| 
					 1  | 
						
import ansible.runner
| 
					 1 2 3 4 5 6 7  | 
						runner = ansible.runner.Runner(    module_name='ping',    module_args='',    pattern='test',    forks=10 ) datastructure = runner.run()  | 
					
| 
					 1  | 
						print datastructure  | 
					
「contacted」に入力されて帰ってきました。
| 
					 1 2 3 4 5 6 7 8 9 10 11 12  | 
						{     'dark': {     },     'contacted': {         'ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com': {             'invocation': {                 'module_name': 'ping', 'module_args': ''             },              u'changed': False, u'ping': u'pong'         }     } }  | 
					
3.	コマンド実行
最後にコマンドモジュールを試してみます。
Apacheのバージョンを取得するプログラムになります。
上から順に「ホストがない場合」「コマンドがあった場合」「コマンドがない場合」「接続出来ない場合」となります。
| 
					 1  | 
						#!/usr/bin/python  | 
					
| 
					 1 2  | 
						import ansible.runner import sys  | 
					
| 
					 1 2 3 4  | 
						results = ansible.runner.Runner(     pattern='test', forks=10,     module_name='command', module_args='/usr/sbin/apachectl -v', ).run()  | 
					
| 
					 1 2 3  | 
						if results is None:    print "No hosts found"    sys.exit(1)  | 
					
| 
					 1 2 3 4  | 
						print "OK ***********" for (hostname, result) in results['contacted'].items():     if not 'No such file or directory' in result:         print "%s >>> %s" % (hostname, result['stdout'])  | 
					
| 
					 1 2 3 4  | 
						print "FAILED *******" for (hostname, result) in results['contacted'].items():     if 'No such file or directory' in result:         print "%s >>> %s" % (hostname, result['msg'])  | 
					
| 
					 1 2 3  | 
						print "DOWN *********" for (hostname, result) in results['dark'].items():     print "%s >>> %s" % (hostname, result)  | 
					
それでは実行してみます。
| 
					 1 2 3 4 5 6  | 
						$ python ansible_test.py OK *********** ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com >>> Server version: Apache/2.2.26 (Unix) Server built:   Dec 10 2013 00:28:54 FAILED ******* DOWN *********  | 
					
成功すれば上記のようにApacheのバージョンを取得出来ます!
いかがでしたでしょうか?
次回は『OSS編~httpingで疎通確認~』と題して、
お楽しみに!!!
