Ansible剧本功能实践介绍

以下例子的配置文件

[rsync:children]
rsync_server
rsync_client

[rsync_server]
192.168.1.5

[rsync_client]
192.168.1.4
/etc/ansible/hosts

编写剧本的重要功能介绍
a 在剧本中设置变量信息 
b 在剧本中设置注册信息 
c 在剧本中设置判断信息 
d 在剧本中设置循环信息
e在剧本中设置错误忽略
f 在剧本中设置标签信息
g 在剧本中设置触发信息
h 在剧本中进行剧本整合

a 在剧本中设置变量信息

方式一:直接在剧本文件编写 
vars:
oldboy01: data01
oldboy02: data02

方式二:在命令行中进行指定
ansible-playbook --extra-vars=oldboy01=data01

方式三:在主机清单文件编写
[oldboy]
oldboy01=data01
oldboy02=data02

三种变量设置方式都配置了,三种方式的优先级???
最优先: 命令行变量设置
次优先: 剧本中变量设置
最后: 主机清单变量设置

如何全局设置变量: roles 剧本整合???

b. 在剧本中设置注册信息

- hosts: oldboy
  tasks:
    - name: check server port
      shell: netstat -lntup   #--- 端口信息
      register: get_server_port  #注册端口变量<--端口信息

 例子演示:
- name: display port info
debug: msg={{ get_server_port.stdout_lines }}
显示进程信息,表示服务已经正常启动
PS: 设置变量不能有空格信息

- hosts: rsync_server
  tasks:
    - name: 01-install rsync
      yum: name=rsync state=installed
    #- name: 02-push conf file    
    #  copy: src=/etc/ansible/server_file/rsync_server/rsyncd.conf dest=/etc/
    - name: 03-create user
      user: name=rsync createhome=no shell=/sbin/nologin
    - name: 04-create backup dir
      file: path=/backup state=directory owner=rsync group=rsync
    - name: 05-create password file
      copy: content=rsync_backup:oldboy123 dest=/etc/rsync.password mode=600
    - name: 06-start rsync server
      service: name=rsyncd state=started enabled=yes
    - name: 07-check server port info
      shell: netstat -lntup | grep 873
      register: get_server_port #注册表量
    - name: display port info
      debug: msg={{ get_server_port.stdout_lines }} #输出信息

测试的错误 因为是测试 netstat -lntup | grep 873 找不端口 所以注册的变量没有值 报错  这个错误直接运行就可以

正常执行的结果


c. 在剧本中设置判断信息

先介绍:[root@linux-node2 ~]# ansible rsync_server -m setup #查看主机清单中的详细信息

