【Ansible】【Python】Ansible の setup で取得したデータをパースして CSV、Excel 形式にコンバートするプログラム

 

少々複雑なことをやろうと思います。(と言っても自分が複雑に感じるだけですが)

Ansible には、ターゲットノードの情報を取得する「gather_facts」という機能があります。

デフォルトでは「gather_facts」は「False」になっていますが、この機能を利用して Ansible で取得した JSON データを Python でパースして綺麗に成形しようと思います。

 

作業の流れ

簡単ですが以下の手順になります。

  1. Ansibleで JSON 形式でデータ取得
  2. JSON をパースして配列に入れる
  3. 配列を綺麗に表示する(CSV,Excel形式)

 

 

ちなみに、先日は Ansible で取得した特定の情報を JSON 形式で出力して Python でパースして CSV、Excel 形式で出力する手順を作りました。

もし全体の情報ではなく「特定の情報(例えば、OSの情報、インストールされているパッケージの情報だけなど)」だけでいいならこちらを参考にしてください。

 

【Ansible】【Python】Ansible で取得した JSON 形式のデータをパースして CSV、Excel 形式にコンバートするプログラム

 

 

 

Ansible の setup を取得する手順

初めに ansible でターゲットノードの情報を取得します。

情報は「setup」モジュールを利用します。

 

setup とは?

setup とは Ansible のモジュールです。

この「setup」モジュールは Ansible の Playbook から自動的に呼ばれ、リモートホスト(ターゲットノード)の各種基本情報を取得します。

Linux だけでなく Windows でも情報を取得することができます。

 

setup モジュールを単独で実行することもできますし、ansible-playbook コマンドで、YAML 形式の「.yml」ファイルに記述して実行することもできます。

 

 

 

 

デフォルトでは「gather facts」は「有効」になっている

デフォルトでは「gathering = implicit」に設定されています。

コメントアウトされていますが「gathering = implicit」がデフォルトです。

[test@cent07 ansible]$ cat /etc/ansible/ansible.cfg
# config file for ansible -- https://ansible.com/
# ===============================================

# nearly all parameters can be overridden in ansible-playbook
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
# finds first

 

[defaults]

# some basic default values...

#inventory = /etc/ansible/hosts
#library = /usr/share/my_modules/
#module_utils = /usr/share/my_module_utils/
#remote_tmp = ~/.ansible/tmp
#local_tmp = ~/.ansible/tmp
#forks = 5
#poll_interval = 15
#sudo_user = root
#ask_sudo_pass = True
#ask_pass = True
#transport = smart
#remote_port = 22
#module_lang = C
#module_set_locale = False

# plays will gather facts by default, which contain information about
# the remote system.
#
# smart - gather by default, but don't regather if already gathered
# implicit - gather by default, turn off with gather_facts: False
# explicit - do not gather by default, must say gather_facts: True
#gathering = implicit ← コメントアウトされていますが、デフォルトは「gathering = implicit」です。明示的に指定したい場合はコメントアウトを外して設定をします。

 

 

 

ansible コマンドの場合

今回は Python で自動化したいため、「ansible」コマンドの方がいいのか「ansible-playbook」コマンドの方が良いのか比較検討します。

ansible コマンドで setup モジュールを指定してターゲットノードの情報を取得する例です。

[test@cent07 ansible]$ ansible -m setup -i hostlist 192.168.1.12
192.168.1.12 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.1.12"
        ],
        "ansible_all_ipv6_addresses": [],
        "ansible_apparmor": {
            "status": "disabled"
        },
        "ansible_architecture": "x86_64",
        "ansible_bios_date": "09/21/2015",
        "ansible_bios_version": "6.00",
        "ansible_cmdline": {
            "BOOT_IMAGE": "/vmlinuz-3.10.0-514.el7.x86_64",
            "LANG": "ja_JP.UTF-8",
            "crashkernel": "auto",
            "quiet": true,
            "rd.lvm.lv": "cl/swap",
            "rhgb": true,
            "ro": true,
            "root": "/dev/mapper/cl-root"
        },
        "ansible_date_time": {
            "date": "2017-09-10",
            "day": "10",
            "epoch": "1505030439",
            "hour": "17",
            "iso8601": "2017-09-10T08:00:39Z",
            "iso8601_basic": "20170910T170039027412",
            "iso8601_basic_short": "20170910T170039",
            "iso8601_micro": "2017-09-10T08:00:39.027581Z",
            "minute": "00",
            "month": "09",
            "second": "39",
            "time": "17:00:39",
            "tz": "JST",
            "tz_offset": "+0900",
            "weekday": "日曜日",
            "weekday_number": "0",
            "weeknumber": "36",
            "year": "2017"
        },
        "ansible_default_ipv4": {
            "address": "192.168.1.12",
            "alias": "ens160",
            "broadcast": "192.168.1.255",
            "gateway": "192.168.1.1",
            "interface": "ens160",
            "macaddress": "00:0c:29:6b:9d:b5",
            "mtu": 1500,
            "netmask": "255.255.255.0",
            "network": "192.168.1.0",
            "type": "ether"
        },
        "ansible_default_ipv6": {},
        "ansible_devices": {
            "fd0": {
                "holders": [],
                "host": "",
                "model": null,
                "partitions": {},
                "removable": "1",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "deadline",
                "sectors": "8",
                "sectorsize": "512",
                "size": "4.00 KB",
                "support_discard": "0",
                "vendor": null
            },
            "sda": {
                "holders": [],
                "host": "SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)",
                "model": "Virtual disk",
                "partitions": {
                    "sda1": {
                        "holders": [],
                        "sectors": "2097152",
                        "sectorsize": 512,
                        "size": "1.00 GB",
                        "start": "2048",
                        "uuid": "aa2722d7-9671-40ae-97de-bcd0e29871e8"
                    },
                    "sda2": {
                        "holders": [
                            "cl-root",
                            "cl-swap"
                        ],
                        "sectors": "31455232",
                        "sectorsize": 512,
                        "size": "15.00 GB",
                        "start": "2099200",
                        "uuid": null
                    }
                },
                "removable": "0",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "deadline",
                "sectors": "33554432",
                "sectorsize": "512",
                "size": "16.00 GB",
                "support_discard": "0",
                "vendor": "VMware"
            },
            "sr0": {
                "holders": [],
                "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",
                "model": "VMware IDE CDR10",
                "partitions": {},
                "removable": "1",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "cfq",
                "sectors": "16173056",
                "sectorsize": "2048",
                "size": "30.85 GB",
                "support_discard": "0",
                "vendor": "NECVMWar"
            }
        },
        "ansible_distribution": "CentOS",
        "ansible_distribution_major_version": "7",
        "ansible_distribution_release": "Core",
        "ansible_distribution_version": "7.3.1611",
        "ansible_dns": {
            "nameservers": [
                "8.8.8.8"
            ]
        },
        "ansible_domain": "",
        "ansible_effective_group_id": 1000,
        "ansible_effective_user_id": 1000,
        "ansible_ens160": {
            "active": true,
            "device": "ens160",
            "features": {
                "busy_poll": "off [fixed]",
                "fcoe_mtu": "off [fixed]",
                "generic_receive_offload": "on",
                "generic_segmentation_offload": "on",
                "highdma": "on",
                "hw_tc_offload": "off [fixed]",
                "l2_fwd_offload": "off [fixed]",
                "large_receive_offload": "on",
                "loopback": "off [fixed]",
                "netns_local": "off [fixed]",
                "ntuple_filters": "off [fixed]",
                "receive_hashing": "off [fixed]",
                "rx_all": "off [fixed]",
                "rx_checksumming": "on",
                "rx_fcs": "off [fixed]",
                "rx_vlan_filter": "on [fixed]",
                "rx_vlan_offload": "on",
                "rx_vlan_stag_filter": "off [fixed]",
                "rx_vlan_stag_hw_parse": "off [fixed]",
                "scatter_gather": "on",
                "tcp_segmentation_offload": "on",
                "tx_checksum_fcoe_crc": "off [fixed]",
                "tx_checksum_ip_generic": "on",
                "tx_checksum_ipv4": "off [fixed]",
                "tx_checksum_ipv6": "off [fixed]",
                "tx_checksum_sctp": "off [fixed]",
                "tx_checksumming": "on",
                "tx_fcoe_segmentation": "off [fixed]",
                "tx_gre_segmentation": "off [fixed]",
                "tx_gso_robust": "off [fixed]",
                "tx_ipip_segmentation": "off [fixed]",
                "tx_lockless": "off [fixed]",
                "tx_mpls_segmentation": "off [fixed]",
                "tx_nocache_copy": "off",
                "tx_scatter_gather": "on",
                "tx_scatter_gather_fraglist": "off [fixed]",
                "tx_sctp_segmentation": "off [fixed]",
                "tx_sit_segmentation": "off [fixed]",
                "tx_tcp6_segmentation": "on",
                "tx_tcp_ecn_segmentation": "off [fixed]",
                "tx_tcp_segmentation": "on",
                "tx_udp_tnl_segmentation": "off [fixed]",
                "tx_vlan_offload": "on",
                "tx_vlan_stag_hw_insert": "off [fixed]",
                "udp_fragmentation_offload": "off [fixed]",
                "vlan_challenged": "off [fixed]"
            },
            "ipv4": {
                "address": "192.168.1.12",
                "broadcast": "192.168.1.255",
                "netmask": "255.255.255.0",
                "network": "192.168.1.0"
            },
            "macaddress": "00:0c:29:6b:9d:b5",
            "module": "vmxnet3",
            "mtu": 1500,
            "pciid": "0000:03:00.0",
            "promisc": false,
            "speed": 10000,
            "type": "ether"
        },
        "ansible_env": {
            "HOME": "/home/test",
            "LANG": "ja_JP.UTF-8",
            "LESSOPEN": "||/usr/bin/lesspipe.sh %s",
            "LOGNAME": "test",
            "LS_COLORS": "rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:",
            "MAIL": "/var/mail/test",
            "PATH": "/usr/local/bin:/usr/bin",
            "PWD": "/home/test",
            "SELINUX_LEVEL_REQUESTED": "",
            "SELINUX_ROLE_REQUESTED": "",
            "SELINUX_USE_CURRENT_RANGE": "",
            "SHELL": "/bin/bash",
            "SHLVL": "2",
            "SSH_CLIENT": "192.168.1.12 60936 22",
            "SSH_CONNECTION": "192.168.1.12 60936 192.168.1.12 22",
            "SSH_TTY": "/dev/pts/4",
            "TERM": "xterm",
            "USER": "test",
            "XDG_RUNTIME_DIR": "/run/user/1000",
            "XDG_SESSION_ID": "22",
            "_": "/usr/bin/python"
        },
        "ansible_fips": false,
        "ansible_form_factor": "Other",
        "ansible_fqdn": "cent07",
        "ansible_gather_subset": [
            "hardware",
            "network",
            "virtual"
        ],
        "ansible_hostname": "cent07",
        "ansible_interfaces": [
            "ens160",
            "lo"
        ],
        "ansible_kernel": "3.10.0-514.el7.x86_64",
        "ansible_lo": {
            "active": true,
            "device": "lo",
            "features": {
                "busy_poll": "off [fixed]",
                "fcoe_mtu": "off [fixed]",
                "generic_receive_offload": "on",
                "generic_segmentation_offload": "on",
                "highdma": "on [fixed]",
                "hw_tc_offload": "off [fixed]",
                "l2_fwd_offload": "off [fixed]",
                "large_receive_offload": "off [fixed]",
                "loopback": "on [fixed]",
                "netns_local": "on [fixed]",
                "ntuple_filters": "off [fixed]",
                "receive_hashing": "off [fixed]",
                "rx_all": "off [fixed]",
                "rx_checksumming": "on [fixed]",
                "rx_fcs": "off [fixed]",
                "rx_vlan_filter": "off [fixed]",
                "rx_vlan_offload": "off [fixed]",
                "rx_vlan_stag_filter": "off [fixed]",
                "rx_vlan_stag_hw_parse": "off [fixed]",
                "scatter_gather": "on",
                "tcp_segmentation_offload": "on",
                "tx_checksum_fcoe_crc": "off [fixed]",
                "tx_checksum_ip_generic": "on [fixed]",
                "tx_checksum_ipv4": "off [fixed]",
                "tx_checksum_ipv6": "off [fixed]",
                "tx_checksum_sctp": "on [fixed]",
                "tx_checksumming": "on",
                "tx_fcoe_segmentation": "off [fixed]",
                "tx_gre_segmentation": "off [fixed]",
                "tx_gso_robust": "off [fixed]",
                "tx_ipip_segmentation": "off [fixed]",
                "tx_lockless": "on [fixed]",
                "tx_mpls_segmentation": "off [fixed]",
                "tx_nocache_copy": "off [fixed]",
                "tx_scatter_gather": "on [fixed]",
                "tx_scatter_gather_fraglist": "on [fixed]",
                "tx_sctp_segmentation": "on",
                "tx_sit_segmentation": "off [fixed]",
                "tx_tcp6_segmentation": "on",
                "tx_tcp_ecn_segmentation": "on",
                "tx_tcp_segmentation": "on",
                "tx_udp_tnl_segmentation": "off [fixed]",
                "tx_vlan_offload": "off [fixed]",
                "tx_vlan_stag_hw_insert": "off [fixed]",
                "udp_fragmentation_offload": "on",
                "vlan_challenged": "on [fixed]"
            },
            "ipv4": {
                "address": "127.0.0.1",
                "broadcast": "host",
                "netmask": "255.0.0.0",
                "network": "127.0.0.0"
            },
            "mtu": 65536,
            "promisc": false,
            "type": "loopback"
        },
        "ansible_machine": "x86_64",
        "ansible_machine_id": "078151465fc1419ca8a5d3f1dd8e4358",
        "ansible_memfree_mb": 586,
        "ansible_memory_mb": {
            "nocache": {
                "free": 717,
                "used": 275
            },
            "real": {
                "free": 586,
                "total": 992,
                "used": 406
            },
            "swap": {
                "cached": 0,
                "free": 1639,
                "total": 1639,
                "used": 0
            }
        },
        "ansible_memtotal_mb": 992,
        "ansible_mounts": [
            {
                "device": "/dev/mapper/cl-root",
                "fstype": "xfs",
                "mount": "/",
                "options": "rw,seclabel,relatime,attr2,inode64,noquota",
                "size_available": 12798021632,
                "size_total": 14371782656,
                "uuid": "37c2f8c1-0eba-4d09-93dd-77a07c2fa2df"
            },
            {
                "device": "/dev/sda1",
                "fstype": "xfs",
                "mount": "/boot",
                "options": "rw,seclabel,relatime,attr2,inode64,noquota",
                "size_available": 916279296,
                "size_total": 1063256064,
                "uuid": "aa2722d7-9671-40ae-97de-bcd0e29871e8"
            }
        ],
        "ansible_nodename": "cent07",
        "ansible_os_family": "RedHat",
        "ansible_pkg_mgr": "yum",
        "ansible_processor": [
            "GenuineIntel",
            "Intel(R) Core(TM) i5 CPU       M 480  @ 2.67GHz"
        ],
        "ansible_processor_cores": 1,
        "ansible_processor_count": 1,
        "ansible_processor_threads_per_core": 1,
        "ansible_processor_vcpus": 1,
        "ansible_product_name": "VMware Virtual Platform",
        "ansible_product_serial": "NA",
        "ansible_product_uuid": "NA",
        "ansible_product_version": "None",
        "ansible_python": {
            "executable": "/usr/bin/python",
            "has_sslcontext": true,
            "type": "CPython",
            "version": {
                "major": 2,
                "micro": 5,
                "minor": 7,
                "releaselevel": "final",
                "serial": 0
            },
            "version_info": [
                2,
                7,
                5,
                "final",
                0
            ]
        },
        "ansible_python_version": "2.7.5",
        "ansible_real_group_id": 1000,
        "ansible_real_user_id": 1000,
        "ansible_selinux": {
            "config_mode": "enforcing",
            "mode": "enforcing",
            "policyvers": 28,
            "status": "enabled",
            "type": "targeted"
        },
        "ansible_service_mgr": "systemd",
        "ansible_ssh_host_key_ecdsa_public": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBI6RisZF04a4x2sKl95kuush7I8b56a2Vq/OajyVzh2xlxqOiYsrkM8ZZFJHklLNjYFViXok+ZwnLSWOshnsmH8=",
        "ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIKbL2EK6Iefg+5MTdICviJwtiXK68F07tqD1aEt4j0JN",
        "ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDUaIVVUEd+7NCewS573ze/CczMPMV1l0O18ZJ0kao11Gkmdz+81Vgb5ap+Et38CMWxJohxFtVldsZtDnryzu9pddNWgxecai4+snxXpiwTqM/Z2hsm4QKpUXdewvbj3w5F7IHboTIph18HEor0fSHZCzW22ADpKcq6CLIzTez9F7v+FNt0MRJjW9k84BGYp8I+PjCIYRLP53zgz4BZCeiiR7ewR5yV9jRFLm95viS+3IbG8Pm10ZaYZ0xjDR5IxxMhEPh5bjbdJ73CDlAkzW3MIpuFXvteMs/GVWvQ6lwem1fJ0Bs3FKNEJ8TZXARjb2JhI+zOpjHILZUF9Wjl7eJd",
        "ansible_swapfree_mb": 1639,
        "ansible_swaptotal_mb": 1639,
        "ansible_system": "Linux",
        "ansible_system_capabilities": [
            ""
        ],
        "ansible_system_capabilities_enforced": "True",
        "ansible_system_vendor": "VMware, Inc.",
        "ansible_uptime_seconds": 9821,
        "ansible_user_dir": "/home/test",
        "ansible_user_gecos": "test",
        "ansible_user_gid": 1000,
        "ansible_user_id": "test",
        "ansible_user_shell": "/bin/bash",
        "ansible_user_uid": 1000,
        "ansible_userspace_architecture": "x86_64",
        "ansible_userspace_bits": "64",
        "ansible_virtualization_role": "guest",
        "ansible_virtualization_type": "VMware",
        "module_setup": true
    },
    "changed": false
}
[test@cent07 ansible]$

 

 

