Ansible之采集系统信息&自定义模块

setup 模块采集系统信息

Ansible之常用模块中我们简单的介绍了这个模块,但这个模块的使用跟其他模块不太一样,主要是与自定义模块配合使用的,所以放在这里来讲。

facts 组件

在讲 setup 模块之前我们先来讲讲 facts 组件:这个组件是用来收集被管理节点信息的,使用 setup 模块可以获取这些信息,facts 收集的数据是 json 格式的,其内任意一项都可以当作变量被直接应用(如在 playbook、Jinja2 模板中)。

ansible_manager ~ > ansible webservers -m setup
192.168.159.131 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.159.131"
        ], 
        "ansible_all_ipv6_addresses": [
            "fe80::e68f:2f9d:64c4:eaf"
        ], 
        "ansible_apparmor": {
            "status": "disabled"
        }, 
        "ansible_architecture": "x86_64", 
        "ansible_bios_date": "07/29/2019", 
        "ansible_bios_version": "6.00", 
        "ansible_cmdline": {
            "BOOT_IMAGE": "/vmlinuz-3.10.0-1062.12.1.el7.x86_64", 
            "LANG": "zh_CN.UTF-8", 
            "quiet": true, 
            "rhgb": true, 
            "ro": true, 
            "root": "UUID=9102522f-d3d9-40a4-b8ab-ea22947588db"
        }, 
        "ansible_date_time": {
            "date": "2020-03-26", 
            "day": "26", 
            "epoch": "1585221115", 
            "hour": "19", 
            "iso8601": "2020-03-26T11:11:55Z", 
            "iso8601_basic": "20200326T191155513355", 
            "iso8601_basic_short": "20200326T191155", 
            "iso8601_micro": "2020-03-26T11:11:55.513445Z", 
            "minute": "11", 
            "month": "03", 
            "second": "55", 
            "time": "19:11:55", 
            "tz": "CST", 
            "tz_offset": "+0800", 
            "weekday": "星期四", 
            "weekday_number": "4", 
            "weeknumber": "12", 
            "year": "2020"
        }, 
        "ansible_default_ipv4": {
            "address": "192.168.159.131", 
            "alias": "ens33", 
            "broadcast": "192.168.159.255", 
            "gateway": "192.168.159.2", 
            "interface": "ens33", 
            "macaddress": "00:0c:29:1e:c8:6c", 
            "mtu": 1500, 
            "netmask": "255.255.255.0", 
            "network": "192.168.159.0", 
            "type": "ether"
        }, 
        "ansible_default_ipv6": {}, 
        "ansible_device_links": {
            "ids": {
                "sr0": [
                    "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
                ]
            }, 
            "labels": {
                "sr0": [
                    "CentOS\\x207\\x20x86_64"
                ]
            }, 
            "masters": {}, 
            "uuids": {
                "sda1": [
                    "35ae303e-6bb5-4109-a5bc-9369f9f0a55d"
                ], 
                "sda2": [
                    "9102522f-d3d9-40a4-b8ab-ea22947588db"
                ], 
                "sda3": [
                    "f65b116d-2e5c-467c-8189-4d80543e8ae4"
                ], 
                "sr0": [
                    "2017-09-05-14-14-50-00"
                ]
            }
        }, 
        "ansible_devices": {
            "sda": {
                "holders": [], 
                "host": "", 
                "links": {
                    "ids": [], 
                    "labels": [], 
                    "masters": [], 
                    "uuids": []
                }, 
                "model": "VMware Virtual S", 
                "partitions": {
                    "sda1": {
                        "holders": [], 
                        "links": {
                            "ids": [], 
                            "labels": [], 
                            "masters": [], 
                            "uuids": [
                                "35ae303e-6bb5-4109-a5bc-9369f9f0a55d"
                            ]
                        }, 
                        "sectors": "409600", 
                        "sectorsize": 512, 
                        "size": "200.00 MB", 
                        "start": "2048", 
                        "uuid": "35ae303e-6bb5-4109-a5bc-9369f9f0a55d"
                    }, 
                    "sda2": {
                        "holders": [], 
                        "links": {
                            "ids": [], 
                            "labels": [], 
                            "masters": [], 
                            "uuids": [
                                "9102522f-d3d9-40a4-b8ab-ea22947588db"
                            ]
                        }, 
                        "sectors": "22648832", 
                        "sectorsize": 512, 
                        "size": "10.80 GB", 
                        "start": "411648", 
                        "uuid": "9102522f-d3d9-40a4-b8ab-ea22947588db"
                    }, 
                    "sda3": {
                        "holders": [], 
                        "links": {
                            "ids": [], 
                            "labels": [], 
                            "masters": [], 
                            "uuids": [
                                "f65b116d-2e5c-467c-8189-4d80543e8ae4"
                            ]
                        }, 
                        "sectors": "4194304", 
                        "sectorsize": 512, 
                        "size": "2.00 GB", 
                        "start": "23060480", 
                        "uuid": "f65b116d-2e5c-467c-8189-4d80543e8ae4"
                    }
                }, 
                "removable": "0", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "deadline", 
                "sectors": "41943040", 
                "sectorsize": "512", 
                "size": "20.00 GB", 
                "support_discard": "0", 
                "vendor": "VMware,", 
                "virtual": 1
            }, 
            "sr0": {
                "holders": [], 
                "host": "", 
                "links": {
                    "ids": [
                        "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
                    ], 
                    "labels": [
                        "CentOS\\x207\\x20x86_64"
                    ], 
                    "masters": [], 
                    "uuids": [
                        "2017-09-05-14-14-50-00"
                    ]
                }, 
                "model": "VMware IDE CDR10", 
                "partitions": {}, 
                "removable": "1", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "deadline", 
                "sectors": "1622016", 
                "sectorsize": "2048", 
                "size": "792.00 MB", 
                "support_discard": "0", 
                "vendor": "NECVMWar", 
                "virtual": 1
            }
        }, 
        "ansible_distribution": "CentOS", 
        "ansible_distribution_file_parsed": true, 
        "ansible_distribution_file_path": "/etc/redhat-release", 
        "ansible_distribution_file_variety": "RedHat", 
        "ansible_distribution_major_version": "7", 
        "ansible_distribution_release": "Core", 
        "ansible_distribution_version": "7.7", 
        "ansible_dns": {
            "nameservers": [
                "114.114.114.114", 
                "223.5.5.5"
            ]
        }, 
        "ansible_domain": "", 
        "ansible_effective_group_id": 0, 
        "ansible_effective_user_id": 0, 
        "ansible_ens33": {
            "active": true, 
            "device": "ens33", 
            "features": {
                "busy_poll": "off [fixed]", 
                "fcoe_mtu": "off [fixed]", 
                "generic_receive_offload": "on", 
                "generic_segmentation_offload": "on", 
                "highdma": "off [fixed]", 
                "hw_tc_offload": "off [fixed]", 
                "l2_fwd_offload": "off [fixed]", 
                "large_receive_offload": "off [fixed]", 
                "loopback": "off [fixed]", 
                "netns_local": "off [fixed]", 
                "ntuple_filters": "off [fixed]", 
                "receive_hashing": "off [fixed]", 
                "rx_all": "off", 
                "rx_checksumming": "off", 
                "rx_fcs": "off", 
                "rx_gro_hw": "off [fixed]", 
                "rx_udp_tunnel_port_offload": "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_csum_segmentation": "off [fixed]", 
                "tx_gre_segmentation": "off [fixed]", 
                "tx_gso_partial": "off [fixed]", 
                "tx_gso_robust": "off [fixed]", 
                "tx_ipip_segmentation": "off [fixed]", 
                "tx_lockless": "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": "off [fixed]", 
                "tx_tcp_ecn_segmentation": "off [fixed]", 
                "tx_tcp_mangleid_segmentation": "off", 
                "tx_tcp_segmentation": "on", 
                "tx_udp_tnl_csum_segmentation": "off [fixed]", 
                "tx_udp_tnl_segmentation": "off [fixed]", 
                "tx_vlan_offload": "on [fixed]", 
                "tx_vlan_stag_hw_insert": "off [fixed]", 
                "udp_fragmentation_offload": "off [fixed]", 
                "vlan_challenged": "off [fixed]"
            }, 
            "hw_timestamp_filters": [], 
            "ipv4": {
                "address": "192.168.159.131", 
                "broadcast": "192.168.159.255", 
                "netmask": "255.255.255.0", 
                "network": "192.168.159.0"
            }, 
            "ipv6": [
                {
                    "address": "fe80::e68f:2f9d:64c4:eaf", 
                    "prefix": "64", 
                    "scope": "link"
                }
            ], 
            "macaddress": "00:0c:29:1e:c8:6c", 
            "module": "e1000", 
            "mtu": 1500, 
            "pciid": "0000:02:01.0", 
            "promisc": false, 
            "speed": 1000, 
            "timestamping": [
                "tx_software", 
                "rx_software", 
                "software"
            ], 
            "type": "ether"
        }, 
        "ansible_env": {
            "HOME": "/root", 
            "LANG": "zh_CN.UTF-8", 
            "LESSOPEN": "||/usr/bin/lesspipe.sh %s", 
            "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/root", 
            "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin", 
            "PWD": "/root", 
            "SELINUX_LEVEL_REQUESTED": "", 
            "SELINUX_ROLE_REQUESTED": "", 
            "SELINUX_USE_CURRENT_RANGE": "", 
            "SHELL": "/bin/bash", 
            "SHLVL": "2", 
            "SSH_CLIENT": "192.168.159.129 49748 22", 
            "SSH_CONNECTION": "192.168.159.129 49748 192.168.159.131 22", 
            "SSH_TTY": "/dev/pts/2", 
            "TERM": "xterm", 
            "USER": "root", 
            "XDG_RUNTIME_DIR": "/run/user/0", 
            "XDG_SESSION_ID": "15", 
            "_": "/usr/bin/python"
        }, 
        "ansible_fibre_channel_wwn": [], 
        "ansible_fips": false, 
        "ansible_form_factor": "Other", 
        "ansible_fqdn": "ansible_node1", 
        "ansible_hostname": "ansible_node1", 
        "ansible_hostnqn": "", 
        "ansible_interfaces": [
            "lo", 
            "ens33"
        ], 
        "ansible_is_chroot": false, 
        "ansible_iscsi_iqn": "", 
        "ansible_kernel": "3.10.0-1062.12.1.el7.x86_64", 
        "ansible_kernel_version": "#1 SMP Tue Feb 4 23:02:59 UTC 2020", 
        "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_gro_hw": "off [fixed]", 
                "rx_udp_tunnel_port_offload": "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_csum_segmentation": "off [fixed]", 
                "tx_gre_segmentation": "off [fixed]", 
                "tx_gso_partial": "off [fixed]", 
                "tx_gso_robust": "off [fixed]", 
                "tx_ipip_segmentation": "off [fixed]", 
                "tx_lockless": "on [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_mangleid_segmentation": "on", 
                "tx_tcp_segmentation": "on", 
                "tx_udp_tnl_csum_segmentation": "off [fixed]", 
                "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]"
            }, 
            "hw_timestamp_filters": [], 
            "ipv4": {
                "address": "127.0.0.1", 
                "broadcast": "host", 
                "netmask": "255.0.0.0", 
                "network": "127.0.0.0"
            }, 
            "ipv6": [
                {
                    "address": "::1", 
                    "prefix": "128", 
                    "scope": "host"
                }
            ], 
            "mtu": 65536, 
            "promisc": false, 
            "timestamping": [
                "rx_software", 
                "software"
            ], 
            "type": "loopback"
        }, 
        "ansible_local": {
            "cpuinfo": {
                "cpu": {
                    "cpuname": "i7 8700tes", 
                    "cpunum": "4"
                }
            }, 
            "get_process": {
                "pnum": "1024"
            }
        }, 
        "ansible_lsb": {}, 
        "ansible_machine": "x86_64", 
        "ansible_machine_id": "5b98a695d07649d2811ed35f1f86e0c8", 
        "ansible_memfree_mb": 280, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 749, 
                "used": 223
            }, 
            "real": {
                "free": 280, 
                "total": 972, 
                "used": 692
            }, 
            "swap": {
                "cached": 0, 
                "free": 2047, 
                "total": 2047, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 972, 
        "ansible_mounts": [
            {
                "block_available": 33096, 
                "block_size": 1024, 
                "block_total": 194235, 
                "block_used": 161139, 
                "device": "/dev/sda1", 
                "fstype": "ext4", 
                "inode_available": 50852, 
                "inode_total": 51200, 
                "inode_used": 348, 
                "mount": "/boot", 
                "options": "rw,seclabel,relatime,data=ordered", 
                "size_available": 33890304, 
                "size_total": 198896640, 
                "uuid": "35ae303e-6bb5-4109-a5bc-9369f9f0a55d"
            }, 
            {
                "block_available": 2135489, 
                "block_size": 4096, 
                "block_total": 2753849, 
                "block_used": 618360, 
                "device": "/dev/sda2", 
                "fstype": "ext4", 
                "inode_available": 651125, 
                "inode_total": 708528, 
                "inode_used": 57403, 
                "mount": "/", 
                "options": "rw,seclabel,relatime,data=ordered", 
                "size_available": 8746962944, 
                "size_total": 11279765504, 
                "uuid": "9102522f-d3d9-40a4-b8ab-ea22947588db"
            }
        ], 
        "ansible_nodename": "ansible_node1", 
        "ansible_os_family": "RedHat", 
        "ansible_pkg_mgr": "yum", 
        "ansible_proc_cmdline": {
            "BOOT_IMAGE": "/vmlinuz-3.10.0-1062.12.1.el7.x86_64", 
            "LANG": "zh_CN.UTF-8", 
            "quiet": true, 
            "rhgb": true, 
            "ro": true, 
            "root": "UUID=9102522f-d3d9-40a4-b8ab-ea22947588db"
        }, 
        "ansible_processor": [
            "0", 
            "GenuineIntel", 
            "Genuine Intel(R) CPU 0000 @ 1.60GHz"
        ], 
        "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 c1 80 5a 86 49 29-63 06 97 f1 59 1e c8 6c", 
        "ansible_product_uuid": "80C14D56-865A-2949-6306-97F1591EC86C", 
        "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": 31, 
            "status": "enabled", 
            "type": "targeted"
        }, 
        "ansible_selinux_python_present": true, 
        "ansible_service_mgr": "systemd", 
        "ansible_ssh_host_key_ecdsa_public": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBIbjWycBuNQrntFBAh0VxF1C/yaT09tkTzAtG5SmA5ZVwrcU31jPfSSiPyt34ibMfODOmgfYVcOZQjymCKG9Prg=", 
        "ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIMDyVF/SfqZ3HnaDjY5vQ8mXjAJ/IN41rp+ifAwm0ROF", 
        "ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQC+S1kqCyMtx3qF1X//1JNZcB+1yHMo1uueH1+hEaj/vtNpe5FUFLDTYzgOZwmPHEMq9dk5Sc9DEOcgNnrsEJusHgJAN1Yn52bmzemnlmZf8nf/jbISY1G+HhH3z1nYO68UW0xbcKxP7odZ/SyCHGl9P6DNNhTSaM+guA+QvT3FAvGDd5uaoYsrGCRqO8JM753WmOtskGiJ0SHP2WBc6xH3qx9svA8xMsI0qRi7Us5MRqwRH/PEb1yNoWBHHZuve+KmSLY3uEPqR2S8uHa3NN6YP3F4TBFhRdHQhdxhnRyp0a3BxAQyWguO05is6Yt/iuonB21SNxM4b+yeMnxXqfUd", 
        "ansible_swapfree_mb": 2047, 
        "ansible_swaptotal_mb": 2047, 
        "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": 17767, 
        "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", 
        "discovered_interpreter_python": "/usr/bin/python", 
        "gather_subset": [
            "all"
        ], 
        "module_setup": true
    }, 
    "changed": false
}