[root@linux-node2 ~]# ansible rsync_server -m setup 
192.168.1.5 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.1.5", 
            "192.168.122.1"
        ], 
        "ansible_all_ipv6_addresses": [
            "fe80::cd7:c134:744a:cf30"
        ], 
        "ansible_apparmor": {
            "status": "disabled"
        }, 
        "ansible_architecture": "x86_64", 
        "ansible_bios_date": "07/02/2015", 
        "ansible_bios_version": "6.00", 
        "ansible_cmdline": {
            "BOOT_IMAGE": "/vmlinuz-3.10.0-957.el7.x86_64", 
            "LANG": "zh_CN.UTF-8", 
            "crashkernel": "auto", 
            "quiet": true, 
            "rd.lvm.lv": "centos/swap", 
            "rhgb": true, 
            "ro": true, 
            "root": "/dev/mapper/centos-root"
        }, 
        "ansible_date_time": {
            "date": "2019-08-12", 
            "day": "12", 
            "epoch": "1565619030", 
            "hour": "22", 
            "iso8601": "2019-08-12T14:10:30Z", 
            "iso8601_basic": "20190812T221030013216", 
            "iso8601_basic_short": "20190812T221030", 
            "iso8601_micro": "2019-08-12T14:10:30.013353Z", 
            "minute": "10", 
            "month": "08", 
            "second": "30", 
            "time": "22:10:30", 
            "tz": "CST", 
            "tz_offset": "+0800", 
            "weekday": "Monday", 
            "weekday_number": "1", 
            "weeknumber": "32", 
            "year": "2019"
        }, 
        "ansible_default_ipv4": {
            "address": "192.168.1.5", 
            "alias": "ens33", 
            "broadcast": "192.168.1.255", 
            "gateway": "192.168.1.1", 
            "interface": "ens33", 
            "macaddress": "00:0c:29:fd:fa:c7", 
            "mtu": 1500, 
            "netmask": "255.255.255.0", 
            "network": "192.168.1.0", 
            "type": "ether"
        }, 
        "ansible_default_ipv6": {}, 
        "ansible_device_links": {
            "ids": {
                "dm-0": [
                    "dm-name-centos-root", 
                    "dm-uuid-LVM-2HXnXe7BZbcjs9fRvZshBrZAC54ATdRIuLSuoIykDvFy9cUdhwaCxE3cXEk4czeG"
                ], 
                "dm-1": [
                    "dm-name-centos-swap", 
                    "dm-uuid-LVM-2HXnXe7BZbcjs9fRvZshBrZAC54ATdRI117wIGnJ5dFMLKYyL4sHfZrgnHn7KNwn"
                ], 
                "dm-2": [
                    "dm-name-centos-home", 
                    "dm-uuid-LVM-2HXnXe7BZbcjs9fRvZshBrZAC54ATdRI85923erIvUJ1mQw9m39jQY5kvSWDXecm"
                ], 
                "sda2": [
                    "lvm-pv-uuid-gqQMB2-Grt9-n4iL-KiZd-dlud-psxw-Dbg9pu"
                ], 
                "sr0": [
                    "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
                ]
            }, 
            "labels": {}, 
            "masters": {
                "sda2": [
                    "dm-0", 
                    "dm-1", 
                    "dm-2"
                ]
            }, 
            "uuids": {
                "dm-0": [
                    "dc3c2d3c-626f-4ada-ac5a-8c3cb5aaa7d6"
                ], 
                "dm-1": [
                    "a84c6a0e-1540-4b11-86a6-60887bb2e923"
                ], 
                "dm-2": [
                    "e7737792-f46e-4acc-86fe-b782ce492618"
                ], 
                "sda1": [
                    "cbb5b15b-ed4b-4e77-9275-834bc5de2d85"
                ]
            }
        }, 
        "ansible_devices": {
            "dm-0": {
                "holders": [], 
                "host": "", 
                "links": {
                    "ids": [
                        "dm-name-centos-root", 
                        "dm-uuid-LVM-2HXnXe7BZbcjs9fRvZshBrZAC54ATdRIuLSuoIykDvFy9cUdhwaCxE3cXEk4czeG"
                    ], 
                    "labels": [], 
                    "masters": [], 
                    "uuids": [
                        "dc3c2d3c-626f-4ada-ac5a-8c3cb5aaa7d6"
                    ]
                }, 
                "model": null, 
                "partitions": {}, 
                "removable": "0", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "", 
                "sectors": "77668352", 
                "sectorsize": "512", 
                "size": "37.04 GB", 
                "support_discard": "0", 
                "vendor": null, 
                "virtual": 1
            }, 
            "dm-1": {
                "holders": [], 
                "host": "", 
                "links": {
                    "ids": [
                        "dm-name-centos-swap", 
                        "dm-uuid-LVM-2HXnXe7BZbcjs9fRvZshBrZAC54ATdRI117wIGnJ5dFMLKYyL4sHfZrgnHn7KNwn"
                    ], 
                    "labels": [], 
                    "masters": [], 
                    "uuids": [
                        "a84c6a0e-1540-4b11-86a6-60887bb2e923"
                    ]
                }, 
                "model": null, 
                "partitions": {}, 
                "removable": "0", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "", 
                "sectors": "8126464", 
                "sectorsize": "512", 
                "size": "3.88 GB", 
                "support_discard": "0", 
                "vendor": null, 
                "virtual": 1
            }, 
            "dm-2": {
                "holders": [], 
                "host": "", 
                "links": {
                    "ids": [
                        "dm-name-centos-home", 
                        "dm-uuid-LVM-2HXnXe7BZbcjs9fRvZshBrZAC54ATdRI85923erIvUJ1mQw9m39jQY5kvSWDXecm"
                    ], 
                    "labels": [], 
                    "masters": [], 
                    "uuids": [
                        "e7737792-f46e-4acc-86fe-b782ce492618"
                    ]
                }, 
                "model": null, 
                "partitions": {}, 
                "removable": "0", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "", 
                "sectors": "37920768", 
                "sectorsize": "512", 
                "size": "18.08 GB", 
                "support_discard": "0", 
                "vendor": null, 
                "virtual": 1
            }, 
            "sda": {
                "holders": [], 
                "host": "SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)", 
                "links": {
                    "ids": [], 
                    "labels": [], 
                    "masters": [], 
                    "uuids": []
                }, 
                "model": "VMware Virtual S", 
                "partitions": {
                    "sda1": {
                        "holders": [], 
                        "links": {
                            "ids": [], 
                            "labels": [], 
                            "masters": [], 
                            "uuids": [
                                "cbb5b15b-ed4b-4e77-9275-834bc5de2d85"
                            ]
                        }, 
                        "sectors": "2097152", 
                        "sectorsize": 512, 
                        "size": "1.00 GB", 
                        "start": "2048", 
                        "uuid": "cbb5b15b-ed4b-4e77-9275-834bc5de2d85"
                    }, 
                    "sda2": {
                        "holders": [
                            "centos-root", 
                            "centos-swap", 
                            "centos-home"
                        ], 
                        "links": {
                            "ids": [
                                "lvm-pv-uuid-gqQMB2-Grt9-n4iL-KiZd-dlud-psxw-Dbg9pu"
                            ], 
                            "labels": [], 
                            "masters": [
                                "dm-0", 
                                "dm-1", 
                                "dm-2"
                            ], 
                            "uuids": []
                        }, 
                        "sectors": "123729920", 
                        "sectorsize": 512, 
                        "size": "59.00 GB", 
                        "start": "2099200", 
                        "uuid": null
                    }
                }, 
                "removable": "0", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "deadline", 
                "sectors": "125829120", 
                "sectorsize": "512", 
                "size": "60.00 GB", 
                "support_discard": "0", 
                "vendor": "VMware,", 
                "virtual": 1
            }, 
            "sr0": {
                "holders": [], 
                "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)", 
                "links": {
                    "ids": [
                        "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
                    ], 
                    "labels": [], 
                    "masters": [], 
                    "uuids": []
                }, 
                "model": "VMware IDE CDR10", 
                "partitions": {}, 
                "removable": "1", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "deadline", 
                "sectors": "2097151", 
                "sectorsize": "512", 
                "size": "1024.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.6.1810", 
        "ansible_dns": {
            "nameservers": [
                "192.168.1.1"
            ], 
            "search": [
                "localdomain"
            ]
        }, 
        "ansible_domain": "localdomain", 
        "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.1.5", 
                "broadcast": "192.168.1.255", 
                "netmask": "255.255.255.0", 
                "network": "192.168.1.0"
            }, 
            "ipv6": [
                {
                    "address": "fe80::cd7:c134:744a:cf30", 
                    "prefix": "64", 
                    "scope": "link"
                }
            ], 
            "macaddress": "00:0c:29:fd:fa:c7", 
            "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": "en_US.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", 
            "SHELL": "/bin/bash", 
            "SHLVL": "2", 
            "SSH_CLIENT": "192.168.1.4 49084 22", 
            "SSH_CONNECTION": "192.168.1.4 49084 192.168.1.5 22", 
            "SSH_TTY": "/dev/pts/1", 
            "TERM": "xterm", 
            "USER": "root", 
            "VIRTUALENVWRAPPER_HOOK_DIR": "/root/Envs", 
            "VIRTUALENVWRAPPER_PROJECT_FILENAME": ".project", 
            "VIRTUALENVWRAPPER_SCRIPT": "/opt/python36/bin/virtualenvwrapper.sh", 
            "VIRTUALENVWRAPPER_WORKON_CD": "1", 
            "WORKON_HOME": "/root/Envs", 
            "XDG_RUNTIME_DIR": "/run/user/0", 
            "XDG_SESSION_ID": "2", 
            "_": "/usr/bin/python"
        }, 
        "ansible_fips": false, 
        "ansible_form_factor": "Other", 
        "ansible_fqdn": "localhost.localdomain", 
        "ansible_hostname": "linux-node1", 
        "ansible_interfaces": [
            "lo", 
            "ens33", 
            "virbr0-nic", 
            "virbr0"
        ], 
        "ansible_kernel": "3.10.0-957.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_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": {}, 
        "ansible_lsb": {}, 
        "ansible_lvm": {
            "lvs": {
                "home": {
                    "size_g": "18.08", 
                    "vg": "centos"
                }, 
                "root": {
                    "size_g": "37.04", 
                    "vg": "centos"
                }, 
                "swap": {
                    "size_g": "3.88", 
                    "vg": "centos"
                }
            }, 
            "pvs": {
                "/dev/sda2": {
                    "free_g": "0.00", 
                    "size_g": "59.00", 
                    "vg": "centos"
                }
            }, 
            "vgs": {
                "centos": {
                    "free_g": "0.00", 
                    "num_lvs": "3", 
                    "num_pvs": "1", 
                    "size_g": "59.00"
                }
            }
        }, 
        "ansible_machine": "x86_64", 
        "ansible_machine_id": "37a27c09411541ca8f072be3ccc05527", 
        "ansible_memfree_mb": 2726, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 3012, 
                "used": 759
            }, 
            "real": {
                "free": 2726, 
                "total": 3771, 
                "used": 1045
            }, 
            "swap": {
                "cached": 0, 
                "free": 3967, 
                "total": 3967, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 3771, 
        "ansible_mounts": [
            {
                "block_available": 7120934, 
                "block_size": 4096, 
                "block_total": 9703804, 
                "block_used": 2582870, 
                "device": "/dev/mapper/centos-root", 
                "fstype": "xfs", 
                "inode_available": 19260818, 
                "inode_total": 19417088, 
                "inode_used": 156270, 
                "mount": "/", 
                "options": "rw,relatime,attr2,inode64,noquota", 
                "size_available": 29167345664, 
                "size_total": 39746781184, 
                "uuid": "dc3c2d3c-626f-4ada-ac5a-8c3cb5aaa7d6"
            }, 
            {
                "block_available": 222443, 
                "block_size": 4096, 
                "block_total": 259584, 
                "block_used": 37141, 
                "device": "/dev/sda1", 
                "fstype": "xfs", 
                "inode_available": 523961, 
                "inode_total": 524288, 
                "inode_used": 327, 
                "mount": "/boot", 
                "options": "rw,relatime,attr2,inode64,noquota", 
                "size_available": 911126528, 
                "size_total": 1063256064, 
                "uuid": "cbb5b15b-ed4b-4e77-9275-834bc5de2d85"
            }, 
            {
                "block_available": 4729288, 
                "block_size": 4096, 
                "block_total": 4737536, 
                "block_used": 8248, 
                "device": "/dev/mapper/centos-home", 
                "fstype": "xfs", 
                "inode_available": 9480189, 
                "inode_total": 9480192, 
                "inode_used": 3, 
                "mount": "/home", 
                "options": "rw,relatime,attr2,inode64,noquota", 
                "size_available": 19371163648, 
                "size_total": 19404947456, 
                "uuid": "e7737792-f46e-4acc-86fe-b782ce492618"
            }, 
            {
                "block_available": 125595, 
                "block_size": 131072, 
                "block_total": 139152, 
                "block_used": 13557, 
                "device": "192.168.1.4:/opt/share", 
                "fstype": "nfs4", 
                "inode_available": 8854887, 
                "inode_total": 8910848, 
                "inode_used": 55961, 
                "mount": "/mnt/nfs/235674007260975", 
                "options": "rw,relatime,vers=4.1,rsize=131072,wsize=131072,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,clientaddr=192.168.1.5,local_lock=none,addr=192.168.1.4", 
                "size_available": 16461987840, 
                "size_total": 18238930944, 
                "uuid": "N/A"
            }, 
            {
                "block_available": 125595, 
                "block_size": 131072, 
                "block_total": 139152, 
                "block_used": 13557, 
                "device": "192.168.1.4:/opt/volume", 
                "fstype": "nfs4", 
                "inode_available": 8854887, 
                "inode_total": 8910848, 
                "inode_used": 55961, 
                "mount": "/mnt/nfs/402885735082765", 
                "options": "rw,relatime,vers=4.1,rsize=131072,wsize=131072,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,clientaddr=192.168.1.5,local_lock=none,addr=192.168.1.4", 
                "size_available": 16461987840, 
                "size_total": 18238930944, 
                "uuid": "N/A"
            }, 
            {
                "block_available": 125595, 
                "block_size": 131072, 
                "block_total": 139152, 
                "block_used": 13557, 
                "device": "192.168.1.4:/opt/test", 
                "fstype": "nfs4", 
                "inode_available": 8854887, 
                "inode_total": 8910848, 
                "inode_used": 55961, 
                "mount": "/mnt/nfs/086690657201746", 
                "options": "rw,relatime,vers=4.1,rsize=131072,wsize=131072,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,clientaddr=192.168.1.5,local_lock=none,addr=192.168.1.4", 
                "size_available": 16461987840, 
                "size_total": 18238930944, 
                "uuid": "N/A"
            }
        ], 
        "ansible_nodename": "linux-node1.localdomain", 
        "ansible_os_family": "RedHat", 
        "ansible_pkg_mgr": "yum", 
        "ansible_processor": [
            "0", 
            "GenuineIntel", 
            "Intel(R) Core(TM) i7-4710MQ CPU @ 2.50GHz", 
            "1", 
            "GenuineIntel", 
            "Intel(R) Core(TM) i7-4710MQ CPU @ 2.50GHz", 
            "2", 
            "GenuineIntel", 
            "Intel(R) Core(TM) i7-4710MQ CPU @ 2.50GHz", 
            "3", 
            "GenuineIntel", 
            "Intel(R) Core(TM) i7-4710MQ CPU @ 2.50GHz"
        ], 
        "ansible_processor_cores": 2, 
        "ansible_processor_count": 2, 
        "ansible_processor_threads_per_core": 1, 
        "ansible_processor_vcpus": 4, 
        "ansible_product_name": "VMware Virtual Platform", 
        "ansible_product_serial": "VMware-56 4d 48 8f 93 62 a0 3f-01 fa 25 b5 f5 fd fa c7", 
        "ansible_product_uuid": "8F484D56-6293-3FA0-01FA-25B5F5FDFAC7", 
        "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": {
            "status": "disabled"
        }, 
        "ansible_selinux_python_present": true, 
        "ansible_service_mgr": "systemd", 
        "ansible_ssh_host_key_ecdsa_public": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFqIRP8gB3zra3sWTF54icmj7D7FtgaN4o79aObpxCWbIVAGdGXzZiRVBUgIsqgdeXenJID4qqKHDeUIlvaobjE=", 
        "ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIP44SN7gTNphLERxVIIm0XcASzCjC3AQeL4Z4qVD1ZVY", 
        "ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDHMohDGQkc78uqcsdt2CEvI1/0UolA0t7Y7ZPPAhVBlrvt8s9Wo7YA2yZllIH5nr9VFML1se/tIepq3uQbeIdCHyzDiBKI2k5A9Dm76+019Xb8566fEXxj410gkxPoOeT438PbD+Z9xezoNosvwtG/AW2r2UfhICZCZpN5UEsYZeTsmF/5vpVDyswd8nWft4kg0tBopWWceqgEzB0E+4xhGRlMAtMmxgQ6BocwjBczsnHyYF7OJdshaDibDk8AgwlWvM6hd+ycf9sW4YkicN2NAHG7EHxcZUDu7pgDqObzTAfhmWFnEh6pAZjrpA8kQANohrDY3LdpAcstmN8ae41J", 
        "ansible_swapfree_mb": 3967, 
        "ansible_swaptotal_mb": 3967, 
        "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": 340, 
        "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_virbr0": {
            "active": false, 
            "device": "virbr0", 
            "features": {
                "busy_poll": "off [fixed]", 
                "fcoe_mtu": "off [fixed]", 
                "generic_receive_offload": "on", 
                "generic_segmentation_offload": "on", 
                "highdma": "off [requested on]", 
                "hw_tc_offload": "off [fixed]", 
                "l2_fwd_offload": "off [fixed]", 
                "large_receive_offload": "off [fixed]", 
                "loopback": "off [fixed]", 
                "netns_local": "on [fixed]", 
                "ntuple_filters": "off [fixed]", 
                "receive_hashing": "off [fixed]", 
                "rx_all": "off [fixed]", 
                "rx_checksumming": "off [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", 
                "tx_checksum_ipv4": "off [fixed]", 
                "tx_checksum_ipv6": "off [fixed]", 
                "tx_checksum_sctp": "off [fixed]", 
                "tx_checksumming": "on", 
                "tx_fcoe_segmentation": "off [requested on]", 
                "tx_gre_csum_segmentation": "on", 
                "tx_gre_segmentation": "on", 
                "tx_gso_partial": "on", 
                "tx_gso_robust": "off [requested on]", 
                "tx_ipip_segmentation": "on", 
                "tx_lockless": "on [fixed]", 
                "tx_nocache_copy": "off", 
                "tx_scatter_gather": "on", 
                "tx_scatter_gather_fraglist": "on", 
                "tx_sctp_segmentation": "off [requested on]", 
                "tx_sit_segmentation": "on", 
                "tx_tcp6_segmentation": "on", 
                "tx_tcp_ecn_segmentation": "on", 
                "tx_tcp_mangleid_segmentation": "on", 
                "tx_tcp_segmentation": "on", 
                "tx_udp_tnl_csum_segmentation": "on", 
                "tx_udp_tnl_segmentation": "on", 
                "tx_vlan_offload": "on", 
                "tx_vlan_stag_hw_insert": "on", 
                "udp_fragmentation_offload": "off [requested on]", 
                "vlan_challenged": "off [fixed]"
            }, 
            "hw_timestamp_filters": [], 
            "id": "8000.5254001739b3", 
            "interfaces": [
                "virbr0-nic"
            ], 
            "ipv4": {
                "address": "192.168.122.1", 
                "broadcast": "192.168.122.255", 
                "netmask": "255.255.255.0", 
                "network": "192.168.122.0"
            }, 
            "macaddress": "52:54:00:17:39:b3", 
            "mtu": 1500, 
            "promisc": false, 
            "stp": true, 
            "timestamping": [
                "rx_software", 
                "software"
            ], 
            "type": "bridge"
        }, 
        "ansible_virbr0_nic": {
            "active": false, 
            "device": "virbr0-nic", 
            "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 [fixed]", 
                "rx_checksumming": "off [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": "off", 
                "tx_checksum_fcoe_crc": "off [fixed]", 
                "tx_checksum_ip_generic": "off [requested on]", 
                "tx_checksum_ipv4": "off [fixed]", 
                "tx_checksum_ipv6": "off [fixed]", 
                "tx_checksum_sctp": "off [fixed]", 
                "tx_checksumming": "off", 
                "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", 
                "tx_scatter_gather": "on", 
                "tx_scatter_gather_fraglist": "on", 
                "tx_sctp_segmentation": "off [fixed]", 
                "tx_sit_segmentation": "off [fixed]", 
                "tx_tcp6_segmentation": "off [requested on]", 
                "tx_tcp_ecn_segmentation": "off [requested on]", 
                "tx_tcp_mangleid_segmentation": "off", 
                "tx_tcp_segmentation": "off [requested on]", 
                "tx_udp_tnl_csum_segmentation": "off [fixed]", 
                "tx_udp_tnl_segmentation": "off [fixed]", 
                "tx_vlan_offload": "on", 
                "tx_vlan_stag_hw_insert": "on", 
                "udp_fragmentation_offload": "off [requested on]", 
                "vlan_challenged": "off [fixed]"
            }, 
            "hw_timestamp_filters": [], 
            "macaddress": "52:54:00:17:39:b3", 
            "mtu": 1500, 
            "promisc": true, 
            "timestamping": [
                "rx_software", 
                "software"
            ], 
            "type": "ether"
        }, 
        "ansible_virtualization_role": "guest", 
        "ansible_virtualization_type": "VMware", 
        "gather_subset": [
            "all"
        ], 
        "module_setup": true
    }, 
    "changed": false
}
View Code