ansible-playbook コマンドの場合

setup モジュールで「gather_facts」を取得して、結果をすべて出力する Playbook を作成します。

[test@cent07 ansible]$ vi test-setup-module-playbook.yml
- hosts: 192.168.1.12
  become: true
  become_user: root
  become_method: sudo
  gather_facts: no
  tasks:
    - setup: ← ここで「setup」モジュールを実行してターゲットノードの情報を取得します。
      register: result ← 取得した情報を「result」に保存します。

    - debug:
        var: result ← debug モジュールで結果を全て出力します。

 

 

上記の Playbook を実行した ansible-playbook コマンド実行結果です。

[test@cent07 ansible]$ ansible-playbook -i hostlist test-setup-module-playbook.yml

PLAY [192.168.1.12] ************************************************************************************

TASK [setup] *******************************************************************************************
ok: [192.168.1.12]

TASK [debug] *******************************************************************************************
ok: [192.168.1.12] => {
    "result": {
        "ansible_facts": {
            "ansible_all_ipv4_addresses": [
                "192.168.1.12"
            ],
            "ansible_all_ipv6_addresses": [],
            "ansible_apparmor": {
                "status": "disabled"
            },
            "ansible_architecture": "x86_64",
            "ansible_bios_date": "09/21/2015",
            "ansible_bios_version": "6.00",
            "ansible_cmdline": {
                "BOOT_IMAGE": "/vmlinuz-3.10.0-514.el7.x86_64",
                "LANG": "ja_JP.UTF-8",
                "crashkernel": "auto",
                "quiet": true,
                "rd.lvm.lv": "cl/swap",
                "rhgb": true,
                "ro": true,
                "root": "/dev/mapper/cl-root"
            },
            "ansible_date_time": {
                "date": "2017-09-10",
                "day": "10",
                "epoch": "1505033430",
                "hour": "17",
                "iso8601": "2017-09-10T08:50:30Z",
                "iso8601_basic": "20170910T175030282579",
                "iso8601_basic_short": "20170910T175030",
                "iso8601_micro": "2017-09-10T08:50:30.282716Z",
                "minute": "50",
                "month": "09",
                "second": "30",
                "time": "17:50:30",
                "tz": "JST",
                "tz_offset": "+0900",
                "weekday": "日曜日",
                "weekday_number": "0",
                "weeknumber": "36",
                "year": "2017"
            },
            "ansible_default_ipv4": {
                "address": "192.168.1.12",
                "alias": "ens160",
                "broadcast": "192.168.1.255",
                "gateway": "192.168.1.1",
                "interface": "ens160",
                "macaddress": "00:0c:29:6b:9d:b5",
                "mtu": 1500,
                "netmask": "255.255.255.0",
                "network": "192.168.1.0",
                "type": "ether"
            },
            "ansible_default_ipv6": {},
            "ansible_devices": {
                "fd0": {
                    "holders": [],
                    "host": "",
                    "model": null,
                    "partitions": {},
                    "removable": "1",
                    "rotational": "1",
                    "sas_address": null,
                    "sas_device_handle": null,
                    "scheduler_mode": "deadline",
                    "sectors": "8",
                    "sectorsize": "512",
                    "size": "4.00 KB",
                    "support_discard": "0",
                    "vendor": null
                },
                "sda": {
                    "holders": [],
                    "host": "SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)",
                    "model": "Virtual disk",
                    "partitions": {
                        "sda1": {
                            "holders": [],
                            "sectors": "2097152",
                            "sectorsize": 512,
                            "size": "1.00 GB",
                            "start": "2048",
                            "uuid": "aa2722d7-9671-40ae-97de-bcd0e29871e8"
                        },
                        "sda2": {
                            "holders": [
                                "cl-root",
                                "cl-swap"
                            ],
                            "sectors": "31455232",
                            "sectorsize": 512,
                            "size": "15.00 GB",
                            "start": "2099200",
                            "uuid": null
                        }
                    },
                    "removable": "0",
                    "rotational": "1",
                    "sas_address": null,
                    "sas_device_handle": null,
                    "scheduler_mode": "deadline",
                    "sectors": "33554432",
                    "sectorsize": "512",
                    "size": "16.00 GB",
                    "support_discard": "0",
                    "vendor": "VMware"
                },
                "sr0": {
                    "holders": [],
                    "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",
                    "model": "VMware IDE CDR10",
                    "partitions": {},
                    "removable": "1",
                    "rotational": "1",
                    "sas_address": null,
                    "sas_device_handle": null,
                    "scheduler_mode": "cfq",
                    "sectors": "16173056",
                    "sectorsize": "2048",
                    "size": "30.85 GB",
                    "support_discard": "0",
                    "vendor": "NECVMWar"
                }
            },
            "ansible_distribution": "CentOS",
            "ansible_distribution_major_version": "7",
            "ansible_distribution_release": "Core",
            "ansible_distribution_version": "7.3.1611",
            "ansible_dns": {
                "nameservers": [
                    "8.8.8.8"
                ]
            },
            "ansible_domain": "",
            "ansible_effective_group_id": 0,
            "ansible_effective_user_id": 0,
            "ansible_ens160": {
                "active": true,
                "device": "ens160",
                "features": {
                    "busy_poll": "off [fixed]",
                    "fcoe_mtu": "off [fixed]",
                    "generic_receive_offload": "on",
                    "generic_segmentation_offload": "on",
                    "highdma": "on",
                    "hw_tc_offload": "off [fixed]",
                    "l2_fwd_offload": "off [fixed]",
                    "large_receive_offload": "on",
                    "loopback": "off [fixed]",
                    "netns_local": "off [fixed]",
                    "ntuple_filters": "off [fixed]",
                    "receive_hashing": "off [fixed]",
                    "rx_all": "off [fixed]",
                    "rx_checksumming": "on",
                    "rx_fcs": "off [fixed]",
                    "rx_vlan_filter": "on [fixed]",
                    "rx_vlan_offload": "on",
                    "rx_vlan_stag_filter": "off [fixed]",
                    "rx_vlan_stag_hw_parse": "off [fixed]",
                    "scatter_gather": "on",
                    "tcp_segmentation_offload": "on",
                    "tx_checksum_fcoe_crc": "off [fixed]",
                    "tx_checksum_ip_generic": "on",
                    "tx_checksum_ipv4": "off [fixed]",
                    "tx_checksum_ipv6": "off [fixed]",
                    "tx_checksum_sctp": "off [fixed]",
                    "tx_checksumming": "on",
                    "tx_fcoe_segmentation": "off [fixed]",
                    "tx_gre_segmentation": "off [fixed]",
                    "tx_gso_robust": "off [fixed]",
                    "tx_ipip_segmentation": "off [fixed]",
                    "tx_lockless": "off [fixed]",
                    "tx_mpls_segmentation": "off [fixed]",
                    "tx_nocache_copy": "off",
                    "tx_scatter_gather": "on",
                    "tx_scatter_gather_fraglist": "off [fixed]",
                    "tx_sctp_segmentation": "off [fixed]",
                    "tx_sit_segmentation": "off [fixed]",
                    "tx_tcp6_segmentation": "on",
                    "tx_tcp_ecn_segmentation": "off [fixed]",
                    "tx_tcp_segmentation": "on",
                    "tx_udp_tnl_segmentation": "off [fixed]",
                    "tx_vlan_offload": "on",
                    "tx_vlan_stag_hw_insert": "off [fixed]",
                    "udp_fragmentation_offload": "off [fixed]",
                    "vlan_challenged": "off [fixed]"
                },
                "ipv4": {
                    "address": "192.168.1.12",
                    "broadcast": "192.168.1.255",
                    "netmask": "255.255.255.0",
                    "network": "192.168.1.0"
                },
                "macaddress": "00:0c:29:6b:9d:b5",
                "module": "vmxnet3",
                "mtu": 1500,
                "pciid": "0000:03:00.0",
                "promisc": false,
                "speed": 10000,
                "type": "ether"
            },
            "ansible_env": {
                "HOME": "/root",
                "LANG": "ja_JP.UTF-8",
                "LOGNAME": "root",
                "LS_COLORS": "rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:",
                "MAIL": "/var/mail/test",
                "PATH": "/sbin:/bin:/usr/sbin:/usr/bin",
                "PWD": "/home/test",
                "SHELL": "/bin/bash",
                "SHLVL": "1",
                "SUDO_COMMAND": "/bin/sh -c echo BECOME-SUCCESS-ctmepwvouyuaauyhjghmeoozlhnfjiyb; /usr/bin/python /home/test/.ansible/tmp/ansible-tmp-1505033428.6-241035206450585/setup.py; rm -rf \"/home/test/.ansible/tmp/ansible-tmp-1505033428.6-241035206450585/\" > /dev/null 2>&1",
                "SUDO_GID": "1000",
                "SUDO_UID": "1000",
                "SUDO_USER": "test",
                "TERM": "xterm",
                "USER": "root",
                "USERNAME": "root",
                "_": "/usr/bin/python"
            },
            "ansible_fips": false,
            "ansible_form_factor": "Other",
            "ansible_fqdn": "cent07",
            "ansible_gather_subset": [
                "hardware",
                "network",
                "virtual"
            ],
            "ansible_hostname": "cent07",
            "ansible_interfaces": [
                "ens160",
                "lo"
            ],
            "ansible_kernel": "3.10.0-514.el7.x86_64",
            "ansible_lo": {
                "active": true,
                "device": "lo",
                "features": {
                    "busy_poll": "off [fixed]",
                    "fcoe_mtu": "off [fixed]",
                    "generic_receive_offload": "on",
                    "generic_segmentation_offload": "on",
                    "highdma": "on [fixed]",
                    "hw_tc_offload": "off [fixed]",
                    "l2_fwd_offload": "off [fixed]",
                    "large_receive_offload": "off [fixed]",
                    "loopback": "on [fixed]",
                    "netns_local": "on [fixed]",
                    "ntuple_filters": "off [fixed]",
                    "receive_hashing": "off [fixed]",
                    "rx_all": "off [fixed]",
                    "rx_checksumming": "on [fixed]",
                    "rx_fcs": "off [fixed]",
                    "rx_vlan_filter": "off [fixed]",
                    "rx_vlan_offload": "off [fixed]",
                    "rx_vlan_stag_filter": "off [fixed]",
                    "rx_vlan_stag_hw_parse": "off [fixed]",
                    "scatter_gather": "on",
                    "tcp_segmentation_offload": "on",
                    "tx_checksum_fcoe_crc": "off [fixed]",
                    "tx_checksum_ip_generic": "on [fixed]",
                    "tx_checksum_ipv4": "off [fixed]",
                    "tx_checksum_ipv6": "off [fixed]",
                    "tx_checksum_sctp": "on [fixed]",
                    "tx_checksumming": "on",
                    "tx_fcoe_segmentation": "off [fixed]",
                    "tx_gre_segmentation": "off [fixed]",
                    "tx_gso_robust": "off [fixed]",
                    "tx_ipip_segmentation": "off [fixed]",
                    "tx_lockless": "on [fixed]",
                    "tx_mpls_segmentation": "off [fixed]",
                    "tx_nocache_copy": "off [fixed]",
                    "tx_scatter_gather": "on [fixed]",
                    "tx_scatter_gather_fraglist": "on [fixed]",
                    "tx_sctp_segmentation": "on",
                    "tx_sit_segmentation": "off [fixed]",
                    "tx_tcp6_segmentation": "on",
                    "tx_tcp_ecn_segmentation": "on",
                    "tx_tcp_segmentation": "on",
                    "tx_udp_tnl_segmentation": "off [fixed]",
                    "tx_vlan_offload": "off [fixed]",
                    "tx_vlan_stag_hw_insert": "off [fixed]",
                    "udp_fragmentation_offload": "on",
                    "vlan_challenged": "on [fixed]"
                },
                "ipv4": {
                    "address": "127.0.0.1",
                    "broadcast": "host",
                    "netmask": "255.0.0.0",
                    "network": "127.0.0.0"
                },
                "mtu": 65536,
                "promisc": false,
                "type": "loopback"
            },
            "ansible_lvm": {
                "lvs": {
                    "root": {
                        "size_g": "13.39",
                        "vg": "cl"
                    },
                    "swap": {
                        "size_g": "1.60",
                        "vg": "cl"
                    }
                },
                "vgs": {
                    "cl": {
                        "free_g": "0",
                        "num_lvs": "2",
                        "num_pvs": "1",
                        "size_g": "15.00"
                    }
                }
            },
            "ansible_machine": "x86_64",
            "ansible_machine_id": "078151465fc1419ca8a5d3f1dd8e4358",
            "ansible_memfree_mb": 582,
            "ansible_memory_mb": {
                "nocache": {
                    "free": 718,
                    "used": 274
                },
                "real": {
                    "free": 582,
                    "total": 992,
                    "used": 410
                },
                "swap": {
                    "cached": 0,
                    "free": 1639,
                    "total": 1639,
                    "used": 0
                }
            },
            "ansible_memtotal_mb": 992,
            "ansible_mounts": [
                {
                    "device": "/dev/mapper/cl-root",
                    "fstype": "xfs",
                    "mount": "/",
                    "options": "rw,seclabel,relatime,attr2,inode64,noquota",
                    "size_available": 12797603840,
                    "size_total": 14371782656,
                    "uuid": "37c2f8c1-0eba-4d09-93dd-77a07c2fa2df"
                },
                {
                    "device": "/dev/sda1",
                    "fstype": "xfs",
                    "mount": "/boot",
                    "options": "rw,seclabel,relatime,attr2,inode64,noquota",
                    "size_available": 916279296,
                    "size_total": 1063256064,
                    "uuid": "aa2722d7-9671-40ae-97de-bcd0e29871e8"
                }
            ],
            "ansible_nodename": "cent07",
            "ansible_os_family": "RedHat",
            "ansible_pkg_mgr": "yum",
            "ansible_processor": [
                "GenuineIntel",
                "Intel(R) Core(TM) i5 CPU       M 480  @ 2.67GHz"
            ],
            "ansible_processor_cores": 1,
            "ansible_processor_count": 1,
            "ansible_processor_threads_per_core": 1,
            "ansible_processor_vcpus": 1,
            "ansible_product_name": "VMware Virtual Platform",
            "ansible_product_serial": "VMware-56 4d 19 f1 e4 30 5c f8-a5 ec 80 24 85 6b 9d b5",
            "ansible_product_uuid": "564D19F1-E430-5CF8-A5EC-8024856B9DB5",
            "ansible_product_version": "None",
            "ansible_python": {
                "executable": "/usr/bin/python",
                "has_sslcontext": true,
                "type": "CPython",
                "version": {
                    "major": 2,
                    "micro": 5,
                    "minor": 7,
                    "releaselevel": "final",
                    "serial": 0
                },
                "version_info": [
                    2,
                    7,
                    5,
                    "final",
                    0
                ]
            },
            "ansible_python_version": "2.7.5",
            "ansible_real_group_id": 0,
            "ansible_real_user_id": 0,
            "ansible_selinux": {
                "config_mode": "enforcing",
                "mode": "enforcing",
                "policyvers": 28,
                "status": "enabled",
                "type": "targeted"
            },
            "ansible_service_mgr": "systemd",
            "ansible_ssh_host_key_ecdsa_public": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBI6RisZF04a4x2sKl95kuush7I8b56a2Vq/OajyVzh2xlxqOiYsrkM8ZZFJHklLNjYFViXok+ZwnLSWOshnsmH8=",
            "ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIKbL2EK6Iefg+5MTdICviJwtiXK68F07tqD1aEt4j0JN",
            "ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDUaIVVUEd+7NCewS573ze/CczMPMV1l0O18ZJ0kao11Gkmdz+81Vgb5ap+Et38CMWxJohxFtVldsZtDnryzu9pddNWgxecai4+snxXpiwTqM/Z2hsm4QKpUXdewvbj3w5F7IHboTIph18HEor0fSHZCzW22ADpKcq6CLIzTez9F7v+FNt0MRJjW9k84BGYp8I+PjCIYRLP53zgz4BZCeiiR7ewR5yV9jRFLm95viS+3IbG8Pm10ZaYZ0xjDR5IxxMhEPh5bjbdJ73CDlAkzW3MIpuFXvteMs/GVWvQ6lwem1fJ0Bs3FKNEJ8TZXARjb2JhI+zOpjHILZUF9Wjl7eJd",
            "ansible_swapfree_mb": 1639,
            "ansible_swaptotal_mb": 1639,
            "ansible_system": "Linux",
            "ansible_system_capabilities": [
                "cap_chown",
                "cap_dac_override",
                "cap_dac_read_search",
                "cap_fowner",
                "cap_fsetid",
                "cap_kill",
                "cap_setgid",
                "cap_setuid",
                "cap_setpcap",
                "cap_linux_immutable",
                "cap_net_bind_service",
                "cap_net_broadcast",
                "cap_net_admin",
                "cap_net_raw",
                "cap_ipc_lock",
                "cap_ipc_owner",
                "cap_sys_module",
                "cap_sys_rawio",
                "cap_sys_chroot",
                "cap_sys_ptrace",
                "cap_sys_pacct",
                "cap_sys_admin",
                "cap_sys_boot",
                "cap_sys_nice",
                "cap_sys_resource",
                "cap_sys_time",
                "cap_sys_tty_config",
                "cap_mknod",
                "cap_lease",
                "cap_audit_write",
                "cap_audit_control",
                "cap_setfcap",
                "cap_mac_override",
                "cap_mac_admin",
                "cap_syslog",
                "35",
                "36+ep"
            ],
            "ansible_system_capabilities_enforced": "True",
            "ansible_system_vendor": "VMware, Inc.",
            "ansible_uptime_seconds": 12812,
            "ansible_user_dir": "/root",
            "ansible_user_gecos": "root",
            "ansible_user_gid": 0,
            "ansible_user_id": "root",
            "ansible_user_shell": "/bin/bash",
            "ansible_user_uid": 0,
            "ansible_userspace_architecture": "x86_64",
            "ansible_userspace_bits": "64",
            "ansible_virtualization_role": "guest",
            "ansible_virtualization_type": "VMware",
            "module_setup": true
        },
        "changed": false
    }
}

