2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ansibleでサーバ情報を取得する

2
Last updated at Posted at 2019-10-28

はじめに

前回Ansibleの基礎を学んだので今回はAnsibleを使用してサーバ情報を取得しようと思う。
色々試したが結果の成形等で悩んで結局、各サーバでcommandを実行⇒pythonで情報を成形という方法を試した。

Ansibleの設定

ディレクトリ構成は以下のようになっている。

ディレクトリ構成
ansible
├── inventory
│   └── hosts
│   
├── json_ansible.cfg
├── json_change.py
├── server_info_get.yml
└── result.json

hostsファイルの中身は以下。

hosts
[targets]
192.168.163.130
192.168.163.131

次にPlay-book(server_info_get.yml)の中身は以下。

server_info_get.yml
- hosts: targets
  user: root
  gather_facts: false
  tasks:
        - command: "{{ item }}"
          with_items:
            - 'hostname'
            - 'cat /etc/redhat-release'
            - 'uname -a'
            - 'yum list installed'

with_items配下に取得したいサーバ情報を書き出した。今回はCentOSサーバが対象だが、windowsサーバなどが対象に入った状態で1つのplay-bookで実行しようとした場合はもう少し工夫が必要そう。

次にansibleで取得した情報をjson形式で保存したいので設定ファイル(json_ansible.cfg)を作成する。

json_ansible.cfg
[defaults]
stdout_callback = json

これでAnsible側の設定は完了した。

Ansibleの実行

それではAnsibleを実行してみようと思う。上記で作成した設定ファイルを読み込ませて実行する。

Ansible_server
[root@server ansible]# ANSIBLE_CONFIG=/ansible/json_ansible.cfg ansible-playbook -i inventory/hosts server_info_get.yml > result.json

ANSIBLE_CONFIGで設定ファイルを指定してAnsibleを実行、実行結果をresult.jsonに掃き出した。

それでは中身を見てみようと思う。内容が多いのでlessで

Ansible_server
[root@server ansible]# less result.json
result.json
{
    "plays": [
        {
            "play": {
                "id": "000c29a4-5724-73ef-251b-000000000008",
                "name": "targets"
            },
            "tasks": [
                {
                    "hosts": {
                        "192.168.163.130": {
                            "changed": true,
                            "msg": "All items completed",
                            "results": [
                                {
                                    "_ansible_ignore_errors": null,
                                    "_ansible_item_result": true,
                                    "_ansible_no_log": false,
                                    "_ansible_parsed": true,
                                    "changed": true,
                                    "cmd": [
                                        "hostname"
                                    ],
                                    "delta": "0:00:00.008092",
                                    "end": "2019-10-28 16:38:35.390429",
                                    "failed": false,
                                    "invocation": {
                                        "module_args": {
                                            "_raw_params": "hostname",
                                            "_uses_shell": false,
                                            "chdir": null,
                                            "creates": null,
                                            "executable": null,
                                            "removes": null,
                                            "stdin": null,
                                            "warn": true
                                        }
                                    },
                                    "item": "hostname",
                                    "rc": 0,
                                    "start": "2019-10-28 16:38:35.382337",
                                    "stderr": "",
                                    "stderr_lines": [],
                                    "stdout": "test1",
                                    "stdout_lines": [
                                        "test1"
~~~~~~~~~~~~~~~~~~~~~~~~~省略~~~~~~~~~~~~~~~~~~~~~~~~~
                                    ]
                                }
                            ],
                            "warnings": [
                                "Consider using yum module rather than running yum"
                            ]
                        }
                    },
                    "task": {
                        "id": "000c29a4-5724-73ef-251b-00000000000a",
                        "name": ""
                    }
                }
            ]
        }
    ],
    "stats": {
        "192.168.163.130": {
            "changed": 1,
            "failures": 0,
            "ok": 1,
            "skipped": 0,
            "unreachable": 0
        },
        "192.168.163.131": {
            "changed": 1,
            "failures": 0,
            "ok": 1,
            "skipped": 0,
            "unreachable": 0
        }
    }
}

うまく実行されたみたいだ。

JSONファイルの成形

json形式で情報は取得できたが、いらない情報も多くあって正直見にくい。なのでjsonファイルの情報をpythonを使って人の目でみて見やすいようしようと思う。

以下のようなプログラムを作成した。

json_change.py
# coding:utf-8
import json
import sys
import pprint

# コマンドライン引数を取り込む。
args = sys.argv
# コマンドライン引数の2番目を取得。
jsonfile = args[1]

f = open(jsonfile,'r')
jsonfile = json.load(f)

for i in json_dict['plays']:
    for j in i['tasks']:
        for m in j['hosts'].items():
          print(m[0])
          data=m[1]["results"]
          print(data[0]["stdout"])
          print(data[1]["stdout"])
          print(data[2]["stdout"])
          print(data[3]["stdout"])

これを実行する。

Ansible_server
[root@server ansible]# python3 json_change.py result.json

192.168.163.130
test1
CentOS Linux release 7.6.1810 (Core)
Linux test1 3.10.0-957.el7.x86_64 #1 SMP Thu Nov 8 23:39:32 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
読み込んだプラグイン:fastestmirror
インストール済みパッケージ
GeoIP.x86_64                          1.5.0-13.el7                     @anaconda
NetworkManager.x86_64                 1:1.12.0-6.el7                   @anaconda
NetworkManager-libnm.x86_64           1:1.12.0-6.el7                   @anaconda
~~~~~~~~~~~~~~~~~~省略~~~~~~~~~~~~~~~~~~
xz-libs.x86_64                        5.2.2-1.el7                      @anaconda
yum.noarch                            3.4.3-161.el7.centos             @anaconda
yum-metadata-parser.x86_64            1.1.4-10.el7                     @anaconda
yum-plugin-fastestmirror.noarch       1.1.31-50.el7                    @anaconda
zlib.x86_64                           1.2.7-18.el7                     @anaconda
192.168.163.131
test2
CentOS Linux release 7.6.1810 (Core)
Linux jtf-docker 3.10.0-957.27.2.el7.x86_64 #1 SMP Mon Jul 29 17:46:05 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
読み込んだプラグイン:fastestmirror
インストール済みパッケージ
GeoIP.x86_64                         1.5.0-13.el7                   @anaconda
NetworkManager.x86_64                1:1.12.0-10.el7_6              @updates
NetworkManager-libnm.x86_64          1:1.12.0-10.el7_6              @updates
~~~~~~~~~~~~~~~~~~省略~~~~~~~~~~~~~~~~~~
yum-metadata-parser.x86_64           1.1.4-10.el7                   @anaconda
yum-plugin-fastestmirror.noarch      1.1.31-50.el7                  @anaconda
yum-utils.noarch                     1.1.31-50.el7                  @base
zlib.x86_64                          1.2.7-18.el7                   @anaconda

お!ちょっと見にくいがほしい情報だけが表示された!

次の課題

情報取得、jsonファイルの成形はできたがまだ見にくい。というかpythonのネストが深くて個人的に微妙・・・。
なので次回は取得した情報をツールを使ってビジュアライズ化しようと思う。(ansibleからは離れるが)

参考

2
4
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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?