这种字典操作在剧本中才有效
获取子信息方法:ansible_eth0[ipv4]

获取内置变量方法:
ansible oldboy -m setup -a "filter=ansible_hostname"

[root@linux-node2 ~]# ansible rsync_server -m setup -a "filter=ansible_hostname"
192.168.1.5 | SUCCESS => {
    "ansible_facts": {
        "ansible_hostname": "linux-node1"
    }, 
    "changed": false
}

 
常见主机信息:

ansible_all_ipv4_addresses: 仅显示ipv4的信息。
ansible_devices: 仅显示磁盘设备信息。
ansible_distribution: 显示是什么系统,例:centos,suse等。
ansible_distribution_major_version: 显示是系统主版本。
ansible_distribution_version: 仅显示系统版本。
ansible_machine: 显示系统类型,例:32位,还是64位。
ansible_eth0: 仅显示eth0的信息。
ansible_hostname: 仅显示主机名。
ansible_kernel: 仅显示内核版本。
ansible_lvm: 显示lvm相关信息。
ansible_memtotal_mb: 显示系统总内存。
ansible_memfree_mb: 显示可用系统内存。
ansible_memory_mb: 详细显示内存情况。
ansible_swaptotal_mb: 显示总的swap内存。
ansible_swapfree_mb: 显示swap内存的可用内存。
ansible_mounts: 显示系统磁盘挂载情况。
ansible_processor: 显示cpu个数(具体显示每个cpu的型号)。
ansible_processor_vcpus: 显示cpu个数(只显示总的个数)。