PLAY RECAP *********************************************************************************************
192.168.1.12               : ok=2    changed=0    unreachable=0    failed=0

[test@cent07 ansible]$

 

 

ansible コマンドと ansible-playbook コマンドの実行結果の差分を確認する

ansible コマンドと ansible-playbook コマンドの実行結果に差分があるか確認するために「WinMerge」で比較します。

ざっくりと比較した感じでは、出力される値の順番は異なりますが、同じ値を取得しています。

 

使い勝手が良さそうなのは「ansible」コマンドの方でした。

しかし、以前 Python で JSON 形式のデータをパースした際に Ansible の環境変数「ANSIBLE_CONFIG=/home/test/ansible/json_ansible.cfg」で ansible-playbook コマンドの出力結果を JSON 形式で出力したことを思い出しました。

 

【Ansible】【Python】Ansible で取得した JSON 形式のデータをパースして CSV、Excel 形式にコンバートするプログラム

 

そのため、今回も「ANSIBLE_CONFIG」JSON 形式で出力する方法にします。

[test@cent07 ansible]$ pwd
/home/test/ansible
[test@cent07 ansible]$ vi json_ansible.cfg ← JSON 用のコンフィグフィルを作成します。
[defaults]
stdout_callback = json ← この設定を入れると JSON 形式で出力されます。

 

 

名前を「json_ansible.cfg」と変更しているので、実行時に「ANSIBLE_CONFIG=/home/test/ansible/json_ansible.cfg」をつけます。

【例】

ANSIBLE_CONFIG=/home/test/ansible/json_ansible.cfg ansible-playbook -i hostlist test-setup-module-playbook.yml

 

上記のように最初に「ANSIBLE_CONFIG=/home/test/ansible/json_ansible.cfg」を読み込ませることで最優先で環境を設定できます。

 

ということで、構成的には「ansible-playbook」コマンドで「setup」モジュールを実行して JSON 形式で情報出力させることにします。

 

 

ansible コマンドで setup モジュールの情報をファイルに吐き出す

以下のように ansible コマンドを実行してファイルに出力します。

[test@cent07 ansible]$ ANSIBLE_CONFIG=/home/test/ansible/json_ansible.cfg ansible-playbook -i hostlist test-setup-module-playbook.yml > 192.168.1.12.json

 

念のためファイルの中身を確認します。

JSON 形式で出力されています。