可以看到使用 setup 这个模块返回了一个很长很长的 json 串,而这个 json 串的内容就是以 ansible_facts 为键的一个键值对,值的部分就是远程主机中的各种信息,我们可以通过 setup 模块的参数 filter 过滤出更细的内容:

ansible_manager ~ > ansible webservers -m setup -a "filter=ansible_ens33"
192.168.159.131 | SUCCESS => {
    "ansible_facts": {
        "ansible_ens33": {
            "active": true, 
            "device": "ens33", 
            "features": {
                "busy_poll": "off [fixed]", 
                "fcoe_mtu": "off [fixed]", 
                "generic_receive_offload": "on", 
                "generic_segmentation_offload": "on", 
                "highdma": "off [fixed]", 
                "hw_tc_offload": "off [fixed]", 
                "l2_fwd_offload": "off [fixed]", 
                "large_receive_offload": "off [fixed]", 
                "loopback": "off [fixed]", 
                "netns_local": "off [fixed]", 
                "ntuple_filters": "off [fixed]", 
                "receive_hashing": "off [fixed]", 
                "rx_all": "off", 
                "rx_checksumming": "off", 
                "rx_fcs": "off", 
                "rx_gro_hw": "off [fixed]", 
                "rx_udp_tunnel_port_offload": "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_csum_segmentation": "off [fixed]", 
                "tx_gre_segmentation": "off [fixed]", 
                "tx_gso_partial": "off [fixed]", 
                "tx_gso_robust": "off [fixed]", 
                "tx_ipip_segmentation": "off [fixed]", 
                "tx_lockless": "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": "off [fixed]", 
                "tx_tcp_ecn_segmentation": "off [fixed]", 
                "tx_tcp_mangleid_segmentation": "off", 
                "tx_tcp_segmentation": "on", 
                "tx_udp_tnl_csum_segmentation": "off [fixed]", 
                "tx_udp_tnl_segmentation": "off [fixed]", 
                "tx_vlan_offload": "on [fixed]", 
                "tx_vlan_stag_hw_insert": "off [fixed]", 
                "udp_fragmentation_offload": "off [fixed]", 
                "vlan_challenged": "off [fixed]"
            }, 
            "hw_timestamp_filters": [], 
            "ipv4": {
                "address": "192.168.159.131", 
                "broadcast": "192.168.159.255", 
                "netmask": "255.255.255.0", 
                "network": "192.168.159.0"
            }, 
            "ipv6": [
                {
                    "address": "fe80::e68f:2f9d:64c4:eaf", 
                    "prefix": "64", 
                    "scope": "link"
                }
            ], 
            "macaddress": "00:0c:29:1e:c8:6c", 
            "module": "e1000", 
            "mtu": 1500, 
            "pciid": "0000:02:01.0", 
            "promisc": false, 
            "speed": 1000, 
            "timestamping": [
                "tx_software", 
                "rx_software", 
                "software"
            ], 
            "type": "ether"
        }, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

也可以使用通配符来查找:

ansible_manager ~ > ansible webservers -m setup -a "filter=*_ipv4"
192.168.159.131 | SUCCESS => {
    "ansible_facts": {
        "ansible_default_ipv4": {
            "address": "192.168.159.131", 
            "alias": "ens33", 
            "broadcast": "192.168.159.255", 
            "gateway": "192.168.159.2", 
            "interface": "ens33", 
            "macaddress": "00:0c:29:1e:c8:6c", 
            "mtu": 1500, 
            "netmask": "255.255.255.0", 
            "network": "192.168.159.0", 
            "type": "ether"
        }, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

值得注意的是,这里 filter 的内容只能过滤到 ansible_facts 下一层的键值对,无法进行更精细的过滤

变量引用 json 数据方式

虽然说 setupfilter 模块只能解析到第二层键值对,但是它返回来的数据仍是 json 串。实时上许多模块执行后返回给主控端的值都是 json 串,而对于 json 串 可以通过转变成 playbook 的变量来获取更细的数据

debug 模块

debug 是 ansible 版本的 print 语句,可以输出变量的内容或者随意的字符串,利于 playbook 执行阶段的调试,参数有:

  • msg:输出定义好的 message,如果没有则默认输出 Hello world!msg 引用变量的语法为 Jinja2
  • var:输出变量的内容,不可与 msg 选项公用

register 注册变量

register 可以用在 tasks 中,用于注册变量,得到的值为 tasks 的返回值,可以通过返回值来判断任务的执行状态

引用模块命令的输出

将命令注册成变量,并用 debug 模块输出或直接在 template 或者 playbook 中引用

# test.yml
- hosts: 192.168.159.131
  tasks: 
  - shell: echo hello world
  	# 注册这个任务的输出结果
    register: say_hi
  - debug: var=say_hi
ansible_manager ~ > ansible-playbook test.yml 

PLAY [192.168.159.131] *********************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [192.168.159.131]

TASK [shell] *******************************************************************************************************
changed: [192.168.159.131]

TASK [debug] *******************************************************************************************************
ok: [192.168.159.131] => {
    "say_hi": {
        "changed": true, 
        "cmd": "echo hello world", 
        "delta": "0:00:00.004234", 
        "end": "2020-03-26 20:17:59.933311", 
        "failed": false, 
        "rc": 0, 
        "start": "2020-03-26 20:17:59.929077", 
        "stderr": "", 
        "stderr_lines": [], 
        "stdout": "hello world", 
        "stdout_lines": [
            "hello world"
        ]
    }
}

PLAY RECAP *********************************************************************************************************
192.168.159.131            : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

可以看到,执行 debug 模块后,返回了 shell 模块执行的结果,执行状态、使用的命令等

引用 json 字典/数组数据

通过引用模块命令的输出可以看到这个返回值同样是一大段 json 串,这时候就 json 子串中的键值对或列表就可以引用字典或数组的方式来获得更细的结果

  • 字典:引用键值对,通过 key[‘dict’] 或 key.dict
# test.yml
- hosts: 192.168.159.131
  tasks: 
  - shell: echo hello world
    register: say_hi
  - debug: var=say_hi.stdout
  - debug: var=say_hi['stdout']
ansible_manager ~ > ansible-playbook test.yml 

PLAY [192.168.159.131] *********************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [192.168.159.131]

TASK [shell] *******************************************************************************************************
changed: [192.168.159.131]

TASK [debug] *******************************************************************************************************
ok: [192.168.159.131] => {
    "say_hi.stdout": "hello world"
}

TASK [debug] *******************************************************************************************************
ok: [192.168.159.131] => {
    "say_hi['stdout']": "hello world"
}

PLAY RECAP *********************************************************************************************************
192.168.159.131            : ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  
  • 数组:引用列表,通过 key[N],N 从 0 开始
# test.yml
- hosts: 192.168.159.131
  tasks: 
  - shell: echo hello world
    register: say_hi
  - debug: var=say_hi.stdout_lines[0]
ansible_manager ~ > ansible-playbook test.yml 

PLAY [192.168.159.131] *********************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [192.168.159.131]

TASK [shell] *******************************************************************************************************
changed: [192.168.159.131]

TASK [debug] *******************************************************************************************************
ok: [192.168.159.131] => {
    "say_hi.stdout_lines[0]": "hello world"
}

PLAY RECAP *********************************************************************************************************
192.168.159.131            : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

引用 facts 数据

从前面 playbook 的执行过程可以看到,第一个执行的 task 总是 Gathering Facts:其实在执行每一个 playbook 时 ansible 都会自动为我们注册一个 ansible_facts 的变量,我们可以直接引用

# test.yml
- hosts: 192.168.159.131
  tasks: 
  - shell: echo hello world
    register: say_hi
  - debug: msg={{ ansible_facts.ens33.ipv4.address }}	# 在这里引用内层字典会自动把ansible_的头去掉
ansible_manager ~ > ansible-playbook test.yml 

PLAY [192.168.159.131] *********************************************************************************************

TASK [Gathering Facts] *********************************************************************************************
ok: [192.168.159.131]

TASK [shell] *******************************************************************************************************
changed: [192.168.159.131]

TASK [debug] *******************************************************************************************************
ok: [192.168.159.131] => {
    "ansible_facts.ens33.ipv4.address": "192.168.159.131"
}

PLAY RECAP *********************************************************************************************************
192.168.159.131            : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

注册和定义变量的方式

从命令行中传递

使用 -e 选项定义变量

ansible IP -m shell -a "echo {{ say_hi }}" -e 'say_hi="hello_world"'

playbook 中的 vars

# playbook.yml
- hosts: localhost
  vars:
    var1: value1
    var2: value2
  tasks:
    - debug: msg="{{ var1 }} {{ var2 }}"
      vars:
      	# 输出的var2是value2.2,局部优先
        var2: value2.2

通过 register 注册

# playbook.yml
- hosts: 192.168.159.131
  tasks: 
  - shell: echo hello world
    register: say_hi
  - debug: var=say_hi.stdout

通过 set_fact 模块定义

# playbook.yml
- hosts: localhost
  tasks:
    - set_fact: one_fact="something"
    - debug: var=one_fact

通过 var_files 文件定义

# playbook.yml
- hosts: localhost
  vars_files:
    - var_file.yml
  tasks:
    - debug: msg="{{ var1 }} {{ var2 }}"
# var_file.yml
var1: value1
var2: value2

inventory 中的主机变量和主机组变量

# 局部优先
192.168.100.68 ansible_ssh_port=22 var1=1
[centos7]
192.168.100.63
192.168.100.64
192.168.100.65 var1=2
[centos7:vars]
var1=2.2
var2=3
[all:vars]
var2=4

两种采集自定义数据的方式

局限性:所有文件、脚本在远程主机中定义

通过 .fact 文件

在远程主机上创建 /etc/ansible/facts.d/ 目录,将定义的数据写入 .fact 文件中放在这里,在主控端就可以通过 setup 模块过滤出 ansible_local 来取得这些数据。.fact 的语法与 Windows 上 .ini 文件的语法格式一样

# 远程主机
# /etc/ansible/facts.d/cpuinfo.fact
[cpuinfo]
cpunum=6
cpuname=i7 8700tes
ansible_manager ~ > ansible webservers -m setup -a "filter=ansible_local"
192.168.159.131 | SUCCESS => {
    "ansible_facts": {
        "ansible_local": {
            "cpuinfo": {
                "cpu": {
                    "cpuname": "i7 8700tes", 
                    "cpunum": "4"
                }
            }, 
        }, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

通过 python 脚本

同样也是将 python 脚本放在远程主机中的 /etc/ansible/facts.d/ 目录下。python 脚本的后缀也为.fact。由于是脚本文件,需要给文件加执行权限

#!/usr/bin/env python
# 远程主机,写python脚本获取最大支持的进程数
# /etc/ansible/facts.d/get_process.fact

import os,json
def get_process_num():
	dic = {}
	file = os.popen('ulimit -n').read().strip()
	dic['pnum'] = file
	print json.dumps(dic)

if __name__ == '__main__':
	get_process_num()
ansible_manager ~ > ansible webservers -m setup -a "filter=ansible_local"
192.168.159.131 | SUCCESS => {
    "ansible_facts": {
        "ansible_local": {
            "cpuinfo": {
                "cpu": {
                    "cpuname": "i7 8700tes", 
                    "cpunum": "4"
                }
            }, 
            "get_process": {
                "pnum": "1024"
            }
        }, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

自定义模块

优点:文件和脚本都在主控端中,更方便

编写模块

ansible 的模块/usr/share/my_modules/ 目录中

#!/usr/bin/env python
# 主控端
# /usr/share/my_modules/uptime.py

import json
import os
up = os.popen('uptime').read()
dic = {"result": up}
print json.dumps(dic)

启动模块目录

ansible 默认是不启用自定义模块的,需要在配置文件中打开

vim /etc/ansible/ansible.cfg

libray=/usr/share/my_modules/

测试自定义模块

可以使用 ansible-doc -l 命令来查看模块是否被 ansible 记录在内

ansible_manager ~ > ansible-doc -l | grep uptime
uptimerobot                                                   Pause and start Uptime Robot monitoring          
uptime                                                        UNDOCUMENTED                                

执行测试

ansible_manager ~ > ansible all -m uptime
192.168.159.131 | SUCCESS => {
    "changed": false, 
    "result": " 21:16:59 up  7:01,  4 users,  load average: 0.00, 0.01, 0.05\n"
}
发布了67 篇原创文章 · 获赞 2 · 访问量 1363

猜你喜欢

转载自blog.csdn.net/weixin_42511320/article/details/105131512
今日推荐