如何指定判断条件:
(ansible_hostname == "nfs01")#当主机名等于nfs01执行该任务
(ansible_hostname == "web01"))#当主机名等于web01执行该任务


setup模块中显示被管理主机系统的详细信息

- hosts: oldboy
remote_user: root
  tasks:
    - name: Check File
      file: path=/tmp/this_is_{{ ansible_hostname }}_file state=touch
      when: (ansible_hostname == "nfs") or (ansible_hostname == "backup")

    - name: install httpd
      yum: name=httpd state=installed
      when: (系统情况 == "CentOS")

    - name: install httpd2
      yum: name=httpd2 state=installed
      when: (系统情况 == "ubuntu") 



04. 在剧本中设置循环信息

- hosts: rsync_server
  tasks:
    - name: 01-install rsync
      yum: name={{ item }} state=installed #循环
      with_items:
        - rsync
        - tree
        - wget
    - name: 02-push conf file & password file
      #copy: src=/etc/ansible/server_file/rsync_server/rsyncd.conf dest=/etc/
      copy: src=/etc/ansible/server_file/rsync_server/{{ item.src }} dest={{ item.dest }} mode={{ item.mode }} #循环
      with_items:
        - { src: 'rsyncd.conf',dest: '/etc/',mode: '644' }
        - { src: 'rsync.password',dest: '/etc/',mode: '600' }
    - name: 03-create user
      user: name=rsync createhome=no shell=/sbin/nologin
    - name: 04-create backup dir
      file: path=/backup state=directory owner=rsync group=rsync
   # - name: 05-create password file
   #   copy: content=rsync_backup:oldboy123 dest=/etc/rsync.password mode=600
    - name: 06-start rsync server
      service: name=rsyncd state=started enabled=yes
    - name: 07-check server port info
      shell: netstat -lntup | grep 873
      register: get_server_port
    - name: display port info
      debug: msg={{ get_server_port.stdout_lines }}