{
    "plays": [
        {
            "play": {
                "id": "000c296b-9db5-f58d-9176-000000000004",
                "name": "192.168.1.12"
            },
            "tasks": [
                {
                    "hosts": {
                        "192.168.1.12": {
                            "_ansible_no_log": false,
                            "_ansible_parsed": true,
                            "_ansible_verbose_override": true,
                            "ansible_facts": {
                                "ansible_all_ipv4_addresses": [
                                    "192.168.1.12"
                                ],
                                "ansible_all_ipv6_addresses": [],
                                "ansible_apparmor": {
                                    "status": "disabled"
                                },
                                "ansible_architecture": "x86_64",
                                "ansible_bios_date": "09/21/2015",
                                "ansible_bios_version": "6.00",
                                "ansible_cmdline": {
                                    "BOOT_IMAGE": "/vmlinuz-3.10.0-514.el7.x86_64",
                                    "LANG": "ja_JP.UTF-8",
                                    "crashkernel": "auto",
                                    "quiet": true,
                                    "rd.lvm.lv": "cl/swap",
                                    "rhgb": true,
                                    "ro": true,
                                    "root": "/dev/mapper/cl-root"
                                },

 

 

ここから Python でパースします。

 

 

Python で Ansible の JSON 出力ファイルをパースする

まずはツールを使って JSON の構成を確認します。

JSON 形式で出力されたファイルを開くと、以下のように一応は整っていますが、それでもまだ構成が分かりにくいです。

そのため、ツールを使って JSON ファイルをツリー上にして構成を分かりやすくします。

{
    "plays": [
        {
            "play": {
                "id": "000c296b-9db5-f58d-9176-000000000004",
                "name": "192.168.1.12"
            },
            "tasks": [
                {
                    "hosts": {
                        "192.168.1.12": {
                            "_ansible_no_log": false,
                            "_ansible_parsed": true,
                            "_ansible_verbose_override": true,
                            "ansible_facts": {
                                "ansible_all_ipv4_addresses": [
                                    "192.168.1.12"
                                ],
                                "ansible_all_ipv6_addresses": [],
                                "ansible_apparmor": {
                                    "status": "disabled"
                                },
                                "ansible_architecture": "x86_64",
                                "ansible_bios_date": "09/21/2015",
                                "ansible_bios_version": "6.00",
                                "ansible_cmdline": {
                                    "BOOT_IMAGE": "/vmlinuz-3.10.0-514.el7.x86_64",
                                    "LANG": "ja_JP.UTF-8",
                                    "crashkernel": "auto",
                                    "quiet": true,
                                    "rd.lvm.lv": "cl/swap",
                                    "rhgb": true,
                                    "ro": true,
                                    "root": "/dev/mapper/cl-root"
                                },

 

 

フリー(無料)の JSONedit が JSON をツリー上にできるので便利

JSONedit のダウンロード URL

http://tomeko.net/software/JSONedit/

 

JSONedit のページに移動したら、ページに下の方にスクロールをして一番最新のツールをダウンロードします。

【Ansible】【Python】Ansible の setup で取得したデータをパースして CSV、Excel 形式にコンバートするプログラム

 

 

zip ファイルをダウンロードして解凍すると下図のように「JSONedit.exe」ファイルができるのでダブルクリックします。

【Ansible】【Python】Ansible の setup で取得したデータをパースして CSV、Excel 形式にコンバートするプログラム

 

JSONedit が起動したら「File」-「Open」をクリックして、JSON ファイル(今回の場合は「192.168.1.12.json」ファイル)を読み込みます。

【Ansible】【Python】Ansible の setup で取得したデータをパースして CSV、Excel 形式にコンバートするプログラム

 

 

JSON ファイルを読み込んだら左側ペインの「Tree」タブをクリックします。

【Ansible】【Python】Ansible の setup で取得したデータをパースして CSV、Excel 形式にコンバートするプログラム

 

 

[+]のつまみをクリックして展開して JSON ファイルの構造を確認します。

【Ansible】【Python】Ansible の setup で取得したデータをパースして CSV、Excel 形式にコンバートするプログラム

 

 

下図のような感じで JSON 構造が一発で分かります。

私的にはこのツールは非常に有用で、JSON 構造が直感的に分かるので重宝しています。

例えば下図を見ると、欲しい情報は [plays] - [0] - [tasks] - [0] - [hosts] - [192.168.1.12] - [ansible_facts] の下にあることが分かります。

そのためプログラムが作りやすいです。

【Ansible】【Python】Ansible の setup で取得したデータをパースして CSV、Excel 形式にコンバートするプログラム

 

 

もしこのツールがないと、JSON ファイルから直接辿って行かなければいけないため、プログラム作成に時間が掛かると思います。

{
    "plays": [
        {
            "play": {
                "id": "000c296b-9db5-f58d-9176-000000000004",
                "name": "192.168.1.12"
            },
            "tasks": [
                {
                    "hosts": {
                        "192.168.1.12": {
                            "_ansible_no_log": false,
                            "_ansible_parsed": true,
                            "_ansible_verbose_override": true,
                            "ansible_facts": {
                                "ansible_all_ipv4_addresses": [
                                    "192.168.1.12"
                                ],
                                "ansible_all_ipv6_addresses": [],
                                "ansible_apparmor": {
                                    "status": "disabled"
                                },
                                "ansible_architecture": "x86_64",
                                "ansible_bios_date": "09/21/2015",
                                "ansible_bios_version": "6.00",
                                "ansible_cmdline": {
                                    "BOOT_IMAGE": "/vmlinuz-3.10.0-514.el7.x86_64",
                                    "LANG": "ja_JP.UTF-8",
                                    "crashkernel": "auto",
                                    "quiet": true,
                                    "rd.lvm.lv": "cl/swap",
                                    "rhgb": true,
                                    "ro": true,
                                    "root": "/dev/mapper/cl-root"
                                },

 

 

 

Python プログラム(途中経過)

まだ完成ではありませんが、ここまで情報を取得できるようになりました。

【プログラム】

[test@cent07 ansible]$ vi setup_parse_01.py
#coding:utf-8
import json
import sys

f = open('/home/test/ansible/192.168.1.12.json','r')

json_dict = json.load(f)

for tasks_key in json_dict["plays"]:
    for i in tasks_key["tasks"][0]['hosts']['192.168.1.12']['ansible_facts'].items():
        print(i)

 

【プログラムの実行結果】

プログラムを実行すると以下のようになります。

出力結果は、Python のタプル型で出力されています。

[test@cent07 ansible]$ python3.6 setup_parse_01.py
('ansible_all_ipv4_addresses', ['192.168.1.12'])
('ansible_all_ipv6_addresses', [])
('ansible_apparmor', {'status': 'disabled'})
('ansible_architecture', 'x86_64')
('ansible_bios_date', '09/21/2015')
('ansible_bios_version', '6.00')
('ansible_cmdline', {'BOOT_IMAGE': '/vmlinuz-3.10.0-514.el7.x86_64', 'LANG': 'ja_JP.UTF-8', 'crashkernel': 'auto', 'quiet': True, 'rd.lvm.lv': 'cl/swap', 'rhgb': True, 'ro': True, 'root': '/dev/mapper/cl-root'})
('ansible_date_time', {'date': '2017-09-10', 'day': '10', 'epoch': '1505042818', 'hour': '20', 'iso8601': '2017-09-10T11:26:58Z', 'iso8601_basic': '20170910T202658078493', 'iso8601_basic_short': '20170910T202658', 'iso8601_micro': '2017-09-10T11:26:58.078637Z', 'minute': '26', 'month': '09', 'second': '58', 'time': '20:26:58', 'tz': 'JST', 'tz_offset': '+0900', 'weekday': '日曜日', 'weekday_number': '0', 'weeknumber': '36', 'year': '2017'})
('ansible_default_ipv4', {'address': '192.168.1.12', 'alias': 'ens160', 'broadcast': '192.168.1.255', 'gateway': '192.168.1.1', 'interface': 'ens160', 'macaddress': '00:0c:29:6b:9d:b5', 'mtu': 1500, 'netmask': '255.255.255.0', 'network': '192.168.1.0', 'type': 'ether'})
('ansible_default_ipv6', {})
('ansible_devices', {'fd0': {'holders': [], 'host': '', 'model': None, 'partitions': {}, 'removable': '1', 'rotational': '1', 'sas_address': None, 'sas_device_handle': None, 'scheduler_mode': 'deadline', 'sectors': '8', 'sectorsize': '512', 'size': '4.00 KB', 'support_discard': '0', 'vendor': None}, 'sda': {'holders': [], 'host': 'SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)', 'model': 'Virtual disk', 'partitions': {'sda1': {'holders': [], 'sectors': '2097152', 'sectorsize': 512, 'size': '1.00 GB', 'start': '2048', 'uuid': 'aa2722d7-9671-40ae-97de-bcd0e29871e8'}, 'sda2': {'holders': ['cl-root', 'cl-swap'], 'sectors': '31455232', 'sectorsize': 512, 'size': '15.00 GB', 'start': '2099200', 'uuid': None}}, 'removable': '0', 'rotational': '1', 'sas_address': None, 'sas_device_handle': None, 'scheduler_mode': 'deadline', 'sectors': '33554432', 'sectorsize': '512', 'size': '16.00 GB', 'support_discard': '0', 'vendor': 'VMware'}, 'sr0': {'holders': [], 'host': 'IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)', 'model': 'VMware IDE CDR10', 'partitions': {}, 'removable': '1', 'rotational': '1', 'sas_address': None, 'sas_device_handle': None, 'scheduler_mode': 'cfq', 'sectors': '16173056', 'sectorsize': '2048', 'size': '30.85 GB', 'support_discard': '0', 'vendor': 'NECVMWar'}})
('ansible_distribution', 'CentOS')
('ansible_distribution_major_version', '7')
('ansible_distribution_release', 'Core')
('ansible_distribution_version', '7.3.1611')
('ansible_dns', {'nameservers': ['8.8.8.8']})
('ansible_domain', '')
('ansible_effective_group_id', 0)
('ansible_effective_user_id', 0)
('ansible_ens160', {'active': True, 'device': 'ens160', 'features': {'busy_poll': 'off [fixed]', 'fcoe_mtu': 'off [fixed]', 'generic_receive_offload': 'on', 'generic_segmentation_offload': 'on', 'highdma': 'on', 'hw_tc_offload': 'off [fixed]', 'l2_fwd_offload': 'off [fixed]', 'large_receive_offload': 'on', 'loopback': 'off [fixed]', 'netns_local': 'off [fixed]', 'ntuple_filters': 'off [fixed]', 'receive_hashing': 'off [fixed]', 'rx_all': 'off [fixed]', 'rx_checksumming': 'on', 'rx_fcs': 'off [fixed]', 'rx_vlan_filter': 'on [fixed]', 'rx_vlan_offload': 'on', 'rx_vlan_stag_filter': 'off [fixed]', 'rx_vlan_stag_hw_parse': 'off [fixed]', 'scatter_gather': 'on', 'tcp_segmentation_offload': 'on', 'tx_checksum_fcoe_crc': 'off [fixed]', 'tx_checksum_ip_generic': 'on', 'tx_checksum_ipv4': 'off [fixed]', 'tx_checksum_ipv6': 'off [fixed]', 'tx_checksum_sctp': 'off [fixed]', 'tx_checksumming': 'on', 'tx_fcoe_segmentation': 'off [fixed]', 'tx_gre_segmentation': 'off [fixed]', 'tx_gso_robust': 'off [fixed]', 'tx_ipip_segmentation': 'off [fixed]', 'tx_lockless': 'off [fixed]', 'tx_mpls_segmentation': 'off [fixed]', 'tx_nocache_copy': 'off', 'tx_scatter_gather': 'on', 'tx_scatter_gather_fraglist': 'off [fixed]', 'tx_sctp_segmentation': 'off [fixed]', 'tx_sit_segmentation': 'off [fixed]', 'tx_tcp6_segmentation': 'on', 'tx_tcp_ecn_segmentation': 'off [fixed]', 'tx_tcp_segmentation': 'on', 'tx_udp_tnl_segmentation': 'off [fixed]', 'tx_vlan_offload': 'on', 'tx_vlan_stag_hw_insert': 'off [fixed]', 'udp_fragmentation_offload': 'off [fixed]', 'vlan_challenged': 'off [fixed]'}, 'ipv4': {'address': '192.168.1.12', 'broadcast': '192.168.1.255', 'netmask': '255.255.255.0', 'network': '192.168.1.0'}, 'macaddress': '00:0c:29:6b:9d:b5', 'module': 'vmxnet3', 'mtu': 1500, 'pciid': '0000:03:00.0', 'promisc': False, 'speed': 10000, 'type': 'ether'})
('ansible_env', {'HOME': '/root', 'LANG': 'ja_JP.UTF-8', 'LOGNAME': 'root', 'LS_COLORS': 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:', 'MAIL': '/var/mail/test', 'PATH': '/sbin:/bin:/usr/sbin:/usr/bin', 'PWD': '/home/test', 'SHELL': '/bin/bash', 'SHLVL': '1', 'SUDO_COMMAND': '/bin/sh -c echo BECOME-SUCCESS-srbmpgkiudqfvhtxlxkdglkqrljwgmys; /usr/bin/python /home/test/.ansible/tmp/ansible-tmp-1505042816.4-257607136295527/setup.py; rm -rf "/home/test/.ansible/tmp/ansible-tmp-1505042816.4-257607136295527/" > /dev/null 2>&1', 'SUDO_GID': '1000', 'SUDO_UID': '1000', 'SUDO_USER': 'test', 'TERM': 'xterm', 'USER': 'root', 'USERNAME': 'root', '_': '/usr/bin/python'})
('ansible_fips', False)
('ansible_form_factor', 'Other')
('ansible_fqdn', 'cent07')
('ansible_gather_subset', ['hardware', 'network', 'virtual'])
('ansible_hostname', 'cent07')
('ansible_interfaces', ['ens160', 'lo'])
('ansible_kernel', '3.10.0-514.el7.x86_64')
('ansible_lo', {'active': True, 'device': 'lo', 'features': {'busy_poll': 'off [fixed]', 'fcoe_mtu': 'off [fixed]', 'generic_receive_offload': 'on', 'generic_segmentation_offload': 'on', 'highdma': 'on [fixed]', 'hw_tc_offload': 'off [fixed]', 'l2_fwd_offload': 'off [fixed]', 'large_receive_offload': 'off [fixed]', 'loopback': 'on [fixed]', 'netns_local': 'on [fixed]', 'ntuple_filters': 'off [fixed]', 'receive_hashing': 'off [fixed]', 'rx_all': 'off [fixed]', 'rx_checksumming': 'on [fixed]', 'rx_fcs': 'off [fixed]', 'rx_vlan_filter': 'off [fixed]', 'rx_vlan_offload': 'off [fixed]', 'rx_vlan_stag_filter': 'off [fixed]', 'rx_vlan_stag_hw_parse': 'off [fixed]', 'scatter_gather': 'on', 'tcp_segmentation_offload': 'on', 'tx_checksum_fcoe_crc': 'off [fixed]', 'tx_checksum_ip_generic': 'on [fixed]', 'tx_checksum_ipv4': 'off [fixed]', 'tx_checksum_ipv6': 'off [fixed]', 'tx_checksum_sctp': 'on [fixed]', 'tx_checksumming': 'on', 'tx_fcoe_segmentation': 'off [fixed]', 'tx_gre_segmentation': 'off [fixed]', 'tx_gso_robust': 'off [fixed]', 'tx_ipip_segmentation': 'off [fixed]', 'tx_lockless': 'on [fixed]', 'tx_mpls_segmentation': 'off [fixed]', 'tx_nocache_copy': 'off [fixed]', 'tx_scatter_gather': 'on [fixed]', 'tx_scatter_gather_fraglist': 'on [fixed]', 'tx_sctp_segmentation': 'on', 'tx_sit_segmentation': 'off [fixed]', 'tx_tcp6_segmentation': 'on', 'tx_tcp_ecn_segmentation': 'on', 'tx_tcp_segmentation': 'on', 'tx_udp_tnl_segmentation': 'off [fixed]', 'tx_vlan_offload': 'off [fixed]', 'tx_vlan_stag_hw_insert': 'off [fixed]', 'udp_fragmentation_offload': 'on', 'vlan_challenged': 'on [fixed]'}, 'ipv4': {'address': '127.0.0.1', 'broadcast': 'host', 'netmask': '255.0.0.0', 'network': '127.0.0.0'}, 'mtu': 65536, 'promisc': False, 'type': 'loopback'})
('ansible_lvm', {'lvs': {'root': {'size_g': '13.39', 'vg': 'cl'}, 'swap': {'size_g': '1.60', 'vg': 'cl'}}, 'vgs': {'cl': {'free_g': '0', 'num_lvs': '2', 'num_pvs': '1', 'size_g': '15.00'}}})
('ansible_machine', 'x86_64')
('ansible_machine_id', '078151465fc1419ca8a5d3f1dd8e4358')
('ansible_memfree_mb', 577)
('ansible_memory_mb', {'nocache': {'free': 716, 'used': 276}, 'real': {'free': 577, 'total': 992, 'used': 415}, 'swap': {'cached': 0, 'free': 1639, 'total': 1639, 'used': 0}})
('ansible_memtotal_mb', 992)
('ansible_mounts', [{'device': '/dev/mapper/cl-root', 'fstype': 'xfs', 'mount': '/', 'options': 'rw,seclabel,relatime,attr2,inode64,noquota', 'size_available': 12797620224, 'size_total': 14371782656, 'uuid': '37c2f8c1-0eba-4d09-93dd-77a07c2fa2df'}, {'device': '/dev/sda1', 'fstype': 'xfs', 'mount': '/boot', 'options': 'rw,seclabel,relatime,attr2,inode64,noquota', 'size_available': 916279296, 'size_total': 1063256064, 'uuid': 'aa2722d7-9671-40ae-97de-bcd0e29871e8'}])
('ansible_nodename', 'cent07')
('ansible_os_family', 'RedHat')
('ansible_pkg_mgr', 'yum')
('ansible_processor', ['GenuineIntel', 'Intel(R) Core(TM) i5 CPU M 480 @ 2.67GHz'])
('ansible_processor_cores', 1)
('ansible_processor_count', 1)
('ansible_processor_threads_per_core', 1)
('ansible_processor_vcpus', 1)
('ansible_product_name', 'VMware Virtual Platform')
('ansible_product_serial', 'VMware-56 4d 19 f1 e4 30 5c f8-a5 ec 80 24 85 6b 9d b5')
('ansible_product_uuid', '564D19F1-E430-5CF8-A5EC-8024856B9DB5')
('ansible_product_version', 'None')
('ansible_python', {'executable': '/usr/bin/python', 'has_sslcontext': True, 'type': 'CPython', 'version': {'major': 2, 'micro': 5, 'minor': 7, 'releaselevel': 'final', 'serial': 0}, 'version_info': [2, 7, 5, 'final', 0]})
('ansible_python_version', '2.7.5')
('ansible_real_group_id', 0)
('ansible_real_user_id', 0)
('ansible_selinux', {'config_mode': 'enforcing', 'mode': 'enforcing', 'policyvers': 28, 'status': 'enabled', 'type': 'targeted'})
('ansible_service_mgr', 'systemd')
('ansible_ssh_host_key_ecdsa_public', 'AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBI6RisZF04a4x2sKl95kuush7I8b56a2Vq/OajyVzh2xlxqOiYsrkM8ZZFJHklLNjYFViXok+ZwnLSWOshnsmH8=')
('ansible_ssh_host_key_ed25519_public', 'AAAAC3NzaC1lZDI1NTE5AAAAIKbL2EK6Iefg+5MTdICviJwtiXK68F07tqD1aEt4j0JN')
('ansible_ssh_host_key_rsa_public', 'AAAAB3NzaC1yc2EAAAADAQABAAABAQDUaIVVUEd+7NCewS573ze/CczMPMV1l0O18ZJ0kao11Gkmdz+81Vgb5ap+Et38CMWxJohxFtVldsZtDnryzu9pddNWgxecai4+snxXpiwTqM/Z2hsm4QKpUXdewvbj3w5F7IHboTIph18HEor0fSHZCzW22ADpKcq6CLIzTez9F7v+FNt0MRJjW9k84BGYp8I+PjCIYRLP53zgz4BZCeiiR7ewR5yV9jRFLm95viS+3IbG8Pm10ZaYZ0xjDR5IxxMhEPh5bjbdJ73CDlAkzW3MIpuFXvteMs/GVWvQ6lwem1fJ0Bs3FKNEJ8TZXARjb2JhI+zOpjHILZUF9Wjl7eJd')
('ansible_swapfree_mb', 1639)
('ansible_swaptotal_mb', 1639)
('ansible_system', 'Linux')
('ansible_system_capabilities', ['cap_chown', 'cap_dac_override', 'cap_dac_read_search', 'cap_fowner', 'cap_fsetid', 'cap_kill', 'cap_setgid', 'cap_setuid', 'cap_setpcap', 'cap_linux_immutable', 'cap_net_bind_service', 'cap_net_broadcast', 'cap_net_admin', 'cap_net_raw', 'cap_ipc_lock', 'cap_ipc_owner', 'cap_sys_module', 'cap_sys_rawio', 'cap_sys_chroot', 'cap_sys_ptrace', 'cap_sys_pacct', 'cap_sys_admin', 'cap_sys_boot', 'cap_sys_nice', 'cap_sys_resource', 'cap_sys_time', 'cap_sys_tty_config', 'cap_mknod', 'cap_lease', 'cap_audit_write', 'cap_audit_control', 'cap_setfcap', 'cap_mac_override', 'cap_mac_admin', 'cap_syslog', '35', '36+ep'])
('ansible_system_capabilities_enforced', 'True')
('ansible_system_vendor', 'VMware, Inc.')
('ansible_uptime_seconds', 22200)
('ansible_user_dir', '/root')
('ansible_user_gecos', 'root')
('ansible_user_gid', 0)
('ansible_user_id', 'root')
('ansible_user_shell', '/bin/bash')
('ansible_user_uid', 0)
('ansible_userspace_architecture', 'x86_64')
('ansible_userspace_bits', '64')
('ansible_virtualization_role', 'guest')
('ansible_virtualization_type', 'VMware')
('module_setup', True)

 

 

Python のタプル型とは?

簡単に特徴をまとめますと、

  • カッコ()で囲まれている
  • [0]、[1]で値を取得できる
  •  値を変更することができない
  • 値がリスト型でもOK

です。

 

たとえば、

('ansible_bios_date', '09/21/2015')

の場合は、ディクショナリ型で例えれば、[0]がキーで[1]がバリューのような構造と言えます。

 

さらに

('ansible_all_ipv4_addresses', ['192.168.1.12'])

のように値がリスト型になっているものもあります。

 

さらに

('ansible_lvm', {'lvs': {'root': {'size_g': '13.39', 'vg': 'cl'}, 'swap': {'size_g': '1.60', 'vg': 'cl'}}, 'vgs': {'cl': {'free_g': '0', 'num_lvs': '2', 'num_pvs': '1', 'size_g': '15.00'}}})

のように値がディクショナリ型、しかも入れ子になっているものもあります。

 

 

まずは全部の情報を取得して、全部の情報を CSV・Excel 形式に出力します。

ただ、以下のように入れ子構造になっているものもあり、入れ子の深さもバラバラなので、整形して CSV・Excel 形式で出力する入れ子のレベルを決めます。

('ansible_all_ipv4_addresses', ['192.168.1.12'])
('ansible_all_ipv6_addresses', [])
('ansible_apparmor', {'status': 'disabled'})
('ansible_architecture', 'x86_64')
('ansible_bios_date', '09/21/2015')
('ansible_bios_version', '6.00')
('ansible_cmdline', {'BOOT_IMAGE': '/vmlinuz-3.10.0-514.el7.x86_64', 'LANG': 'ja_JP.UTF-8', 'crashkernel': 'auto', 'quiet': True, 'rd.lvm.lv': 'cl/swap', 'rhgb': True, 'ro': True, 'root': '/dev/mapper/cl-root'})
('ansible_date_time', {'date': '2017-09-10', 'day': '10', 'epoch': '1505042818', 'hour': '20', 'iso8601': '2017-09-10T11:26:58Z', 'iso8601_basic': '20170910T202658078493', 'iso8601_basic_short': '20170910T202658', 'iso8601_micro': '2017-09-10T11:26:58.078637Z', 'minute': '26', 'month': '09', 'second': '58', 'time': '20:26:58', 'tz': 'JST', 'tz_offset': '+0900', 'weekday': '日曜日', 'weekday_number': '0', 'weeknumber': '36', 'year': '2017'})
('ansible_default_ipv4', {'address': '192.168.1.12', 'alias': 'ens160', 'broadcast': '192.168.1.255', 'gateway': '192.168.1.1', 'interface': 'ens160', 'macaddress': '00:0c:29:6b:9d:b5', 'mtu': 1500, 'netmask': '255.255.255.0', 'network': '192.168.1.0', 'type': 'ether'})
('ansible_default_ipv6', {})
('ansible_devices', {'fd0': {'holders': [], 'host': '', 'model': None, 'partitions': {}, 'removable': '1', 'rotational': '1', 'sas_address': None, 'sas_device_handle': None, 'scheduler_mode': 'deadline', 'sectors': '8', 'sectorsize': '512', 'size': '4.00 KB', 'support_discard': '0', 'vendor': None}, 'sda': {'holders': [], 'host': 'SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)', 'model': 'Virtual disk', 'partitions': {'sda1': {'holders': [], 'sectors': '2097152', 'sectorsize': 512, 'size': '1.00 GB', 'start': '2048', 'uuid': 'aa2722d7-9671-40ae-97de-bcd0e29871e8'}, 'sda2': {'holders': ['cl-root', 'cl-swap'], 'sectors': '31455232', 'sectorsize': 512, 'size': '15.00 GB', 'start': '2099200', 'uuid': None}}, 'removable': '0', 'rotational': '1', 'sas_address': None, 'sas_device_handle': None, 'scheduler_mode': 'deadline', 'sectors': '33554432', 'sectorsize': '512', 'size': '16.00 GB', 'support_discard': '0', 'vendor': 'VMware'}, 'sr0': {'holders': [], 'host': 'IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)', 'model': 'VMware IDE CDR10', 'partitions': {}, 'removable': '1', 'rotational': '1', 'sas_address': None, 'sas_device_handle': None, 'scheduler_mode': 'cfq', 'sectors': '16173056', 'sectorsize': '2048', 'size': '30.85 GB', 'support_discard': '0', 'vendor': 'NECVMWar'}})
('ansible_distribution', 'CentOS')
('ansible_distribution_major_version', '7')
('ansible_distribution_release', 'Core')
('ansible_distribution_version', '7.3.1611')
('ansible_dns', {'nameservers': ['8.8.8.8']})
('ansible_domain', '')
('ansible_effective_group_id', 0)
('ansible_effective_user_id', 0)
('ansible_ens160', {'active': True, 'device': 'ens160', 'features': {'busy_poll': 'off [fixed]', 'fcoe_mtu': 'off [fixed]', 'generic_receive_offload': 'on', 'generic_segmentation_offload': 'on', 'highdma': 'on', 'hw_tc_offload': 'off [fixed]', 'l2_fwd_offload': 'off [fixed]', 'large_receive_offload': 'on', 'loopback': 'off [fixed]', 'netns_local': 'off [fixed]', 'ntuple_filters': 'off [fixed]', 'receive_hashing': 'off [fixed]', 'rx_all': 'off [fixed]', 'rx_checksumming': 'on', 'rx_fcs': 'off [fixed]', 'rx_vlan_filter': 'on [fixed]', 'rx_vlan_offload': 'on', 'rx_vlan_stag_filter': 'off [fixed]', 'rx_vlan_stag_hw_parse': 'off [fixed]', 'scatter_gather': 'on', 'tcp_segmentation_offload': 'on', 'tx_checksum_fcoe_crc': 'off [fixed]', 'tx_checksum_ip_generic': 'on', 'tx_checksum_ipv4': 'off [fixed]', 'tx_checksum_ipv6': 'off [fixed]', 'tx_checksum_sctp': 'off [fixed]', 'tx_checksumming': 'on', 'tx_fcoe_segmentation': 'off [fixed]', 'tx_gre_segmentation': 'off [fixed]', 'tx_gso_robust': 'off [fixed]', 'tx_ipip_segmentation': 'off [fixed]', 'tx_lockless': 'off [fixed]', 'tx_mpls_segmentation': 'off [fixed]', 'tx_nocache_copy': 'off', 'tx_scatter_gather': 'on', 'tx_scatter_gather_fraglist': 'off [fixed]', 'tx_sctp_segmentation': 'off [fixed]', 'tx_sit_segmentation': 'off [fixed]', 'tx_tcp6_segmentation': 'on', 'tx_tcp_ecn_segmentation': 'off [fixed]', 'tx_tcp_segmentation': 'on', 'tx_udp_tnl_segmentation': 'off [fixed]', 'tx_vlan_offload': 'on', 'tx_vlan_stag_hw_insert': 'off [fixed]', 'udp_fragmentation_offload': 'off [fixed]', 'vlan_challenged': 'off [fixed]'}, 'ipv4': {'address': '192.168.1.12', 'broadcast': '192.168.1.255', 'netmask': '255.255.255.0', 'network': '192.168.1.0'}, 'macaddress': '00:0c:29:6b:9d:b5', 'module': 'vmxnet3', 'mtu': 1500, 'pciid': '0000:03:00.0', 'promisc': False, 'speed': 10000, 'type': 'ether'})
('ansible_env', {'HOME': '/root', 'LANG': 'ja_JP.UTF-8', 'LOGNAME': 'root', 'LS_COLORS': 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:', 'MAIL': '/var/mail/test', 'PATH': '/sbin:/bin:/usr/sbin:/usr/bin', 'PWD': '/home/test', 'SHELL': '/bin/bash', 'SHLVL': '1', 'SUDO_COMMAND': '/bin/sh -c echo BECOME-SUCCESS-srbmpgkiudqfvhtxlxkdglkqrljwgmys; /usr/bin/python /home/test/.ansible/tmp/ansible-tmp-1505042816.4-257607136295527/setup.py; rm -rf "/home/test/.ansible/tmp/ansible-tmp-1505042816.4-257607136295527/" > /dev/null 2>&1', 'SUDO_GID': '1000', 'SUDO_UID': '1000', 'SUDO_USER': 'test', 'TERM': 'xterm', 'USER': 'root', 'USERNAME': 'root', '_': '/usr/bin/python'})
('ansible_fips', False)
('ansible_form_factor', 'Other')
('ansible_fqdn', 'cent07')
('ansible_gather_subset', ['hardware', 'network', 'virtual'])
('ansible_hostname', 'cent07')
('ansible_interfaces', ['ens160', 'lo'])
('ansible_kernel', '3.10.0-514.el7.x86_64')
('ansible_lo', {'active': True, 'device': 'lo', 'features': {'busy_poll': 'off [fixed]', 'fcoe_mtu': 'off [fixed]', 'generic_receive_offload': 'on', 'generic_segmentation_offload': 'on', 'highdma': 'on [fixed]', 'hw_tc_offload': 'off [fixed]', 'l2_fwd_offload': 'off [fixed]', 'large_receive_offload': 'off [fixed]', 'loopback': 'on [fixed]', 'netns_local': 'on [fixed]', 'ntuple_filters': 'off [fixed]', 'receive_hashing': 'off [fixed]', 'rx_all': 'off [fixed]', 'rx_checksumming': 'on [fixed]', 'rx_fcs': 'off [fixed]', 'rx_vlan_filter': 'off [fixed]', 'rx_vlan_offload': 'off [fixed]', 'rx_vlan_stag_filter': 'off [fixed]', 'rx_vlan_stag_hw_parse': 'off [fixed]', 'scatter_gather': 'on', 'tcp_segmentation_offload': 'on', 'tx_checksum_fcoe_crc': 'off [fixed]', 'tx_checksum_ip_generic': 'on [fixed]', 'tx_checksum_ipv4': 'off [fixed]', 'tx_checksum_ipv6': 'off [fixed]', 'tx_checksum_sctp': 'on [fixed]', 'tx_checksumming': 'on', 'tx_fcoe_segmentation': 'off [fixed]', 'tx_gre_segmentation': 'off [fixed]', 'tx_gso_robust': 'off [fixed]', 'tx_ipip_segmentation': 'off [fixed]', 'tx_lockless': 'on [fixed]', 'tx_mpls_segmentation': 'off [fixed]', 'tx_nocache_copy': 'off [fixed]', 'tx_scatter_gather': 'on [fixed]', 'tx_scatter_gather_fraglist': 'on [fixed]', 'tx_sctp_segmentation': 'on', 'tx_sit_segmentation': 'off [fixed]', 'tx_tcp6_segmentation': 'on', 'tx_tcp_ecn_segmentation': 'on', 'tx_tcp_segmentation': 'on', 'tx_udp_tnl_segmentation': 'off [fixed]', 'tx_vlan_offload': 'off [fixed]', 'tx_vlan_stag_hw_insert': 'off [fixed]', 'udp_fragmentation_offload': 'on', 'vlan_challenged': 'on [fixed]'}, 'ipv4': {'address': '127.0.0.1', 'broadcast': 'host', 'netmask': '255.0.0.0', 'network': '127.0.0.0'}, 'mtu': 65536, 'promisc': False, 'type': 'loopback'})
('ansible_lvm', {'lvs': {'root': {'size_g': '13.39', 'vg': 'cl'}, 'swap': {'size_g': '1.60', 'vg': 'cl'}}, 'vgs': {'cl': {'free_g': '0', 'num_lvs': '2', 'num_pvs': '1', 'size_g': '15.00'}}})
('ansible_machine', 'x86_64')
('ansible_machine_id', '078151465fc1419ca8a5d3f1dd8e4358')
('ansible_memfree_mb', 577)
('ansible_memory_mb', {'nocache': {'free': 716, 'used': 276}, 'real': {'free': 577, 'total': 992, 'used': 415}, 'swap': {'cached': 0, 'free': 1639, 'total': 1639, 'used': 0}})
('ansible_memtotal_mb', 992)
('ansible_mounts', [{'device': '/dev/mapper/cl-root', 'fstype': 'xfs', 'mount': '/', 'options': 'rw,seclabel,relatime,attr2,inode64,noquota', 'size_available': 12797620224, 'size_total': 14371782656, 'uuid': '37c2f8c1-0eba-4d09-93dd-77a07c2fa2df'}, {'device': '/dev/sda1', 'fstype': 'xfs', 'mount': '/boot', 'options': 'rw,seclabel,relatime,attr2,inode64,noquota', 'size_available': 916279296, 'size_total': 1063256064, 'uuid': 'aa2722d7-9671-40ae-97de-bcd0e29871e8'}])
('ansible_nodename', 'cent07')
('ansible_os_family', 'RedHat')
('ansible_pkg_mgr', 'yum')
('ansible_processor', ['GenuineIntel', 'Intel(R) Core(TM) i5 CPU M 480 @ 2.67GHz'])
('ansible_processor_cores', 1)
('ansible_processor_count', 1)
('ansible_processor_threads_per_core', 1)
('ansible_processor_vcpus', 1)
('ansible_product_name', 'VMware Virtual Platform')
('ansible_product_serial', 'VMware-56 4d 19 f1 e4 30 5c f8-a5 ec 80 24 85 6b 9d b5')
('ansible_product_uuid', '564D19F1-E430-5CF8-A5EC-8024856B9DB5')
('ansible_product_version', 'None')
('ansible_python', {'executable': '/usr/bin/python', 'has_sslcontext': True, 'type': 'CPython', 'version': {'major': 2, 'micro': 5, 'minor': 7, 'releaselevel': 'final', 'serial': 0}, 'version_info': [2, 7, 5, 'final', 0]})
('ansible_python_version', '2.7.5')
('ansible_real_group_id', 0)
('ansible_real_user_id', 0)
('ansible_selinux', {'config_mode': 'enforcing', 'mode': 'enforcing', 'policyvers': 28, 'status': 'enabled', 'type': 'targeted'})
('ansible_service_mgr', 'systemd')
('ansible_ssh_host_key_ecdsa_public', 'AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBI6RisZF04a4x2sKl95kuush7I8b56a2Vq/OajyVzh2xlxqOiYsrkM8ZZFJHklLNjYFViXok+ZwnLSWOshnsmH8=')
('ansible_ssh_host_key_ed25519_public', 'AAAAC3NzaC1lZDI1NTE5AAAAIKbL2EK6Iefg+5MTdICviJwtiXK68F07tqD1aEt4j0JN')
('ansible_ssh_host_key_rsa_public', 'AAAAB3NzaC1yc2EAAAADAQABAAABAQDUaIVVUEd+7NCewS573ze/CczMPMV1l0O18ZJ0kao11Gkmdz+81Vgb5ap+Et38CMWxJohxFtVldsZtDnryzu9pddNWgxecai4+snxXpiwTqM/Z2hsm4QKpUXdewvbj3w5F7IHboTIph18HEor0fSHZCzW22ADpKcq6CLIzTez9F7v+FNt0MRJjW9k84BGYp8I+PjCIYRLP53zgz4BZCeiiR7ewR5yV9jRFLm95viS+3IbG8Pm10ZaYZ0xjDR5IxxMhEPh5bjbdJ73CDlAkzW3MIpuFXvteMs/GVWvQ6lwem1fJ0Bs3FKNEJ8TZXARjb2JhI+zOpjHILZUF9Wjl7eJd')
('ansible_swapfree_mb', 1639)
('ansible_swaptotal_mb', 1639)
('ansible_system', 'Linux')
('ansible_system_capabilities', ['cap_chown', 'cap_dac_override', 'cap_dac_read_search', 'cap_fowner', 'cap_fsetid', 'cap_kill', 'cap_setgid', 'cap_setuid', 'cap_setpcap', 'cap_linux_immutable', 'cap_net_bind_service', 'cap_net_broadcast', 'cap_net_admin', 'cap_net_raw', 'cap_ipc_lock', 'cap_ipc_owner', 'cap_sys_module', 'cap_sys_rawio', 'cap_sys_chroot', 'cap_sys_ptrace', 'cap_sys_pacct', 'cap_sys_admin', 'cap_sys_boot', 'cap_sys_nice', 'cap_sys_resource', 'cap_sys_time', 'cap_sys_tty_config', 'cap_mknod', 'cap_lease', 'cap_audit_write', 'cap_audit_control', 'cap_setfcap', 'cap_mac_override', 'cap_mac_admin', 'cap_syslog', '35', '36+ep'])
('ansible_system_capabilities_enforced', 'True')
('ansible_system_vendor', 'VMware, Inc.')
('ansible_uptime_seconds', 22200)
('ansible_user_dir', '/root')
('ansible_user_gecos', 'root')
('ansible_user_gid', 0)
('ansible_user_id', 'root')
('ansible_user_shell', '/bin/bash')
('ansible_user_uid', 0)
('ansible_userspace_architecture', 'x86_64')
('ansible_userspace_bits', '64')
('ansible_virtualization_role', 'guest')
('ansible_virtualization_type', 'VMware')
('module_setup', True)

 

 

JSONedit で入れ子の深さの確認をすると、

  •  [plays] - [0] - [tasks] - [0] - [hosts] - [192.168.1.12] - [ansible_facts] - [ansible_xxxx] - [値]
  •  [plays] - [0] - [tasks] - [0] - [hosts] - [192.168.1.12] - [ansible_facts] - [ansible_xxxx] - [ディクショナリ型変数] - [ [key] [value],[key] [value],・・・]
  •  [plays] - [0] - [tasks] - [0] - [hosts] - [192.168.1.12] - [ansible_facts] - [ansible_xxxx] - [list型変数] - [ [0],[1],[2],[3],[4],[5]・・・]
  •  [plays] - [0] - [tasks] - [0] - [hosts] - [192.168.1.12] - [ansible_facts] - [ansible_xxxx(ディクショナリ型変数)] - [ [key] [value],[key] [value],・・・]
  •  [plays] - [0] - [tasks] - [0] - [hosts] - [192.168.1.12] - [ansible_facts] - [ansible_xxxx(list型変数)] - [ [0],[1],[2],[3],[4],[5]・・・]

というパターンになりそうです。

 

【例】

下図の「ansible_lo」の場合は、

  • [plays] - [0] - [tasks] - [0] - [hosts] - [192.168.1.12] - [ansible_facts] - [ansible_lo(dict型)] - [ [active] : [true] ]
  • [plays] - [0] - [tasks] - [0] - [hosts] - [192.168.1.12] - [ansible_facts] - [ansible_lo(dict型)] - [ [device] : [lo]
  • [plays] - [0] - [tasks] - [0] - [hosts] - [192.168.1.12] - [ansible_facts] - [ansible_lo(dict型)] - [features] - [ [key] : [value],[key] : [value],・・・]
  • [plays] - [0] - [tasks] - [0] - [hosts] - [192.168.1.12] - [ansible_facts] - [ansible_lo] - [ipv4] - [ [address] : [127.0.0.1] ]
  • [plays] - [0] - [tasks] - [0] - [hosts] - [192.168.1.12] - [ansible_facts] - [ansible_lo] - [ipv4] - [ [broadcast] : [host] ]
  • [plays] - [0] - [tasks] - [0] - [hosts] - [192.168.1.12] - [ansible_facts] - [ansible_lo] - [ipv4] - [ [netmask] : [255.255.255.0] ]
  • [plays] - [0] - [tasks] - [0] - [hosts] - [192.168.1.12] - [ansible_facts] - [ansible_lo] - [ipv4] - [ [network] : [127.0.0.0] ]

という構成になりそうです。

【Ansible】【Python】Ansible の setup で取得したデータをパースして CSV、Excel 形式にコンバートするプログラム

 

プログラム上では、様々な型が現われるため、型のタイプをチェックして処理を変える必要があります。

また、プログラムで出力をすると「タプル型」で出力されます。

再度タプル型での構造も確認します。

('ansible_kernel', '3.10.0-514.el7.x86_64')
('ansible_lo', {'active': True, 'device': 'lo', 'features': {'busy_poll': 'off [fixed]', 'fcoe_mtu': 'off [fixed]', 'generic_receive_offload': 'on', 'generic_segmentation_offload': 'on', 'highdma': 'on [fixed]', 'hw_tc_offload': 'off [fixed]', 'l2_fwd_offload': 'off [fixed]', 'large_receive_offload': 'off [fixed]', 'loopback': 'on [fixed]', 'netns_local': 'on [fixed]', 'ntuple_filters': 'off [fixed]', 'receive_hashing': 'off [fixed]', 'rx_all': 'off [fixed]', 'rx_checksumming': 'on [fixed]', 'rx_fcs': 'off [fixed]', 'rx_vlan_filter': 'off [fixed]', 'rx_vlan_offload': 'off [fixed]', 'rx_vlan_stag_filter': 'off [fixed]', 'rx_vlan_stag_hw_parse': 'off [fixed]', 'scatter_gather': 'on', 'tcp_segmentation_offload': 'on', 'tx_checksum_fcoe_crc': 'off [fixed]', 'tx_checksum_ip_generic': 'on [fixed]', 'tx_checksum_ipv4': 'off [fixed]', 'tx_checksum_ipv6': 'off [fixed]', 'tx_checksum_sctp': 'on [fixed]', 'tx_checksumming': 'on', 'tx_fcoe_segmentation': 'off [fixed]', 'tx_gre_segmentation': 'off [fixed]', 'tx_gso_robust': 'off [fixed]', 'tx_ipip_segmentation': 'off [fixed]', 'tx_lockless': 'on [fixed]', 'tx_mpls_segmentation': 'off [fixed]', 'tx_nocache_copy': 'off [fixed]', 'tx_scatter_gather': 'on [fixed]', 'tx_scatter_gather_fraglist': 'on [fixed]', 'tx_sctp_segmentation': 'on', 'tx_sit_segmentation': 'off [fixed]', 'tx_tcp6_segmentation': 'on', 'tx_tcp_ecn_segmentation': 'on', 'tx_tcp_segmentation': 'on', 'tx_udp_tnl_segmentation': 'off [fixed]', 'tx_vlan_offload': 'off [fixed]', 'tx_vlan_stag_hw_insert': 'off [fixed]', 'udp_fragmentation_offload': 'on', 'vlan_challenged': 'on [fixed]'}, 'ipv4': {'address': '127.0.0.1', 'broadcast': 'host', 'netmask': '255.0.0.0', 'network': '127.0.0.0'}, 'mtu': 65536, 'promisc': False, 'type': 'loopback'})
('ansible_lvm', {'lvs': {'root': {'size_g': '13.39', 'vg': 'cl'}, 'swap': {'size_g': '1.60', 'vg': 'cl'}}, 'vgs': {'cl': {'free_g': '0', 'num_lvs': '2', 'num_pvs': '1', 'size_g': '15.00'}}})

 

タプル型の場合は、

([0(dct型でいうキー相当が来る)], [1(バリュー)])

([0(dct型でいうキー相当が来る)], [1(バリューがディクショナリ型)])

・・・

となるので、まずはタプル型変数の最初の値はディクショナリ型で言う「キー」と考えることができます。

そして、次の[1]からバリューとして扱っていいのか?ディクショナリ型として扱うのか?リスト型なのか?「型」のタイプを判定して条件分岐で処理を変えるということになりそうです。

 

 

タイプの確認方法

ここで一旦タイプの確認方法について調べます。

 

【サンプルプログラム】

#coding:utf-8

 

test1 = 100
test2 = 'test'
test3 = ('test', 'taple')
test4 = ['test', 'list']
test5 = {'test':'dict', 'test1':'dict'}

 

print(type(test1))
print(type(test2))
print(type(test3))
print(type(test4))
print(type(test5))

 

 

【実行結果】

[test@cent07 ansible]$ python3.6 python_type_check.py
<class 'int'>
<class 'str'>
<class 'tuple'>
<class 'list'>
<class 'dict'> 

 

プログラムの実行結果より方が判定できることが分かりましたので、この結果を元に条件分岐ができそうです。

 

タプルの[0] → str 型

タプルの[1] → str 型 → 値

タプルの[1] → int 型 → 値

【Ansible】【Python】Ansible の setup で取得したデータをパースして CSV、Excel 形式にコンバートするプログラム

タプルの[1] → list 型 → list[0]がキーとなるため、list[1]のチェックに進む

 → list[1] → str 型 → 値

【Ansible】【Python】Ansible の setup で取得したデータをパースして CSV、Excel 形式にコンバートするプログラム

 → list[1] → int 型 → 値

 → list[1] → dict 型 → [キー]:[バリュー]、[キー]:[バリュー] ※ここで打ち止め

【Ansible】【Python】Ansible の setup で取得したデータをパースして CSV、Excel 形式にコンバートするプログラム

タプルの[1] → dict 型 → dict[0]がキーとなるため、dict[1]のチェックに進む

 → dict[1] → dict 型 → [キー]:[バリュー]、[キー]:[バリュー] ※ここで打ち止め

 

まとめると以上のパターンになるでしょうか。

これを Python プログラムにします。

 

 

Pythonでの条件分岐

Pythonでの条件分岐です。

if 条件式:

    処理

elif 条件式:

    処理

else:

    処理

 

 

上記の条件分岐を今回のプログラムに当てはめます。

if taple[1] の type が int 型:

    処理

elif taple[1] の type が str 型:

    処理

elif taple[1] の type が list 型:

    処理

elif taple[1] の type が dict 型:

    処理

else:

    エラー処理

 

 

更に入れ子を含めます。

if taple[1] の type が int 型:

    処理

elif taple[1] の type が str 型:

    処理

elif taple[1] の type が list 型:

    if list[1] の type が int 型:

        処理

    elif list[1] の type が str 型:

        処理

    elif list[1] の type が list 型:

        処理

    elif list[1] の type が dict 型:

        処理

    else:

elif taple[1] の type が dict 型:

    if dict[1] の type が int 型:

        処理

    elif dict[1] の type が str 型:

        処理

    elif dict[1] の type が list 型:

        処理

    elif dict[1] の type が dict 型:

        処理

else:

 エラー処理

 

 

Python の条件式

オブジェクトの type を確認して条件式でどの処理をするのか決定します。

その条件式です。

 

プログラムを確認します。

 

【途中経過】

[test@cent07 ansible]$ cat setup_parse_01.py
#coding:utf-8
import json
import sys

f = open('/home/test/ansible/192.168.1.12.json','r')

json_dict = json.load(f)

for tasks_key in json_dict["plays"]:
    for i in tasks_key["tasks"][0]['hosts']['192.168.1.12']['ansible_facts'].items():
        print(i) ← ここで1行ずつ情報が出力されます。

 

 

【タイプを表示するプログラム】

[test@cent07 ansible]$ cat python_type_check.py
#coding:utf-8

 

test1 = 100
test2 = 'test'
test3 = ('test', 'taple')
test4 = ['test', 'list']
test5 = {'test':'dict', 'test1':'dict'}

 

print(type(test1))
print(type(test2))
print(type(test3))
print(type(test4))
print(type(test5))

[test@cent07 ansible]$ python3.6 python_type_check.py
<class 'int'>
<class 'str'>
<class 'tuple'>
<class 'list'>
<class 'dict'>
[test@cent07 ansible]$

 

 

変数を作り、type でタイプを取得し、

  • 変数==int の場合
  • 変数==str の場合
  • 変数==list の場合
  • 変数==dict の場合

というように条件式を作ります。

 

【サンプルプログラム】

初めに単純なサンプルプログラムを作成します。

オブジェクトのタイプを調べると「<class 'int'>」などが表示されます。

それを一旦文字列に変換して split 関数で分割をして欲しい値(list,str,int,dictなど)を取得します。

[test@cent07 ansible]$ cat setup_parse_01.py
#coding:utf-8
import json
import sys

f = open('/home/test/ansible/192.168.1.12.json','r')

json_dict = json.load(f)

for tasks_key in json_dict["plays"]:
    for i in tasks_key["tasks"][0]['hosts']['192.168.1.12']['ansible_facts'].items():

        # タプルの[1]のタイプを調べます。
        type_check = type(i[1])

        # type 関数での返り値を str に変換します。
        type_check = str(type_check)

        # <class 'dict'> などの返り値を split で分割します。
        type_check = type_check.split("'")

        # split で分割した値の2番目を取得します。
        type_checked = type_check[1]

        print(type_checked)

[test@cent07 ansible]$

 

 

プログラムを実行します。

問題なくオブジェクトのタイプが取得できていますが、「bool」型もありました。

[test@cent07 ansible]$ python3.6 setup_parse_01.py
list
list
dict
str
str
str
dict
dict
dict
dict
dict
str
str
str
str
dict
str
int
int
dict
dict
bool ← bool 型もありました。
str
str
list
str
list
str
dict
dict
str
str
int
dict
int
list
str
str
str
list
int
int
int
int
str
str
str
str
dict
str
int
int
dict
str
str
str
str
int
int
str
list
str
str
int
str
str
int
str
str
int
str
str
str
str
bool ← bool 型もありました。
[test@cent07 ansible]$

 

 

さらに条件分岐がちゃんとできるか確認するために改良しました。

[test@cent07 ansible]$ cat setup_parse_01.py
#coding:utf-8
import json
import sys

f = open('/home/test/ansible/192.168.1.12.json','r')

json_dict = json.load(f)

for tasks_key in json_dict["plays"]:
    for i in tasks_key["tasks"][0]['hosts']['192.168.1.12']['ansible_facts'].items():

        # タプルの[1]のタイプを調べます。
        type_check = type(i[1])

        # type 関数での返り値を str に変換します。
        type_check = str(type_check)

        # <class 'dict'> などの返り値を split で分割します。
        type_check = type_check.split("'")

        # split で分割した値の2番目を取得します。
        type_checked = type_check[1]

        if type_checked == 'int':
            print('int型')
        elif type_checked == 'str':
            print('str型')
        elif type_checked == 'list':
            print('list型')
        elif type_checked == 'dict':
            print('dict型')
        elif type_checked == 'bool':
            print('bool型')
        else:
            print('エラー')

[test@cent07 ansible]$

 

 

上記プログラムの実行結果です。

徐々にプログラムが完成に近づいていきます。

条件分岐も問題なさそうです。

[test@cent07 ansible]$ python3.6 setup_parse_01.py
list型
list型
dict型
str型
str型
str型
dict型
dict型
dict型
dict型
dict型
str型
str型
str型
str型
dict型
str型
int型
int型
dict型
dict型
bool型
str型
str型
list型
str型
list型
str型
dict型
dict型
str型
str型
int型
dict型
int型
list型
str型
str型
str型
list型
int型
int型
int型
int型
str型
str型
str型
str型
dict型
str型
int型
int型
dict型
str型
str型
str型
str型
int型
int型
str型
list型
str型
str型
int型
str型
str型
int型
str型
str型
int型
str型
str型
str型
str型
bool型
[test@cent07 ansible]$

 

 

今のところ、最終的なゴールはこんな感じでの出力です。

 

元の JSON 構造

 

物足りないが完成プログラム

プログラムは完成しましたが、今一つ物足りないです(笑)

[test@cent07 ansible]$ cat setup_parse_01.py
#coding:utf-8
import json
import sys

f = open('/home/test/ansible/192.168.1.12.json','r')

json_dict = json.load(f)

for tasks_key in json_dict["plays"]:
    for i in tasks_key["tasks"][0]['hosts']['192.168.1.12']['ansible_facts'].items():
        #print(i)
        # タプルの[1]のタイプを調べます。
        type_check = type(i[1])
        # type 関数での返り値を str に変換します。
        type_check = str(type_check)
        # <class 'dict'> などの返り値を split で分割します。
        type_check = type_check.split("'")
        # split で分割した値の2番目を取得します。
        type_checked = type_check[1]

        if type_checked == 'int':
            #print('int型')
            print(i[0] + ',' + str(i[1]))
        elif type_checked == 'str':
            #print('str型')
            print(i[0] + ',' + str(i[1]))
        elif type_checked == 'list':
            #print('list型')
            print(i[0] + ',')
            for item in i[1]:
                print(',' + str(item))
        elif type_checked == 'dict':
            #print('dict型')
            print(i[0] + ',')
            for key, value in i[1].items():
                print(',' + key + ',' + str(value))
        elif type_checked == 'bool':
            #print('bool型')
            print(i[0] + ',' + str(i[1]))
        else:
            print('エラー')

 

 

実行結果

[test@cent07 ansible]$ python3.6 setup_parse_01.py
ansible_all_ipv4_addresses,
,192.168.1.12
ansible_all_ipv6_addresses,
ansible_apparmor,
,status,disabled
ansible_architecture,x86_64
ansible_bios_date,09/21/2015
ansible_bios_version,6.00
ansible_cmdline,
,BOOT_IMAGE,/vmlinuz-3.10.0-514.el7.x86_64
,LANG,ja_JP.UTF-8
,crashkernel,auto
,quiet,True
,rd.lvm.lv,cl/swap
,rhgb,True
,ro,True
,root,/dev/mapper/cl-root
ansible_date_time,
,date,2017-09-10
,day,10
,epoch,1505042818
,hour,20
,iso8601,2017-09-10T11:26:58Z
,iso8601_basic,20170910T202658078493
,iso8601_basic_short,20170910T202658
,iso8601_micro,2017-09-10T11:26:58.078637Z
,minute,26
,month,09
,second,58
,time,20:26:58
,tz,JST
,tz_offset,+0900
,weekday,日曜日
,weekday_number,0
,weeknumber,36
,year,2017
ansible_default_ipv4,
,address,192.168.1.12
,alias,ens160
,broadcast,192.168.1.255
,gateway,192.168.1.1
,interface,ens160
,macaddress,00:0c:29:6b:9d:b5
,mtu,1500
,netmask,255.255.255.0
,network,192.168.1.0
,type,ether
ansible_default_ipv6,
ansible_devices,
,fd0,{'holders': [], 'host': '', 'model': None, 'partitions': {}, 'removable': '1', 'rotational': '1', 'sas_address': None, 'sas_device_handle': None, 'scheduler_mo de': 'deadline', 'sectors': '8', 'sectorsize': '512', 'size': '4.00 KB', 'support_discard': '0', 'vendor': None}
,sda,{'holders': [], 'host': 'SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)', 'model': 'Virtual disk', 'pa rtitions': {'sda1': {'holders': [], 'sectors': '2097152', 'sectorsize': 512, 'size': '1.00 GB', 'start': '2048', 'uuid': 'aa2722d7-9671-40ae-97de-bcd0e29871e8'}, 's da2': {'holders': ['cl-root', 'cl-swap'], 'sectors': '31455232', 'sectorsize': 512, 'size': '15.00 GB', 'start': '2099200', 'uuid': None}}, 'removable': '0', 'rotat ional': '1', 'sas_address': None, 'sas_device_handle': None, 'scheduler_mode': 'deadline', 'sectors': '33554432', 'sectorsize': '512', 'size': '16.00 GB', 'support_ discard': '0', 'vendor': 'VMware'}
,sr0,{'holders': [], 'host': 'IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)', 'model': 'VMware IDE CDR10', 'partitions': {}, 'removable': '1', ' rotational': '1', 'sas_address': None, 'sas_device_handle': None, 'scheduler_mode': 'cfq', 'sectors': '16173056', 'sectorsize': '2048', 'size': '30.85 GB', 'support _discard': '0', 'vendor': 'NECVMWar'}
ansible_distribution,CentOS
ansible_distribution_major_version,7
ansible_distribution_release,Core
ansible_distribution_version,7.3.1611
ansible_dns,
,nameservers,['8.8.8.8']
ansible_domain,
ansible_effective_group_id,0
ansible_effective_user_id,0
ansible_ens160,
,active,True
,device,ens160
,features,{'busy_poll': 'off [fixed]', 'fcoe_mtu': 'off [fixed]', 'generic_receive_offload': 'on', 'generic_segmentation_offload': 'on', 'highdma': 'on', 'hw_tc_off load': 'off [fixed]', 'l2_fwd_offload': 'off [fixed]', 'large_receive_offload': 'on', 'loopback': 'off [fixed]', 'netns_local': 'off [fixed]', 'ntuple_filters': 'of f [fixed]', 'receive_hashing': 'off [fixed]', 'rx_all': 'off [fixed]', 'rx_checksumming': 'on', 'rx_fcs': 'off [fixed]', 'rx_vlan_filter': 'on [fixed]', 'rx_vlan_of fload': 'on', 'rx_vlan_stag_filter': 'off [fixed]', 'rx_vlan_stag_hw_parse': 'off [fixed]', 'scatter_gather': 'on', 'tcp_segmentation_offload': 'on', 'tx_checksum_f coe_crc': 'off [fixed]', 'tx_checksum_ip_generic': 'on', 'tx_checksum_ipv4': 'off [fixed]', 'tx_checksum_ipv6': 'off [fixed]', 'tx_checksum_sctp': 'off [fixed]', 't x_checksumming': 'on', 'tx_fcoe_segmentation': 'off [fixed]', 'tx_gre_segmentation': 'off [fixed]', 'tx_gso_robust': 'off [fixed]', 'tx_ipip_segmentation': 'off [fi xed]', 'tx_lockless': 'off [fixed]', 'tx_mpls_segmentation': 'off [fixed]', 'tx_nocache_copy': 'off', 'tx_scatter_gather': 'on', 'tx_scatter_gather_fraglist': 'off [fixed]', 'tx_sctp_segmentation': 'off [fixed]', 'tx_sit_segmentation': 'off [fixed]', 'tx_tcp6_segmentation': 'on', 'tx_tcp_ecn_segmentation': 'off [fixed]', 'tx_t cp_segmentation': 'on', 'tx_udp_tnl_segmentation': 'off [fixed]', 'tx_vlan_offload': 'on', 'tx_vlan_stag_hw_insert': 'off [fixed]', 'udp_fragmentation_offload': 'of f [fixed]', 'vlan_challenged': 'off [fixed]'}
,ipv4,{'address': '192.168.1.12', 'broadcast': '192.168.1.255', 'netmask': '255.255.255.0', 'network': '192.168.1.0'}
,macaddress,00:0c:29:6b:9d:b5
,module,vmxnet3
,mtu,1500
,pciid,0000:03:00.0
,promisc,False
,speed,10000
,type,ether
ansible_env,
,HOME,/root
,LANG,ja_JP.UTF-8
,LOGNAME,root
,LS_COLORS,rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:s t=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*. t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=0 1;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.ca b=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;3 5:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.m p4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:* .xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01 ;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:
,MAIL,/var/mail/test
,PATH,/sbin:/bin:/usr/sbin:/usr/bin
,PWD,/home/test
,SHELL,/bin/bash
,SHLVL,1
,SUDO_COMMAND,/bin/sh -c echo BECOME-SUCCESS-srbmpgkiudqfvhtxlxkdglkqrljwgmys; /usr/bin/python /home/test/.ansible/tmp/ansible-tmp-1505042816.4-257607136295527/setu p.py; rm -rf "/home/test/.ansible/tmp/ansible-tmp-1505042816.4-257607136295527/" > /dev/null 2>&1
,SUDO_GID,1000
,SUDO_UID,1000
,SUDO_USER,test
,TERM,xterm
,USER,root
,USERNAME,root
,_,/usr/bin/python
ansible_fips,False
ansible_form_factor,Other
ansible_fqdn,cent07
ansible_gather_subset,
,hardware
,network
,virtual
ansible_hostname,cent07
ansible_interfaces,
,ens160
,lo
ansible_kernel,3.10.0-514.el7.x86_64
ansible_lo,
,active,True
,device,lo
,features,{'busy_poll': 'off [fixed]', 'fcoe_mtu': 'off [fixed]', 'generic_receive_offload': 'on', 'generic_segmentation_offload': 'on', 'highdma': 'on [fixed]', 'h w_tc_offload': 'off [fixed]', 'l2_fwd_offload': 'off [fixed]', 'large_receive_offload': 'off [fixed]', 'loopback': 'on [fixed]', 'netns_local': 'on [fixed]', 'ntupl e_filters': 'off [fixed]', 'receive_hashing': 'off [fixed]', 'rx_all': 'off [fixed]', 'rx_checksumming': 'on [fixed]', 'rx_fcs': 'off [fixed]', 'rx_vlan_filter': 'o ff [fixed]', 'rx_vlan_offload': 'off [fixed]', 'rx_vlan_stag_filter': 'off [fixed]', 'rx_vlan_stag_hw_parse': 'off [fixed]', 'scatter_gather': 'on', 'tcp_segmentati on_offload': 'on', 'tx_checksum_fcoe_crc': 'off [fixed]', 'tx_checksum_ip_generic': 'on [fixed]', 'tx_checksum_ipv4': 'off [fixed]', 'tx_checksum_ipv6': 'off [fixed ]', 'tx_checksum_sctp': 'on [fixed]', 'tx_checksumming': 'on', 'tx_fcoe_segmentation': 'off [fixed]', 'tx_gre_segmentation': 'off [fixed]', 'tx_gso_robust': 'off [f ixed]', 'tx_ipip_segmentation': 'off [fixed]', 'tx_lockless': 'on [fixed]', 'tx_mpls_segmentation': 'off [fixed]', 'tx_nocache_copy': 'off [fixed]', 'tx_scatter_gat her': 'on [fixed]', 'tx_scatter_gather_fraglist': 'on [fixed]', 'tx_sctp_segmentation': 'on', 'tx_sit_segmentation': 'off [fixed]', 'tx_tcp6_segmentation': 'on', 't x_tcp_ecn_segmentation': 'on', 'tx_tcp_segmentation': 'on', 'tx_udp_tnl_segmentation': 'off [fixed]', 'tx_vlan_offload': 'off [fixed]', 'tx_vlan_stag_hw_insert': 'o ff [fixed]', 'udp_fragmentation_offload': 'on', 'vlan_challenged': 'on [fixed]'}
,ipv4,{'address': '127.0.0.1', 'broadcast': 'host', 'netmask': '255.0.0.0', 'network': '127.0.0.0'}
,mtu,65536
,promisc,False
,type,loopback
ansible_lvm,
,lvs,{'root': {'size_g': '13.39', 'vg': 'cl'}, 'swap': {'size_g': '1.60', 'vg': 'cl'}}
,vgs,{'cl': {'free_g': '0', 'num_lvs': '2', 'num_pvs': '1', 'size_g': '15.00'}}
ansible_machine,x86_64
ansible_machine_id,078151465fc1419ca8a5d3f1dd8e4358
ansible_memfree_mb,577
ansible_memory_mb,
,nocache,{'free': 716, 'used': 276}
,real,{'free': 577, 'total': 992, 'used': 415}
,swap,{'cached': 0, 'free': 1639, 'total': 1639, 'used': 0}
ansible_memtotal_mb,992
ansible_mounts,
,{'device': '/dev/mapper/cl-root', 'fstype': 'xfs', 'mount': '/', 'options': 'rw,seclabel,relatime,attr2,inode64,noquota', 'size_available': 12797620224, 'size_tota l': 14371782656, 'uuid': '37c2f8c1-0eba-4d09-93dd-77a07c2fa2df'}
,{'device': '/dev/sda1', 'fstype': 'xfs', 'mount': '/boot', 'options': 'rw,seclabel,relatime,attr2,inode64,noquota', 'size_available': 916279296, 'size_total': 1063 256064, 'uuid': 'aa2722d7-9671-40ae-97de-bcd0e29871e8'}
ansible_nodename,cent07
ansible_os_family,RedHat
ansible_pkg_mgr,yum
ansible_processor,
,GenuineIntel
,Intel(R) Core(TM) i5 CPU M 480 @ 2.67GHz
ansible_processor_cores,1
ansible_processor_count,1
ansible_processor_threads_per_core,1
ansible_processor_vcpus,1
ansible_product_name,VMware Virtual Platform
ansible_product_serial,VMware-56 4d 19 f1 e4 30 5c f8-a5 ec 80 24 85 6b 9d b5
ansible_product_uuid,564D19F1-E430-5CF8-A5EC-8024856B9DB5
ansible_product_version,None
ansible_python,
,executable,/usr/bin/python
,has_sslcontext,True
,type,CPython
,version,{'major': 2, 'micro': 5, 'minor': 7, 'releaselevel': 'final', 'serial': 0}
,version_info,[2, 7, 5, 'final', 0]
ansible_python_version,2.7.5
ansible_real_group_id,0
ansible_real_user_id,0
ansible_selinux,
,config_mode,enforcing
,mode,enforcing
,policyvers,28
,status,enabled
,type,targeted
ansible_service_mgr,systemd
ansible_ssh_host_key_ecdsa_public,AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBI6RisZF04a4x2sKl95kuush7I8b56a2Vq/OajyVzh2xlxqOiYsrkM8ZZFJHklLNjYFViXok+ZwnLS WOshnsmH8=
ansible_ssh_host_key_ed25519_public,AAAAC3NzaC1lZDI1NTE5AAAAIKbL2EK6Iefg+5MTdICviJwtiXK68F07tqD1aEt4j0JN
ansible_ssh_host_key_rsa_public,AAAAB3NzaC1yc2EAAAADAQABAAABAQDUaIVVUEd+7NCewS573ze/CczMPMV1l0O18ZJ0kao11Gkmdz+81Vgb5ap+Et38CMWxJohxFtVldsZtDnryzu9pddNWgxecai4+snxX piwTqM/Z2hsm4QKpUXdewvbj3w5F7IHboTIph18HEor0fSHZCzW22ADpKcq6CLIzTez9F7v+FNt0MRJjW9k84BGYp8I+PjCIYRLP53zgz4BZCeiiR7ewR5yV9jRFLm95viS+3IbG8Pm10ZaYZ0xjDR5IxxMhEPh5bjbd J73CDlAkzW3MIpuFXvteMs/GVWvQ6lwem1fJ0Bs3FKNEJ8TZXARjb2JhI+zOpjHILZUF9Wjl7eJd
ansible_swapfree_mb,1639
ansible_swaptotal_mb,1639
ansible_system,Linux
ansible_system_capabilities,
,cap_chown
,cap_dac_override
,cap_dac_read_search
,cap_fowner
,cap_fsetid
,cap_kill
,cap_setgid
,cap_setuid
,cap_setpcap
,cap_linux_immutable
,cap_net_bind_service
,cap_net_broadcast
,cap_net_admin
,cap_net_raw
,cap_ipc_lock
,cap_ipc_owner
,cap_sys_module
,cap_sys_rawio
,cap_sys_chroot
,cap_sys_ptrace
,cap_sys_pacct
,cap_sys_admin
,cap_sys_boot
,cap_sys_nice
,cap_sys_resource
,cap_sys_time
,cap_sys_tty_config
,cap_mknod
,cap_lease
,cap_audit_write
,cap_audit_control
,cap_setfcap
,cap_mac_override
,cap_mac_admin
,cap_syslog
,35
,36+ep
ansible_system_capabilities_enforced,True
ansible_system_vendor,VMware, Inc.
ansible_uptime_seconds,22200
ansible_user_dir,/root
ansible_user_gecos,root
ansible_user_gid,0
ansible_user_id,root
ansible_user_shell,/bin/bash
ansible_user_uid,0
ansible_userspace_architecture,x86_64
ansible_userspace_bits,64
ansible_virtualization_role,guest
ansible_virtualization_type,VMware
module_setup,True
[test@cent07 ansible]$
[test@cent07 ansible]$ python3.6 setup_parse_01.py
ansible_all_ipv4_addresses,
,192.168.1.12
ansible_all_ipv6_addresses,
ansible_apparmor,
,status,disabled
ansible_architecture,x86_64
ansible_bios_date,09/21/2015
ansible_bios_version,6.00
ansible_cmdline,
,BOOT_IMAGE,/vmlinuz-3.10.0-514.el7.x86_64
,LANG,ja_JP.UTF-8
,crashkernel,auto
,quiet,True
,rd.lvm.lv,cl/swap
,rhgb,True
,ro,True
,root,/dev/mapper/cl-root
ansible_date_time,
,date,2017-09-10
,day,10
,epoch,1505042818
,hour,20
,iso8601,2017-09-10T11:26:58Z
,iso8601_basic,20170910T202658078493
,iso8601_basic_short,20170910T202658
,iso8601_micro,2017-09-10T11:26:58.078637Z
,minute,26
,month,09
,second,58
,time,20:26:58
,tz,JST
,tz_offset,+0900
,weekday,日曜日
,weekday_number,0
,weeknumber,36
,year,2017
ansible_default_ipv4,
,address,192.168.1.12
,alias,ens160
,broadcast,192.168.1.255
,gateway,192.168.1.1
,interface,ens160
,macaddress,00:0c:29:6b:9d:b5
,mtu,1500
,netmask,255.255.255.0
,network,192.168.1.0
,type,ether
ansible_default_ipv6,
ansible_devices,
,fd0,{'holders': [], 'host': '', 'model': None, 'partitions': {}, 'removable': '1', 'rotational': '1', 'sas_address': None, 'sas_device_handle': None, 'scheduler_mode': 'deadline', 'sectors': '8', 'sectorsize': '512', 'size': '4.00 KB', 'support_discard': '0', 'vendor': None}
,sda,{'holders': [], 'host': 'SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)', 'model': 'Virtual disk', 'partitions': {'sda1': {'holders': [], 'sectors': '2097152', 'sectorsize': 512, 'size': '1.00 GB', 'start': '2048', 'uuid': 'aa2722d7-9671-40ae-97de-bcd0e29871e8'}, 'sda2': {'holders': ['cl-root', 'cl-swap'], 'sectors': '31455232', 'sectorsize': 512, 'size': '15.00 GB', 'start': '2099200', 'uuid': None}}, 'removable': '0', 'rotational': '1', 'sas_address': None, 'sas_device_handle': None, 'scheduler_mode': 'deadline', 'sectors': '33554432', 'sectorsize': '512', 'size': '16.00 GB', 'support_discard': '0', 'vendor': 'VMware'}
,sr0,{'holders': [], 'host': 'IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)', 'model': 'VMware IDE CDR10', 'partitions': {}, 'removable': '1', 'rotational': '1', 'sas_address': None, 'sas_device_handle': None, 'scheduler_mode': 'cfq', 'sectors': '16173056', 'sectorsize': '2048', 'size': '30.85 GB', 'support_discard': '0', 'vendor': 'NECVMWar'}
ansible_distribution,CentOS
ansible_distribution_major_version,7
ansible_distribution_release,Core
ansible_distribution_version,7.3.1611
ansible_dns,
,nameservers,['8.8.8.8']
ansible_domain,
ansible_effective_group_id,0
ansible_effective_user_id,0
ansible_ens160,
,active,True
,device,ens160
,features,{'busy_poll': 'off [fixed]', 'fcoe_mtu': 'off [fixed]', 'generic_receive_offload': 'on', 'generic_segmentation_offload': 'on', 'highdma': 'on', 'hw_tc_offload': 'off [fixed]', 'l2_fwd_offload': 'off [fixed]', 'large_receive_offload': 'on', 'loopback': 'off [fixed]', 'netns_local': 'off [fixed]', 'ntuple_filters': 'off [fixed]', 'receive_hashing': 'off [fixed]', 'rx_all': 'off [fixed]', 'rx_checksumming': 'on', 'rx_fcs': 'off [fixed]', 'rx_vlan_filter': 'on [fixed]', 'rx_vlan_offload': 'on', 'rx_vlan_stag_filter': 'off [fixed]', 'rx_vlan_stag_hw_parse': 'off [fixed]', 'scatter_gather': 'on', 'tcp_segmentation_offload': 'on', 'tx_checksum_fcoe_crc': 'off [fixed]', 'tx_checksum_ip_generic': 'on', 'tx_checksum_ipv4': 'off [fixed]', 'tx_checksum_ipv6': 'off [fixed]', 'tx_checksum_sctp': 'off [fixed]', 'tx_checksumming': 'on', 'tx_fcoe_segmentation': 'off [fixed]', 'tx_gre_segmentation': 'off [fixed]', 'tx_gso_robust': 'off [fixed]', 'tx_ipip_segmentation': 'off [fixed]', 'tx_lockless': 'off [fixed]', 'tx_mpls_segmentation': 'off [fixed]', 'tx_nocache_copy': 'off', 'tx_scatter_gather': 'on', 'tx_scatter_gather_fraglist': 'off [fixed]', 'tx_sctp_segmentation': 'off [fixed]', 'tx_sit_segmentation': 'off [fixed]', 'tx_tcp6_segmentation': 'on', 'tx_tcp_ecn_segmentation': 'off [fixed]', 'tx_tcp_segmentation': 'on', 'tx_udp_tnl_segmentation': 'off [fixed]', 'tx_vlan_offload': 'on', 'tx_vlan_stag_hw_insert': 'off [fixed]', 'udp_fragmentation_offload': 'off [fixed]', 'vlan_challenged': 'off [fixed]'}
,ipv4,{'address': '192.168.1.12', 'broadcast': '192.168.1.255', 'netmask': '255.255.255.0', 'network': '192.168.1.0'}
,macaddress,00:0c:29:6b:9d:b5
,module,vmxnet3
,mtu,1500
,pciid,0000:03:00.0
,promisc,False
,speed,10000
,type,ether
ansible_env,
,HOME,/root
,LANG,ja_JP.UTF-8
,LOGNAME,root
,LS_COLORS,rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:
,MAIL,/var/mail/test
,PATH,/sbin:/bin:/usr/sbin:/usr/bin
,PWD,/home/test
,SHELL,/bin/bash
,SHLVL,1
,SUDO_COMMAND,/bin/sh -c echo BECOME-SUCCESS-srbmpgkiudqfvhtxlxkdglkqrljwgmys; /usr/bin/python /home/test/.ansible/tmp/ansible-tmp-1505042816.4-257607136295527/setup.py; rm -rf "/home/test/.ansible/tmp/ansible-tmp-1505042816.4-257607136295527/" > /dev/null 2>&1
,SUDO_GID,1000
,SUDO_UID,1000
,SUDO_USER,test
,TERM,xterm
,USER,root
,USERNAME,root
,_,/usr/bin/python
ansible_fips,False
ansible_form_factor,Other
ansible_fqdn,cent07
ansible_gather_subset,
,hardware
,network
,virtual
ansible_hostname,cent07
ansible_interfaces,
,ens160
,lo
ansible_kernel,3.10.0-514.el7.x86_64
ansible_lo,
,active,True
,device,lo
,features,{'busy_poll': 'off [fixed]', 'fcoe_mtu': 'off [fixed]', 'generic_receive_offload': 'on', 'generic_segmentation_offload': 'on', 'highdma': 'on [fixed]', 'hw_tc_offload': 'off [fixed]', 'l2_fwd_offload': 'off [fixed]', 'large_receive_offload': 'off [fixed]', 'loopback': 'on [fixed]', 'netns_local': 'on [fixed]', 'ntuple_filters': 'off [fixed]', 'receive_hashing': 'off [fixed]', 'rx_all': 'off [fixed]', 'rx_checksumming': 'on [fixed]', 'rx_fcs': 'off [fixed]', 'rx_vlan_filter': 'off [fixed]', 'rx_vlan_offload': 'off [fixed]', 'rx_vlan_stag_filter': 'off [fixed]', 'rx_vlan_stag_hw_parse': 'off [fixed]', 'scatter_gather': 'on', 'tcp_segmentation_offload': 'on', 'tx_checksum_fcoe_crc': 'off [fixed]', 'tx_checksum_ip_generic': 'on [fixed]', 'tx_checksum_ipv4': 'off [fixed]', 'tx_checksum_ipv6': 'off [fixed]', 'tx_checksum_sctp': 'on [fixed]', 'tx_checksumming': 'on', 'tx_fcoe_segmentation': 'off [fixed]', 'tx_gre_segmentation': 'off [fixed]', 'tx_gso_robust': 'off [fixed]', 'tx_ipip_segmentation': 'off [fixed]', 'tx_lockless': 'on [fixed]', 'tx_mpls_segmentation': 'off [fixed]', 'tx_nocache_copy': 'off [fixed]', 'tx_scatter_gather': 'on [fixed]', 'tx_scatter_gather_fraglist': 'on [fixed]', 'tx_sctp_segmentation': 'on', 'tx_sit_segmentation': 'off [fixed]', 'tx_tcp6_segmentation': 'on', 'tx_tcp_ecn_segmentation': 'on', 'tx_tcp_segmentation': 'on', 'tx_udp_tnl_segmentation': 'off [fixed]', 'tx_vlan_offload': 'off [fixed]', 'tx_vlan_stag_hw_insert': 'off [fixed]', 'udp_fragmentation_offload': 'on', 'vlan_challenged': 'on [fixed]'}
,ipv4,{'address': '127.0.0.1', 'broadcast': 'host', 'netmask': '255.0.0.0', 'network': '127.0.0.0'}
,mtu,65536
,promisc,False
,type,loopback
ansible_lvm,
,lvs,{'root': {'size_g': '13.39', 'vg': 'cl'}, 'swap': {'size_g': '1.60', 'vg': 'cl'}}
,vgs,{'cl': {'free_g': '0', 'num_lvs': '2', 'num_pvs': '1', 'size_g': '15.00'}}
ansible_machine,x86_64
ansible_machine_id,078151465fc1419ca8a5d3f1dd8e4358
ansible_memfree_mb,577
ansible_memory_mb,
,nocache,{'free': 716, 'used': 276}
,real,{'free': 577, 'total': 992, 'used': 415}
,swap,{'cached': 0, 'free': 1639, 'total': 1639, 'used': 0}
ansible_memtotal_mb,992
ansible_mounts,
,{'device': '/dev/mapper/cl-root', 'fstype': 'xfs', 'mount': '/', 'options': 'rw,seclabel,relatime,attr2,inode64,noquota', 'size_available': 12797620224, 'size_total': 14371782656, 'uuid': '37c2f8c1-0eba-4d09-93dd-77a07c2fa2df'}
,{'device': '/dev/sda1', 'fstype': 'xfs', 'mount': '/boot', 'options': 'rw,seclabel,relatime,attr2,inode64,noquota', 'size_available': 916279296, 'size_total': 1063256064, 'uuid': 'aa2722d7-9671-40ae-97de-bcd0e29871e8'}
ansible_nodename,cent07
ansible_os_family,RedHat
ansible_pkg_mgr,yum
ansible_processor,
,GenuineIntel
,Intel(R) Core(TM) i5 CPU M 480 @ 2.67GHz
ansible_processor_cores,1
ansible_processor_count,1
ansible_processor_threads_per_core,1
ansible_processor_vcpus,1
ansible_product_name,VMware Virtual Platform
ansible_product_serial,VMware-56 4d 19 f1 e4 30 5c f8-a5 ec 80 24 85 6b 9d b5
ansible_product_uuid,564D19F1-E430-5CF8-A5EC-8024856B9DB5
ansible_product_version,None
ansible_python,
,executable,/usr/bin/python
,has_sslcontext,True
,type,CPython
,version,{'major': 2, 'micro': 5, 'minor': 7, 'releaselevel': 'final', 'serial': 0}
,version_info,[2, 7, 5, 'final', 0]
ansible_python_version,2.7.5
ansible_real_group_id,0
ansible_real_user_id,0
ansible_selinux,
,config_mode,enforcing
,mode,enforcing
,policyvers,28
,status,enabled
,type,targeted
ansible_service_mgr,systemd
ansible_ssh_host_key_ecdsa_public,AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBI6RisZF04a4x2sKl95kuush7I8b56a2Vq/OajyVzh2xlxqOiYsrkM8ZZFJHklLNjYFViXok+ZwnLSWOshnsmH8=
ansible_ssh_host_key_ed25519_public,AAAAC3NzaC1lZDI1NTE5AAAAIKbL2EK6Iefg+5MTdICviJwtiXK68F07tqD1aEt4j0JN
ansible_ssh_host_key_rsa_public,AAAAB3NzaC1yc2EAAAADAQABAAABAQDUaIVVUEd+7NCewS573ze/CczMPMV1l0O18ZJ0kao11Gkmdz+81Vgb5ap+Et38CMWxJohxFtVldsZtDnryzu9pddNWgxecai4+snxXpiwTqM/Z2hsm4QKpUXdewvbj3w5F7IHboTIph18HEor0fSHZCzW22ADpKcq6CLIzTez9F7v+FNt0MRJjW9k84BGYp8I+PjCIYRLP53zgz4BZCeiiR7ewR5yV9jRFLm95viS+3IbG8Pm10ZaYZ0xjDR5IxxMhEPh5bjbdJ73CDlAkzW3MIpuFXvteMs/GVWvQ6lwem1fJ0Bs3FKNEJ8TZXARjb2JhI+zOpjHILZUF9Wjl7eJd
ansible_swapfree_mb,1639
ansible_swaptotal_mb,1639
ansible_system,Linux
ansible_system_capabilities,
,cap_chown
,cap_dac_override
,cap_dac_read_search
,cap_fowner
,cap_fsetid
,cap_kill
,cap_setgid
,cap_setuid
,cap_setpcap
,cap_linux_immutable
,cap_net_bind_service
,cap_net_broadcast
,cap_net_admin
,cap_net_raw
,cap_ipc_lock
,cap_ipc_owner
,cap_sys_module
,cap_sys_rawio
,cap_sys_chroot
,cap_sys_ptrace
,cap_sys_pacct
,cap_sys_admin
,cap_sys_boot
,cap_sys_nice
,cap_sys_resource
,cap_sys_time
,cap_sys_tty_config
,cap_mknod
,cap_lease
,cap_audit_write
,cap_audit_control
,cap_setfcap
,cap_mac_override
,cap_mac_admin
,cap_syslog
,35
,36+ep
ansible_system_capabilities_enforced,True
ansible_system_vendor,VMware, Inc.
ansible_uptime_seconds,22200
ansible_user_dir,/root
ansible_user_gecos,root
ansible_user_gid,0
ansible_user_id,root
ansible_user_shell,/bin/bash
ansible_user_uid,0
ansible_userspace_architecture,x86_64
ansible_userspace_bits,64
ansible_virtualization_role,guest
ansible_virtualization_type,VMware
module_setup,True
[test@cent07 ansible]$

 

上記実行結果をエディタは貼り付け、「test.csv」で保存し、Excel で開きます。

開くとこんな感じになります。

 

 

まとめ

Python でツールを作ってみましたが、様々な可能性を感じました。

インフラ系エンジニアなので普段はプログラミングはしていませんが、プログラミングは好きなのでこれからもアイデアを出してプログラムで実現を続けていきます。

 

 

Posted by 100%レンタルサーバーを使いこなすサイト管理人

コメントを残す

メールアドレスが公開されることはありません。