运行结果:


vim test04.yml

- hosts: all
remote_user: root
  tasks:
    - name: Add Users
      user: name={{ item.name }} groups={{ item.groups }} state=present
      with_items:
        - { name: 'testuser1', groups: 'bin' }
        - { name: 'testuser2', groups: 'root' }


vim test05.yml

- hosts: all
remote_user: root
  tasks:
    - name: Installed Pkg
      yum: name={{ item }} state=present
      with_items:
        - wget
        - tree
        - lrzsz 

      
    - name: 01-install rsync
      yum:
        name: ['rsync', 'tree', 'wget']  --- saltstack  这种循环也可以
        state: installed
    
    - name: xxx
      yum: name=xxx state=installed      --- ansible

05. 在剧本中设置忽略错误

    剧本执行出现错误排查思路/步骤:
    1) 找到剧本中出现问题关键点
    2) 将剧本中的操作转换成模块进行操作
    3) 将模块的功能操作转换成linux命令
       本地管理主机上执行命令测试
       远程被管理主机上执行命令测试


默认playbook会检查命令和模块的返回状态,如遇到错误就中断playbook的执行
可以加入ignore_errors: yes忽略错误  就会跳过这个错误 不会中断   到后面再去解决


vim test06.yml

- hosts: all
remote_user: root
  tasks:
    - name: Ignore False
      command: /bin/false
      ignore_errors: yes
    - name: touch new file
      file: path=/tmp/oldboy_ignore state=touch 

06. 在剧本中设置标签功能

- hosts: oldboy
ignore_errors: yes
remote_user: root
  tasks:
    - name: Check File
      file: path=/tmp/this_is_{{ ansible_hostname }}_file state=touch
      when: (ansible_hostname == "nfs01") or (ansible_hostname == "backup")
      tags: t1

    - name: bad thing
      command: ech 123
      #ignore_errors: yes
      tags: t2

    - name: install httpd
      yum: name=httpd state=installed
      when: (ansible_all_ipv4_addresses == ["172.16.1.7","10.0.0.7"])
      tags: t3

    - name: install httpd2
      yum: name=httpd2 state=installed
      when: (ansible_distribution == "ubuntu")
      tags: t4

指定执行哪个标签任务: ansible-playbook --tags=t2 test05.yml
跳过指定标签任务: ansible-playbook --skip-tags=t2 test05.yml

- hosts: rsync_server
  tasks:
    - name: 01-install rsync
      yum: name={{ item }} state=installed #循环
      with_items:
        - rsync
        - tree
        - wget
      tags: install_soft #标签。。。
    - name: 02-push conf file & password file
      #copy: src=/etc/ansible/server_file/rsync_server/rsyncd.conf dest=/etc/
      copy: src=/etc/ansible/server_file/rsync_server/{{ item.src }} dest={{ item.dest }} mode={{ item.mode }} #循环
      with_items:
        - { src: 'rsyncd.conf',dest: '/etc/',mode: '644' }
        - { src: 'rsync.password',dest: '/etc/',mode: '600' }
    - name: 03-create user
      user: name=rsync createhome=no shell=/sbin/nologin
    - name: 04-create backup dir
      file: path=/backup state=directory owner=rsync group=rsync
   # - name: 05-create password file
   #   copy: content=rsync_backup:oldboy123 dest=/etc/rsync.password mode=600
    - name: 06-start rsync server
      service: name=rsyncd state=started enabled=yes
    - name: 07-check server port info
      shell: netstat -lntup | grep 873
      register: get_server_port
    - name: display port info
      debug: msg={{ get_server_port.stdout_lines }}
rsync例子

 

07. 在剧本中设置触发功能

- hosts: backup
remote_user: root
  tasks:
    - name: 01 Install rsync
      yum: name=rsync state=present

    - name: 02 push config file
      copy: src=./file/{{ item.src }} dest=/etc/{{ item.dest }} mode={{ item.mode }}
      with_items:
        - { src: "rsyncd.conf", dest: "rsyncd.conf", mode: "0644" }
        - { src: "rsync.password", dest: "rsync.password", mode: "0600" }
      notify: restart rsync server #上copy发生改变是触发

  handlers:
    - name: restart rsync server
      service: name=rsyncd state=restarted 
- hosts: rsync_server
  tasks:
    - name: 01-install rsync
      yum: name={{ item }} state=installed #循环
      with_items:
        - rsync
        - tree
        - wget
      tags: install_soft #标签。。。
    - name: 02-push conf file & password file
      #copy: src=/etc/ansible/server_file/rsync_server/rsyncd.conf dest=/etc/
      copy: src=/etc/ansible/server_file/rsync_server/{{ item.src }} dest={{ item.dest }} mode={{ item.mode }} #循环
      with_items:
        - { src: 'rsyncd.conf',dest: '/etc/',mode: '644' }
        - { src: 'rsync.password',dest: '/etc/',mode: '600' }
      notify: restart rsync server  #触发
    - name: 03-create user
      user: name=rsync createhome=no shell=/sbin/nologin
    - name: 04-create backup dir
      file: path=/backup state=directory owner=rsync group=rsync
   # - name: 05-create password file
   #   copy: content=rsync_backup:oldboy123 dest=/etc/rsync.password mode=600
    - name: 06-start rsync server
      service: name=rsyncd state=started enabled=yes
    - name: 07-check server port info
      shell: netstat -lntup | grep 873
      register: get_server_port
    - name: display port info
      debug: msg={{ get_server_port.stdout_lines }}
  handlers: #触发执行
    - name: restart rsync server
      service: name=rsyncd state=restarted
rsync小栗子


08. 将多个剧本进行整合
方式一:include_tasks: f1.yml
- hosts: all
remote_user: root
tasks:
- include_tasks: f1.yml
- include_tasks: f2.yml

方式二:include: f1.yml
- include:f1.yml
- include:f2.yml

方式三:- import_playbook:
[root@m01 ansible-playbook]# cat main.yml
- import_playbook: base.yml
- import_playbook: rsync.yml
- import_playbook: nfs.yml
- import_playbook: oxxx.yml
- import_playbook: rsync.yml
- import_playbook: nfs.yml

原文地址:https://www.cnblogs.com/linux985/p/11320228.html