做用:測試目標主機是否在線,若是在線則返回pong。html
ansible 172.16.1.10 -m ping 172.16.1.10 | SUCCESS => { "changed": false, "ping": "pong" }
做用:收集遠程主機的信息node
收集可用的facts,收集每一個節點的相關信息:架構信息,IP,時間,域名,網卡,MAC,主機名,CPU等信息。這些收集的信息,能夠做爲變量。python
ansible 172.16.1.11 -m setup 172.16.1.11 | SUCCESS => { "ansible_facts": { "ansible_all_ipv4_addresses": [ "172.16.1.11", "10.0.0.11" ], "ansible_all_ipv6_addresses": [ "fe80::20c:29ff:fe38:f731", "fe80::20c:29ff:fe38:f727" ], "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-327.el7.x86_64", "LANG": "en_US.UTF-8", "biosdevname": "0", "crashkernel": "auto", "net.ifnames": "0", "quiet": true, "rd.lvm.lv": "centos/swap", "rhgb": true, "ro": true, "root": "/dev/mapper/centos-root" }, "ansible_date_time": { "date": "2018-04-07", "day": "07", "epoch": "1523036430", "hour": "01", "iso8601": "2018-04-06T17:40:30Z", "iso8601_basic": "20180407T014030318261", "iso8601_basic_short": "20180407T014030", "iso8601_micro": "2018-04-06T17:40:30.318329Z", "minute": "40", "month": "04", "second": "30", "time": "01:40:30", "tz": "CST", "tz_offset": "+0800", "weekday": "Saturday", "weekday_number": "6", "weeknumber": "14", "year": "2018" }, "ansible_default_ipv4": { "address": "10.0.0.11", "alias": "eth0", "broadcast": "10.0.0.255", "gateway": "10.0.0.254", "interface": "eth0", "macaddress": "00:0c:29:38:f7:27", "mtu": 1500, "netmask": "255.255.255.0", "network": "10.0.0.0", "type": "ether" }, "ansible_default_ipv6": {}, "ansible_device_links": { "ids": { "dm-0": [ "dm-name-centos-root", "dm-uuid-LVM-OmgwEwCs46ML9QRxXxqk4cHvy540HNFalJbquES0XxGb6tBr1Cjy00IId3ONuhzH" ], "dm-1": [ "dm-name-centos-swap", "dm-uuid-LVM-OmgwEwCs46ML9QRxXxqk4cHvy540HNFam8DX5dgQd8KPEC76ow6eSbeDR05d25hd" ], "sda2": [ "lvm-pv-uuid-Sswdav-yqLM-dX1B-Iym0-2rB9-fDIC-ZaWlad" ] }, "labels": {}, "masters": { "sda2": [ "dm-0", "dm-1" ] }, "uuids": { "dm-0": [ "599eb534-f348-449e-8d17-dae06ec4ad14" ], "dm-1": [ "3b9e0480-0869-49be-b79e-1903a38b4362" ], "sda1": [ "60dc75a8-7a29-4f0a-bd1c-c16113b880a5" ] } }, "ansible_devices": { "dm-0": { "holders": [], "host": "", "links": { "ids": [ "dm-name-centos-root", "dm-uuid-LVM-OmgwEwCs46ML9QRxXxqk4cHvy540HNFalJbquES0XxGb6tBr1Cjy00IId3ONuhzH" ], "labels": [], "masters": [], "uuids": [ "599eb534-f348-449e-8d17-dae06ec4ad14" ] }, "model": null, "partitions": {}, "removable": "0", "rotational": "1", "sas_address": null, "sas_device_handle": null, "scheduler_mode": "", "sectors": "99540992", "sectorsize": "512", "size": "47.46 GB", "support_discard": "0", "vendor": null, "virtual": 1 }, "dm-1": { "holders": [], "host": "", "links": { "ids": [ "dm-name-centos-swap", "dm-uuid-LVM-OmgwEwCs46ML9QRxXxqk4cHvy540HNFam8DX5dgQd8KPEC76ow6eSbeDR05d25hd" ], "labels": [], "masters": [], "uuids": [ "3b9e0480-0869-49be-b79e-1903a38b4362" ] }, "model": null, "partitions": {}, "removable": "0", "rotational": "1", "sas_address": null, "sas_device_handle": null, "scheduler_mode": "", "sectors": "4194304", "sectorsize": "512", "size": "2.00 GB", "support_discard": "0", "vendor": null, "virtual": 1 }, "sda": { "holders": [], "host": "", "links": { "ids": [], "labels": [], "masters": [], "uuids": [] }, "model": "VMware Virtual S", "partitions": { "sda1": { "holders": [], "links": { "ids": [], "labels": [], "masters": [], "uuids": [ "60dc75a8-7a29-4f0a-bd1c-c16113b880a5" ] }, "sectors": "1024000", "sectorsize": 512, "size": "500.00 MB", "start": "2048", "uuid": "60dc75a8-7a29-4f0a-bd1c-c16113b880a5" }, "sda2": { "holders": [ "centos-root", "centos-swap" ], "links": { "ids": [ "lvm-pv-uuid-Sswdav-yqLM-dX1B-Iym0-2rB9-fDIC-ZaWlad" ], "labels": [], "masters": [ "dm-0", "dm-1" ], "uuids": [] }, "sectors": "103831552", "sectorsize": 512, "size": "49.51 GB", "start": "1026048", "uuid": null } }, "removable": "0", "rotational": "1", "sas_address": null, "sas_device_handle": null, "scheduler_mode": "deadline", "sectors": "104857600", "sectorsize": "512", "size": "50.00 GB", "support_discard": "0", "vendor": "VMware,", "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.2.1511", "ansible_dns": { "nameservers": [ "223.5.5.5" ], "search": [ "example.com" ] }, "ansible_domain": "localdomain", "ansible_effective_group_id": 0, "ansible_effective_user_id": 0, "ansible_env": { "HOME": "/root", "LANG": "en_US.UTF-8", "LESSOPEN": "||/usr/bin/lesspipe.sh %s", "LOGNAME": "root", "MAIL": "/var/mail/root", "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin", "PWD": "/root", "SHELL": "/bin/bash", "SHLVL": "2", "SSH_CLIENT": "172.16.1.5 37778 22", "SSH_CONNECTION": "172.16.1.5 37778 172.16.1.11 22", "SSH_TTY": "/dev/pts/1", "TERM": "linux", "USER": "root", "XDG_RUNTIME_DIR": "/run/user/0", "XDG_SESSION_ID": "21", "_": "/usr/bin/python" }, "ansible_eth0": { "active": true, "device": "eth0", "features": { "busy_poll": "off [fixed]", "fcoe_mtu": "off [fixed]", "generic_receive_offload": "on", "generic_segmentation_offload": "on", "highdma": "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_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_sit_segmentation": "off [fixed]", "tx_tcp6_segmentation": "off [fixed]", "tx_tcp_ecn_segmentation": "off [fixed]", "tx_tcp_segmentation": "on", "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": "10.0.0.11", "broadcast": "10.0.0.255", "netmask": "255.255.255.0", "network": "10.0.0.0" }, "ipv6": [ { "address": "fe80::20c:29ff:fe38:f727", "prefix": "64", "scope": "link" } ], "macaddress": "00:0c:29:38:f7:27", "module": "e1000", "mtu": 1500, "pciid": "0000:02:01.0", "promisc": false, "speed": 1000, "timestamping": [ "tx_software", "rx_software", "software" ], "type": "ether" }, "ansible_eth1": { "active": true, "device": "eth1", "features": { "busy_poll": "off [fixed]", "fcoe_mtu": "off [fixed]", "generic_receive_offload": "on", "generic_segmentation_offload": "on", "highdma": "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_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_sit_segmentation": "off [fixed]", "tx_tcp6_segmentation": "off [fixed]", "tx_tcp_ecn_segmentation": "off [fixed]", "tx_tcp_segmentation": "on", "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": "172.16.1.11", "broadcast": "172.16.1.255", "netmask": "255.255.255.0", "network": "172.16.1.0" }, "ipv6": [ { "address": "fe80::20c:29ff:fe38:f731", "prefix": "64", "scope": "link" } ], "macaddress": "00:0c:29:38:f7:31", "module": "e1000", "mtu": 1500, "pciid": "0000:02:02.0", "promisc": false, "speed": 1000, "timestamping": [ "tx_software", "rx_software", "software" ], "type": "ether" }, "ansible_fips": false, "ansible_form_factor": "Other", "ansible_fqdn": "localhost.localdomain", "ansible_hostname": "ansible2", "ansible_interfaces": [ "lo", "eth1", "eth0" ], "ansible_kernel": "3.10.0-327.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]", "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": "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": "on [fixed]", "tx_mpls_segmentation": "off [fixed]", "tx_nocache_copy": "off [fixed]", "tx_scatter_gather": "on [fixed]", "tx_scatter_gather_fraglist": "on [fixed]", "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]" }, "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": { "root": { "size_g": "47.46", "vg": "centos" }, "swap": { "size_g": "2.00", "vg": "centos" } }, "pvs": { "/dev/sda2": { "free_g": "0.04", "size_g": "49.51", "vg": "centos" } }, "vgs": { "centos": { "free_g": "0.04", "num_lvs": "2", "num_pvs": "1", "size_g": "49.51" } } }, "ansible_machine": "x86_64", "ansible_machine_id": "80d97b9393504f53b90042db024e84e1", "ansible_memfree_mb": 1362, "ansible_memory_mb": { "nocache": { "free": 1652, "used": 172 }, "real": { "free": 1362, "total": 1824, "used": 462 }, "swap": { "cached": 0, "free": 2047, "total": 2047, "used": 0 } }, "ansible_memtotal_mb": 1824, "ansible_mounts": [ { "block_available": 12068308, "block_size": 4096, "block_total": 12436549, "block_used": 368241, "device": "/dev/mapper/centos-root", "fstype": "xfs", "inode_available": 49715109, "inode_total": 49770496, "inode_used": 55387, "mount": "/", "options": "rw,relatime,attr2,inode64,noquota", "size_available": 49431789568, "size_total": 50940104704, "uuid": "599eb534-f348-449e-8d17-dae06ec4ad14" }, { "block_available": 95325, "block_size": 4096, "block_total": 127147, "block_used": 31822, "device": "/dev/sda1", "fstype": "xfs", "inode_available": 511670, "inode_total": 512000, "inode_used": 330, "mount": "/boot", "options": "rw,relatime,attr2,inode64,noquota", "size_available": 390451200, "size_total": 520794112, "uuid": "60dc75a8-7a29-4f0a-bd1c-c16113b880a5" } ], "ansible_nodename": "ansible2", "ansible_os_family": "RedHat", "ansible_pkg_mgr": "yum", "ansible_processor": [ "0", "GenuineIntel", "Intel(R) Core(TM) i7-4600U CPU @ 2.10GHz" ], "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 83 3a c3 f9 36 4a-2b 77 40 6e f8 38 f7 27", "ansible_product_uuid": "564D833A-C3F9-364A-2B77-406EF838F727", "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": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBDQn4yP9rxLxFNchOrAxYtuLo21oW04eXrmr6e3b/WeA79IW5HYMmmPECMUNktYgH+94WAu8wO25Ibc5e7VOVj0=", "ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIC+jDGgLrikn2BxnnVvLvvJuweiMpSwCRlTlnYR1SIgM", "ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDZlzbbdPDqKp34+uzzQVHElvbC79oBqCGLpPbTfT6zf9ZaOWPe8TAGdUMAsf/y58uTkAnaldPpWnTK6JXD/L0G0FgMjb5ZM9HfjmSVsV3yFybBWFltM6UVi1Gd+bqyav1CgcFX5peX6ob+GU9XU+tLvYUJsvSHS4dwI8DDovyuiCEQnxnjDqWW9mtplN0ecg6lFREDtoVGK7i8ahHVAjFkHr/yLGpDfbBub3um/jbKDYgm4qFdEzX7QG4TgmIRxsB5J6d0PGKgwu+rLETFsMewW9B1/mXEcQy2cXWcCgx3bYjVP8hLwtdBNfTOXBVjy5I+7PKwGnK8Ya+xPZ+BT6S9", "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": 26330, "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", "gather_subset": [ "all" ], "module_setup": true }, "changed": false }
做用:用於在各被管理節點運行指定的命令linux
區別:shell模塊能夠特殊字符(好比管道符"|"等),而command是不支持ios
顯示各個主機時間:nginx
ansible all -m command -a "date" 172.16.1.10 | SUCCESS | rc=0 >> Sat Apr 7 01:49:30 CST 2018 172.16.1.11 | SUCCESS | rc=0 >> Sat Apr 7 01:49:30 CST 2018
在各個主機建立目錄:git
ansible all -m command -a "mkdir /tmp/test" 172.16.1.10 | SUCCESS | rc=0 >> 172.16.1.11 | SUCCESS | rc=0 >>
刪除各個主機上的目錄:github
ansible all -m shell -a "rm -rf /tmp/test" 172.16.1.10 | SUCCESS | rc=0 >> 172.16.1.11 | SUCCESS | rc=0 >>
做用:管理用戶shell
name:指定用戶名 password:設定用戶密碼,password參數須要接受md5加密後的值 state:用戶狀態,默認爲present,其中present表示添加用戶,absent表示刪除用戶。 update_password:修改用戶密碼;always:新密碼和舊密碼不一樣時進行修改,on_create:爲新建立的用戶指定密碼 createhome:建立家目錄(yes/no) remove:刪除用戶是是否刪除用戶的家目錄(yes/no) system:新建用戶時指定是普通用戶仍是系統用戶,默認是普通用戶,yes時建立的是系統用戶
若是建立用戶的時候不指定任何參數,默認生成的選項有:apache
home:建立家目錄 shell:建立默認的shell爲/bin/bash system:默認建立爲普通用戶,而非系統用戶,指定是用yes
ansible-doc -s user - name: Manage user accounts user: append: # If `yes', will only add groups, not set them to just the list in `groups'. comment: # Optionally sets the description (aka `GECOS') of user account. createhome: # Unless set to `no', a home directory will be made for the user when the account is created or if the home directory does not exist. expires: # An expiry time for the user in epoch, it will be ignored on platforms that do not support this. Currently supported on Linux and FreeBSD. force: # When used with `state=absent', behavior is as with `userdel --force'. generate_ssh_key: # Whether to generate a SSH key for the user in question. This will *not* overwrite an existing SSH key. group: # Optionally sets the user's primary group (takes a group name). groups: # Puts the user in list of groups. When set to the empty string ('groups='), the user is removed from all groups except the primary group. Before version 2.3, the only input format allowed was a 'comma separated string', now it should be able to accept YAML lists also. home: # Optionally set the user's home directory. local: # Forces the use of "local" command alternatives on platforms that implement it. This is useful in environments that use centralized authentification when you want to manipulate the local users. I.E. it uses `luseradd` instead of `useradd`. This requires that these commands exist on the targeted host, otherwise it will be a fatal error. login_class: # Optionally sets the user's login class for FreeBSD, OpenBSD and NetBSD systems. move_home: # If set to `yes' when used with `home=', attempt to move the user's home directory to the specified directory if it isn't there already. name: # (required) Name of the user to create, remove or modify. non_unique: # Optionally when used with the -u option, this option allows to change the user ID to a non-unique value. password: # Optionally set the user's password to this crypted value. See the user example in the github examples directory for what this looks like in a playbook. See http://docs.ansible.com/ansible/faq.html#how-do-i-generate-crypted-passwords-for- the-user-module for details on various ways to generate these password values. Note on Darwin system, this value has to be cleartext. Beware of security issues. remove: # When used with `state=absent', behavior is as with `userdel --remove'. seuser: # Optionally sets the seuser type (user_u) on selinux enabled systems. shell: # Optionally set the user's shell. skeleton: # Optionally set a home skeleton directory. Requires createhome option! ssh_key_bits: # Optionally specify number of bits in SSH key to create. ssh_key_comment: # Optionally define the comment for the SSH key. ssh_key_file: # Optionally specify the SSH key filename. If this is a relative filename then it will be relative to the user's home directory. ssh_key_passphrase: # Set a passphrase for the SSH key. If no passphrase is provided, the SSH key will default to having no passphrase. ssh_key_type: # Optionally specify the type of SSH key to generate. Available SSH key types will depend on implementation present on target host. state: # Whether the account should exist or not, taking action if the state is different from what is stated. system: # When creating an account, setting this to `yes' makes the user a system account. This setting cannot be changed on existing users. uid: # Optionally sets the `UID' of the user. update_password: # `always' will update passwords if they differ. `on_create' will only set the password for newly created users.
ansible all -m user -a "name=staryjie password=Vu39hbnx" 172.16.1.11 | SUCCESS => { "changed": true, "comment": "", "createhome": true, "group": 1000, "home": "/home/staryjie", "name": "staryjie", "password": "NOT_LOGGING_PASSWORD", "shell": "/bin/bash", "state": "present", "system": false, "uid": 1000 } 172.16.1.10 | SUCCESS => { "changed": true, "comment": "", "createhome": true, "group": 1000, "home": "/home/staryjie", "name": "staryjie", "password": "NOT_LOGGING_PASSWORD", "shell": "/bin/bash", "state": "present", "system": false, "uid": 1000 }
ansible 172.16.1.10 -m user -a "name=staryjie remove=yes state=absent" 172.16.1.10 | SUCCESS => { "changed": true, "force": false, "name": "staryjie", "remove": true, "state": "absent" }
echo 654321 | openssl passwd -1 -stdin $1$UsYedBAd$wE0J9.4TloucJepB4rvlc0 ansible 172.16.1.11 -m user -a "name=staryjie update_password=always password=$1$UsYedBAd$wE0J9.4TloucJepB4rvlc0" 172.16.1.11 | SUCCESS => { "append": false, "changed": true, "comment": "", "group": 1000, "home": "/home/staryjie", "move_home": false, "name": "staryjie", "password": "NOT_LOGGING_PASSWORD", "shell": "/bin/bash", "state": "present", "uid": 1000 }
做用:對遠程文件管理
force:須要在兩種狀況下強制建立軟連接,一種是源文件不存在但以後會創建的狀況下;一種是目標軟連接已存在,須要先取消以前的軟連接,而後建立新的軟連接。(yes/no) group:定義文件/目錄的屬組 mode:定義文件/目錄的權限 owner:定義文件/目錄的屬主 path:必選項,定義文件/目錄的路徑 recurse:遞歸設置文件屬性,只對目錄有效 src:要被連接的源文件路徑,只應用於state=link的狀況 dest:要被連接到的路徑,只應用於state=link的狀況 state: directory,若是目錄不存在,建立目錄 file:即便文件不存在,也不會被建立 link:建立軟連接 hard:建立硬連接 touch:若是文件不存在,則會建立一個新的文件,若是文件或目錄已存在,則會更新其最後修改時間 absent:刪除文件、目錄或者取消連接文件
ansible 172.16.1.10 -m file -a "path=/tmp/test.txt state=touch" 172.16.1.10 | SUCCESS => { "changed": true, "dest": "/tmp/test.txt", "gid": 0, "group": "root", "mode": "0644", "owner": "root", "size": 0, "state": "file", "uid": 0 }
檢查是否已經建立
ansible 172.16.1.10 -a "ls -l /tmp" 172.16.1.10 | SUCCESS | rc=0 >> total 0 drwx------ 2 root root 80 Apr 7 09:42 ansible_xKLD9L drwx------ 3 root root 60 Apr 7 02:32 systemd-private-1252e0d7a6c24ac6a4d16a3d41e86d91-chronyd.service-zEDo4U -rw-r--r-- 1 root root 0 Apr 7 09:42 test.txt
ansible 172.16.1.10 -m file -a "path=/tmp/directory state=directory" 172.16.1.10 | SUCCESS => { "changed": true, "gid": 0, "group": "root", "mode": "0755", "owner": "root", "path": "/tmp/directory", "size": 40, "state": "directory", "uid": 0 }
檢查是否已經建立
ansible 172.16.1.10 -m file -a "path=/tmp/directory state=directory" 172.16.1.10 | SUCCESS => { "changed": true, "gid": 0, "group": "root", "mode": "0755", "owner": "root", "path": "/tmp/directory", "size": 40, "state": "directory", "uid": 0 }
ansible 172.16.1.10 -m file -a "path=/tmp/test.txt state=absent" 172.16.1.10 | SUCCESS => { "changed": true, "path": "/tmp/test.txt", "state": "absent" }
檢查是否已經刪除
ansible 172.16.1.10 -a "ls -l /tmp" 172.16.1.10 | SUCCESS | rc=0 >> total 0 drwx------ 2 root root 80 Apr 7 09:47 ansible_sIY_9c drwxr-xr-x 2 root root 40 Apr 7 09:45 directory drwx------ 3 root root 60 Apr 7 02:32 systemd-private-1252e0d7a6c24ac6a4d16a3d41e86d91-chronyd.service-zEDo4U
ansible 172.16.1.10 -m file -a "src=/etc/fstab dest=/tmp/fstab state=link" 172.16.1.10 | SUCCESS => { "changed": true, "dest": "/tmp/fstab", "gid": 0, "group": "root", "mode": "0777", "owner": "root", "size": 10, "src": "/etc/fstab", "state": "link", "uid": 0 }
檢查是否已經建立
ansible 172.16.1.10 -a "ls -l /tmp" 172.16.1.10 | SUCCESS | rc=0 >> total 0 drwx------ 2 root root 80 Apr 7 09:49 ansible_65KboK drwxr-xr-x 2 root root 40 Apr 7 09:45 directory lrwxrwxrwx 1 root root 10 Apr 7 09:49 fstab -> /etc/fstab drwx------ 3 root root 60 Apr 7 02:32 systemd-private-1252e0d7a6c24ac6a4d16a3d41e86d91-chronyd.service-zEDo4U
ansible 172.16.1.10 -m file -a "path=/tmp/fstab state=absent" 172.16.1.10 | SUCCESS => { "changed": true, "path": "/tmp/fstab", "state": "absent" }
檢查是否已經刪除
ansible 172.16.1.10 -a "ls -l /tmp" 172.16.1.10 | SUCCESS | rc=0 >> total 0 drwx------ 2 root root 80 Apr 7 09:53 ansible_yBdz9A drwxr-xr-x 2 root root 40 Apr 7 09:45 directory drwx------ 3 root root 60 Apr 7 02:32 systemd-private-1252e0d7a6c24ac6a4d16a3d41e86d91-chronyd.service-zEDo4U
做用:複製文件到遠程主機
backup:在覆蓋以前將原文件備份(若是兩個文件內容徹底同樣,那麼不復制),備份文件包含時間信息。(yes/no) content:用於替代「src」,能夠直接設定指定文件的值 dest:必選項。要將源文件複製到遠程主機的絕對路徑,若是源文件是一個目錄,那麼該路徑也必須是個目錄 directory_mode:遞歸的設定目錄權限,默認爲系統默認權限 force:若是目標主機包含該文件,但內容不一樣,若是設置yes,則強制覆蓋,若是爲no,則只當目標主機的目標位置不存在該文件時才複製。默認yes others:全部的file模塊裏的選項均可以在這裏使用 src:要複製到遠程主機的文件在本地的地址,能夠是絕對路徑,也能夠是相對路徑。若是路徑是一個目錄,它將遞歸複製。這種狀況下,若是路徑使用"/"結尾,則只複製目錄裏面的內容,若是沒有"/",則包含目錄在內的整個內容所有複製,相似於rsync validate:驗證命令在複製到位以前運行。 要驗證的文件的路徑是經過'%s'傳入的,必須像下面的例子那樣存在。 該命令安全地傳遞,所以shell功能(如擴展和管道)將不起做用。
ansible 172.16.1.10 -m copy -a "src=/data/source/test.txt dest=/data/source/test.txt backup=yes" 172.16.1.10 | SUCCESS => { "backup_file": "/data/source/test.txt.20516.2018-04-07@10:10:03~", "changed": true, "checksum": "16e94334e2d805206d441a0f3a17881d4a6cac37", "dest": "/data/source/test.txt", "gid": 0, "group": "root", "md5sum": "262a588f694f4061a8fd146f7c6fa7b1", "mode": "0644", "owner": "root", "size": 60, "src": "/root/.ansible/tmp/ansible-tmp-1523067003.01-155573397925916/source", "state": "file", "uid": 0 }
檢查是否拷貝且備份
ansible 172.16.1.10 -a "ls -l /data/source" 172.16.1.10 | SUCCESS | rc=0 >> total 4 -rw-r--r-- 1 root root 60 Apr 7 10:10 test.txt -rw-r--r-- 1 root root 0 Apr 7 10:05 test.txt.20516.2018-04-07@10:10:03~
ansible 172.16.1.10 -m copy -a "src=/etc/passwd dest=/tmp/passwd owner=root group=root mode=644" 172.16.1.10 | SUCCESS => { "changed": true, "checksum": "6f46b572f89fe704a5ed1cd9f7b33d5996974477", "dest": "/tmp/passwd", "gid": 0, "group": "root", "md5sum": "b02b6e4546f22496fa3bddf6691995a3", "mode": "0644", "owner": "root", "size": 1161, "src": "/root/.ansible/tmp/ansible-tmp-1523067285.86-265073633091003/source", "state": "file", "uid": 0 }
檢查文件是否複製,權限是否正確
ansible 172.16.1.10 -a "ls -l /tmp/passwd" 172.16.1.10 | SUCCESS | rc=0 >> -rw-r--r-- 1 root root 1161 Apr 7 10:14 /tmp/passwd
ansible 172.16.1.10 -m copy -a "src=/etc/sudoers dest=/etc/sudoers validate='visudo -cf %s'" 172.16.1.10 | SUCCESS => { "changed": false, "checksum": "d36e30f4796b61a566e7b2becc10fc329810af95", "gid": 0, "group": "root", "mode": "0440", "owner": "root", "path": "/etc/sudoers", "size": 4188, "state": "file", "uid": 0 }
做用:解壓遠程或者本地的壓縮包
copy:在解壓文件以前,是否先將文件複製到遠程主機,默認爲yes。若爲no,則要求目標主機上壓縮包必須存在。 creates:指定一個文件名,當該文件存在時,則解壓指令不執行。 dest:遠程主機上的一個路徑,即文件解壓的路徑。 grop:解壓後的目錄或文件的屬組。 list_files:若是爲yes,則會列出壓縮包裏的文件,默認爲no,2.0版本新增的選項。 mode:解決後文件的權限。 src:若是copy爲yes,則須要指定壓縮文件的源路徑。 owner:解壓後文件或目錄的屬主。
ansible 172.16.101.50 -m unarchive -a "src=/etc/ansible/playbook/yongxindai/data/yongxindai.tar.gz dest=/application/ copy=yes" 172.16.101.50 | SUCCESS => { "changed": true, "dest": "/application/", "extract_results": { "cmd": [ "/usr/bin/gtar", "--extract", "-C", "/application/", "-z", "-f", "/root/.ansible/tmp/ansible-tmp-1525920029.48-166566029730285/source" ], "err": "", "out": "", "rc": 0 }, "gid": 0, "group": "root", "handler": "TgzArchive", "mode": "0755", "owner": "root", "size": 4096, "src": "/root/.ansible/tmp/ansible-tmp-1525920029.48-166566029730285/source", "state": "directory", "uid": 0 }
做用:管理服務
arguments:給命令行提供一些選項 enabled:是否開機自啓(yes/no) name:必選項,服務名稱 pattern:定義一個模式,若是經過status指令來查看服務狀態時沒有響應,就會經過ps指令在進程中根據該模式進行檢查,若是匹配到則認爲該服務仍在運行 runlevel:運行級別設置 sleep:若是執行了restart,則在stop和start之間睡眠幾秒鐘 state:對當前指定服務執行啓動、中止和重啓等操做(started、stoped、restarted、reloaded)
ansible nginx -m service -a "name=nginx enabled=yes state=started" 172.16.1.10 | SUCCESS => { "changed": true, "enabled": true, "name": "nginx", "state": "started", "status": { "ActiveEnterTimestampMonotonic": "0", "ActiveExitTimestampMonotonic": "0", "ActiveState": "inactive", "After": "system.slice tmp.mount -.mount remote-fs.target network.target nss-lookup.target systemd-journald.socket basic.target", "AllowIsolate": "no", "AssertResult": "no", "AssertTimestampMonotonic": "0", "Before": "shutdown.target", "BlockIOAccounting": "no", "BlockIOWeight": "18446744073709551615", "CPUAccounting": "no", "CPUQuotaPerSecUSec": "infinity", "CPUSchedulingPolicy": "0", "CPUSchedulingPriority": "0", "CPUSchedulingResetOnFork": "no", "CPUShares": "18446744073709551615", "CanIsolate": "no", "CanReload": "yes", "CanStart": "yes", "CanStop": "yes", "CapabilityBoundingSet": "18446744073709551615", "ConditionResult": "no", "ConditionTimestampMonotonic": "0", "Conflicts": "shutdown.target", "ControlPID": "0", "DefaultDependencies": "yes", "Delegate": "no", "Description": "The nginx HTTP and reverse proxy server", "DevicePolicy": "auto", "ExecMainCode": "0", "ExecMainExitTimestampMonotonic": "0", "ExecMainPID": "0", "ExecMainStartTimestampMonotonic": "0", "ExecMainStatus": "0", "ExecReload": "{ path=/bin/kill ; argv[]=/bin/kill -s HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", "ExecStart": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", "ExecStartPre": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -t ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", "FailureAction": "none", "FileDescriptorStoreMax": "0", "FragmentPath": "/usr/lib/systemd/system/nginx.service", "GuessMainPID": "yes", "IOScheduling": "0", "Id": "nginx.service", "IgnoreOnIsolate": "no", "IgnoreOnSnapshot": "no", "IgnoreSIGPIPE": "yes", "InactiveEnterTimestampMonotonic": "0", "InactiveExitTimestampMonotonic": "0", "JobTimeoutAction": "none", "JobTimeoutUSec": "0", "KillMode": "process", "KillSignal": "3", "LimitAS": "18446744073709551615", "LimitCORE": "18446744073709551615", "LimitCPU": "18446744073709551615", "LimitDATA": "18446744073709551615", "LimitFSIZE": "18446744073709551615", "LimitLOCKS": "18446744073709551615", "LimitMEMLOCK": "65536", "LimitMSGQUEUE": "819200", "LimitNICE": "0", "LimitNOFILE": "4096", "LimitNPROC": "7217", "LimitRSS": "18446744073709551615", "LimitRTPRIO": "0", "LimitRTTIME": "18446744073709551615", "LimitSIGPENDING": "7217", "LimitSTACK": "18446744073709551615", "LoadState": "loaded", "MainPID": "0", "MemoryAccounting": "no", "MemoryCurrent": "18446744073709551615", "MemoryLimit": "18446744073709551615", "MountFlags": "0", "Names": "nginx.service", "NeedDaemonReload": "no", "Nice": "0", "NoNewPrivileges": "no", "NonBlocking": "no", "NotifyAccess": "none", "OOMScoreAdjust": "0", "OnFailureJobMode": "replace", "PIDFile": "/run/nginx.pid", "PermissionsStartOnly": "no", "PrivateDevices": "no", "PrivateNetwork": "no", "PrivateTmp": "yes", "ProtectHome": "no", "ProtectSystem": "no", "RefuseManualStart": "no", "RefuseManualStop": "no", "RemainAfterExit": "no", "Requires": "tmp.mount -.mount basic.target", "RequiresMountsFor": "/tmp /var/tmp", "Restart": "no", "RestartUSec": "100ms", "Result": "success", "RootDirectoryStartOnly": "no", "RuntimeDirectoryMode": "0755", "SameProcessGroup": "no", "SecureBits": "0", "SendSIGHUP": "no", "SendSIGKILL": "yes", "Slice": "system.slice", "StandardError": "inherit", "StandardInput": "null", "StandardOutput": "journal", "StartLimitAction": "none", "StartLimitBurst": "5", "StartLimitInterval": "10000000", "StartupBlockIOWeight": "18446744073709551615", "StartupCPUShares": "18446744073709551615", "StatusErrno": "0", "StopWhenUnneeded": "no", "SubState": "dead", "SyslogLevelPrefix": "yes", "SyslogPriority": "30", "SystemCallErrorNumber": "0", "TTYReset": "no", "TTYVHangup": "no", "TTYVTDisallocate": "no", "TimeoutStartUSec": "1min 30s", "TimeoutStopUSec": "5s", "TimerSlackNSec": "50000", "Transient": "no", "Type": "forking", "UMask": "0022", "UnitFilePreset": "disabled", "UnitFileState": "disabled", "Wants": "system.slice", "WatchdogTimestampMonotonic": "0", "WatchdogUSec": "0" } }
檢查遠程主機是否已經啓動Nginx
ansible nginx -m shell -a "netstat -lnutp|grep nginx" 172.16.1.10 | SUCCESS | rc=0 >> tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 20991/nginx: master tcp6 0 0 :::80 :::* LISTEN 20991/nginx: master ansible nginx -m shell -a "systemctl status nginx" 172.16.1.10 | SUCCESS | rc=0 >> ● nginx.service - The nginx HTTP and reverse proxy server Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled) Active: active (running) since Sat 2018-04-07 10:34:11 CST; 2min 51s ago Process: 20988 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS) Process: 20985 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS) Process: 20983 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS) Main PID: 20991 (nginx) CGroup: /system.slice/nginx.service ├─20991 nginx: master process /usr/sbin/ngin └─20992 nginx: worker proces Apr 07 10:34:11 ansible1 systemd[1]: Starting The nginx HTTP and reverse proxy server... Apr 07 10:34:11 ansible1 nginx[20985]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok Apr 07 10:34:11 ansible1 nginx[20985]: nginx: configuration file /etc/nginx/nginx.conf test is successful Apr 07 10:34:11 ansible1 systemd[1]: Failed to read PID from file /run/nginx.pid: Invalid argument Apr 07 10:34:11 ansible1 systemd[1]: Started The nginx HTTP and reverse proxy server.
ansible nginx -m service -a "name=nginx state=stopped"
特別注意:關於state的選項,不是命令行使用的start、stop、restart,而是started、stopped、restarted、reloaded
ansible nginx -m service -a "name=nginx state=restarted sleep=10" [WARNING]: Ignoring "sleep" as it is not used in "systemd" 172.16.1.10 | SUCCESS => { "changed": true, "name": "nginx", "state": "started", "status": { "ActiveEnterTimestamp": "Sat 2018-04-07 10:40:35 CST", "ActiveEnterTimestampMonotonic": "58941914461", "ActiveExitTimestamp": "Sat 2018-04-07 10:38:11 CST", "ActiveExitTimestampMonotonic": "58797789339", "ActiveState": "active", "After": "network.target remote-fs.target -.mount basic.target system.slice tmp.mount systemd-journald.socket nss-lookup.target", "AllowIsolate": "no", "AssertResult": "yes", "AssertTimestamp": "Sat 2018-04-07 10:40:35 CST", "AssertTimestampMonotonic": "58941853769", "Before": "multi-user.target shutdown.target", "BlockIOAccounting": "no", "BlockIOWeight": "18446744073709551615", "CPUAccounting": "no", "CPUQuotaPerSecUSec": "infinity", "CPUSchedulingPolicy": "0", "CPUSchedulingPriority": "0", "CPUSchedulingResetOnFork": "no", "CPUShares": "18446744073709551615", "CanIsolate": "no", "CanReload": "yes", "CanStart": "yes", "CanStop": "yes", "CapabilityBoundingSet": "18446744073709551615", "ConditionResult": "yes", "ConditionTimestamp": "Sat 2018-04-07 10:40:35 CST", "ConditionTimestampMonotonic": "58941853769", "Conflicts": "shutdown.target", "ControlGroup": "/system.slice/nginx.service", "ControlPID": "0", "DefaultDependencies": "yes", "Delegate": "no", "Description": "The nginx HTTP and reverse proxy server", "DevicePolicy": "auto", "ExecMainCode": "0", "ExecMainExitTimestampMonotonic": "0", "ExecMainPID": "21454", "ExecMainStartTimestamp": "Sat 2018-04-07 10:40:35 CST", "ExecMainStartTimestampMonotonic": "58941914400", "ExecMainStatus": "0", "ExecReload": "{ path=/bin/kill ; argv[]=/bin/kill -s HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", "ExecStart": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx ; ignore_errors=no ; start_time=[Sat 2018-04-07 10:40:35 CST] ; stop_time=[Sat 2018-04-07 10:40:35 CST] ; pid=21451 ; code=exited ; status=0 }", "ExecStartPre": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -t ; ignore_errors=no ; start_time=[Sat 2018-04-07 10:40:35 CST] ; stop_time=[Sat 2018-04-07 10:40:35 CST] ; pid=21447 ; code=exited ; status=0 }", "FailureAction": "none", "FileDescriptorStoreMax": "0", "FragmentPath": "/usr/lib/systemd/system/nginx.service", "GuessMainPID": "yes", "IOScheduling": "0", "Id": "nginx.service", "IgnoreOnIsolate": "no", "IgnoreOnSnapshot": "no", "IgnoreSIGPIPE": "yes", "InactiveEnterTimestamp": "Sat 2018-04-07 10:38:11 CST", "InactiveEnterTimestampMonotonic": "58797796873", "InactiveExitTimestamp": "Sat 2018-04-07 10:40:35 CST", "InactiveExitTimestampMonotonic": "58941854284", "JobTimeoutAction": "none", "JobTimeoutUSec": "0", "KillMode": "process", "KillSignal": "3", "LimitAS": "18446744073709551615", "LimitCORE": "18446744073709551615", "LimitCPU": "18446744073709551615", "LimitDATA": "18446744073709551615", "LimitFSIZE": "18446744073709551615", "LimitLOCKS": "18446744073709551615", "LimitMEMLOCK": "65536", "LimitMSGQUEUE": "819200", "LimitNICE": "0", "LimitNOFILE": "4096", "LimitNPROC": "7217", "LimitRSS": "18446744073709551615", "LimitRTPRIO": "0", "LimitRTTIME": "18446744073709551615", "LimitSIGPENDING": "7217", "LimitSTACK": "18446744073709551615", "LoadState": "loaded", "MainPID": "21454", "MemoryAccounting": "no", "MemoryCurrent": "18446744073709551615", "MemoryLimit": "18446744073709551615", "MountFlags": "0", "Names": "nginx.service", "NeedDaemonReload": "no", "Nice": "0", "NoNewPrivileges": "no", "NonBlocking": "no", "NotifyAccess": "none", "OOMScoreAdjust": "0", "OnFailureJobMode": "replace", "PIDFile": "/run/nginx.pid", "PermissionsStartOnly": "no", "PrivateDevices": "no", "PrivateNetwork": "no", "PrivateTmp": "yes", "ProtectHome": "no", "ProtectSystem": "no", "RefuseManualStart": "no", "RefuseManualStop": "no", "RemainAfterExit": "no", "Requires": "-.mount tmp.mount basic.target", "RequiresMountsFor": "/tmp /var/tmp", "Restart": "no", "RestartUSec": "100ms", "Result": "success", "RootDirectoryStartOnly": "no", "RuntimeDirectoryMode": "0755", "SameProcessGroup": "no", "SecureBits": "0", "SendSIGHUP": "no", "SendSIGKILL": "yes", "Slice": "system.slice", "StandardError": "inherit", "StandardInput": "null", "StandardOutput": "journal", "StartLimitAction": "none", "StartLimitBurst": "5", "StartLimitInterval": "10000000", "StartupBlockIOWeight": "18446744073709551615", "StartupCPUShares": "18446744073709551615", "StatusErrno": "0", "StopWhenUnneeded": "no", "SubState": "running", "SyslogLevelPrefix": "yes", "SyslogPriority": "30", "SystemCallErrorNumber": "0", "TTYReset": "no", "TTYVHangup": "no", "TTYVTDisallocate": "no", "TimeoutStartUSec": "1min 30s", "TimeoutStopUSec": "5s", "TimerSlackNSec": "50000", "Transient": "no", "Type": "forking", "UMask": "0022", "UnitFilePreset": "disabled", "UnitFileState": "enabled", "WantedBy": "multi-user.target", "Wants": "system.slice", "WatchdogTimestampMonotonic": "0", "WatchdogUSec": "0" } }
如上可知,在CentOS 7系統中是採用systemctl來管理服務的,systemctl不支持sleep參數。
做用:管理crond計劃任務
backup:對遠程主機上的原計劃任務作出修改以前備份,若是修改先後是同樣的就不作修改 cron_file:若是指定該選項,則用該文件替換遠程主機上的cron.d目錄下的用戶任務計劃 day:日(1-31,,/2,....) hour:小時(0-23,,/2,....) minute:分鐘(0-59,,/2,....) month:月(1-12,,/2,....) weekday:周(1-7,*,....) job:要執行的任務,依賴於state=present name:該任務的描述 special_time:指定何時執行,參數:reboot,yearly,annually,monthly,weekly,daily,hourly state:確認該計劃是建立仍是刪除(present/absent) user:以哪一個用戶的身份執行,默認root
*/1 * * * * /bin/echo "hello world" 分 時 日 月 周
ansible nginx -m cron -a 'name="running a job" job="/data/source/job.sh" minute=*/1' 172.16.1.10 | SUCCESS => { "changed": true, "envs": [], "jobs": [ "running a job" ] }
檢查是否添加
ansible nginx -a 'crontab -l' 172.16.1.10 | SUCCESS | rc=0 >> #Ansible: running a job */1 * * * * /data/source/job.sh
ansible nginx -m cron -a 'name="when system reboot" job="/data/source/job.sh" special_time=reboot' 172.16.1.10 | SUCCESS => { "changed": true, "envs": [], "jobs": [ "running a job", "when system reboot" ] }
檢查
ansible nginx -a 'crontab -l' 172.16.1.10 | SUCCESS | rc=0 >> #Ansible: running a job */1 * * * * /data/source/job.sh #Ansible: when system reboot @reboot /data/source/job.sh
ansible nginx -m cron -a 'name="test crond" job="cat /etc/passwd >/tmp/test.log" cron_file="test_cron_ansible" minute=0 hour=12 user=root' 172.16.1.10 | SUCCESS => { "changed": true, "cron_file": "test_cron_ansible", "envs": [], "jobs": [ "test crond" ] }
檢查:
ansible nginx -a "ls -l /etc/cron.d" 172.16.1.10 | SUCCESS | rc=0 >> total 8 -rw-r--r--. 1 root root 128 Jul 27 2015 0hourly -rw-r--r-- 1 root root 68 Apr 7 11:05 test_cron_ansible
查看test_cron_ansible文件內容
ansible nginx -a "cat /etc/cron.d/test_cron_ansible" 172.16.1.10 | SUCCESS | rc=0 >> #Ansible: test crond 0 12 * * * root cat /etc/passwd >/tmp/test.log
ansible nginx -m cron -a 'name="when system reboot" state=absent' 172.16.1.10 | SUCCESS => { "changed": true, "envs": [], "jobs": [ "running a job" ] }
檢查
ansible nginx -a "crontab -l" 172.16.1.10 | SUCCESS | rc=0 >> #Ansible: running a job */1 * * * * /data/source/job.sh
ansible nginx -m cron -a 'name="test crond" cron_file="test_cron_ansible" state=absent' 172.16.1.10 | SUCCESS => { "changed": true, "cron_file": "test_cron_ansible", "envs": [], "jobs": [] }
檢查
ansible nginx -a "cat /etc/cron.d/test_cron_ansible" 172.16.1.10 | SUCCESS | rc=0 >>
做用:經過yum包管理器管理軟件包
config-fie:yum的配置文件 disable_gpg_check:關閉gpg_check disablerepo:不啓用某個源 enablerepo:啓用某個源 name:要進行操做的軟件包的名字,也能夠傳遞一個url或者一個本地rpm包的路徑 state:狀態(present、absent、latest)
ansible nginx -m yum -a 'name="httpd" state=latest' 172.16.1.10 | SUCCESS => { "changed": true, "msg": "", "rc": 0, "results": [ "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-67.el7.centos.6 will be installed\n--> Processing Dependency: httpd-tools = 2.4.6-67.el7.centos.6 for package: httpd-2.4.6-67.el7.centos.6.x86_64\n--> Processing Dependency: /etc/mime.types for package: httpd-2.4.6-67.el7.centos.6.x86_64\n--> Running transaction check\n---> Package httpd-tools.x86_64 0:2.4.6-67.el7.centos.6 will be installed\n---> Package mailcap.noarch 0:2.1.41-2.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n httpd x86_64 2.4.6-67.el7.centos.6 updates 2.7 M\nInstalling for dependencies:\n httpd-tools x86_64 2.4.6-67.el7.centos.6 updates 88 k\n mailcap noarch 2.1.41-2.el7 base 31 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package (+2 Dependent packages)\n\nTotal download size: 2.8 M\nInstalled size: 9.6 M\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal 2.0 MB/s | 2.8 MB 00:01 \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : httpd-tools-2.4.6-67.el7.centos.6.x86_64 1/3 \n Installing : mailcap-2.1.41-2.el7.noarch 2/3 \n Installing : httpd-2.4.6-67.el7.centos.6.x86_64 3/3 \n Verifying : mailcap-2.1.41-2.el7.noarch 1/3 \n Verifying : httpd-2.4.6-67.el7.centos.6.x86_64 2/3 \n Verifying : httpd-tools-2.4.6-67.el7.centos.6.x86_64 3/3 \n\nInstalled:\n httpd.x86_64 0:2.4.6-67.el7.centos.6 \n\nDependency Installed:\n httpd-tools.x86_64 0:2.4.6-67.el7.centos.6 mailcap.noarch 0:2.1.41-2.el7 \n\nComplete!\n" ] }
檢查
ansible nginx -a 'systemctl status httpd.service' 172.16.1.10 | FAILED | rc=3 >> ● httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled) Active: inactive (dead) Docs: man:httpd(8) man:apachectl(8)non-zero return code
ansible nginx -m yum -a 'name=httpd state=absent' 172.16.1.10 | SUCCESS => { "changed": true, "msg": "", "rc": 0, "results": [ "Loaded plugins: fastestmirror\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-67.el7.centos.6 will be erased\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nRemoving:\n httpd x86_64 2.4.6-67.el7.centos.6 @updates 9.4 M\n\nTransaction Summary\n================================================================================\nRemove 1 Package\n\nInstalled size: 9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Erasing : httpd-2.4.6-67.el7.centos.6.x86_64 1/1 \n Verifying : httpd-2.4.6-67.el7.centos.6.x86_64 1/1 \n\nRemoved:\n httpd.x86_64 0:2.4.6-67.el7.centos.6 \n\nComplete!\n" ] }
檢查
ansible nginx -a 'systemctl status httpd.service' 172.16.1.10 | FAILED | rc=3 >> ● httpd.service Loaded: not-found (Reason: No such file or directory) Active: inactive (dead) Apr 07 11:21:13 ansible1 systemd[1]: Stopped The Apache HTTP Server.non-zero return code
做用:從http、ftp、https服務器上下載軟件(相似於wget)
sha256sum:下載完成後進行sha256sum檢查 timeout:設置下載超時時間,默認10s url:下載軟件的url url_password、url_username:用於須要用戶名密碼驗證的狀況 use_proxy:使用代理下載,須要事先在環境變量中定義
ansible nginx -m get_url -a 'url="http://pcdl.itools.cn/itools4/itoolssetup_4.3.4.2.exe" dest=/data/source/itoolssetup.exe mode=0755 timeout=20' 172.16.1.10 | SUCCESS => { "changed": true, "checksum_dest": null, "checksum_src": "1a405e90a7729f14173e74397c7dfc2cb1affe29", "dest": "/data/source/itoolssetup.exe", "gid": 0, "group": "root", "md5sum": "2fb4fbd952435c2fe00c8b1b3e856558", "mode": "0755", "msg": "OK (36594288 bytes)", "owner": "root", "size": 36594288, "src": "/tmp/tmpnqaqrb", "state": "file", "status_code": 200, "uid": 0, "url": "http://pcdl.itools.cn/itools4/itoolssetup_4.3.4.2.exe" }
檢查:
ansible nginx -m shell -a 'ls -l /data/source|grep itools*' 172.16.1.10 | SUCCESS | rc=0 >> -rwxr-xr-x 1 root root 36594288 Apr 7 11:28 itoolssetup.exe
做用:文件編輯,經過修改匹配到的內容,或者新增、刪除內容
path:指定要修改的配置文件的絕對路徑 regexp:匹配要修改的內容 line:要增長或者修改的內容 state: absent:表示刪除,當匹配到時進行刪除 present:表示增長,當匹配到時進行修改,當沒有匹配到時在最後增長一行,默認爲此項 backrefs: no:表示若是沒有匹配到,則增長line;若是匹配成功,則替換line; yes:表示若是沒有匹配到,則不變line;若是匹配成功,則替換line; backup: no:表示若是沒有匹配到,則增長line;若是匹配成功,則替換line;不備份原文件 yes:表示若是沒有匹配到,則增長line;若是匹配成功,則替換line;備份原文件 insertafter:匹配到這一行,在這行後面添加一行 insertbefore:匹配到這一行,在這行前面添加一行
ansible nginx -m lineinfile -a 'path="/etc/nginx/nginx.conf" regexp="listen 80 default_server;" line="listen 8080 default_server;" backup=yes backrefs=yes' 172.16.1.10 | SUCCESS => { "backup": "/etc/nginx/nginx.conf.22878.2018-04-07@11:41:14~", "changed": true, "msg": "line replaced" }
檢查
ansible nginx -m shell -a "cat /etc/nginx/nginx.conf|grep 8080" 172.16.1.10 | SUCCESS | rc=0 >> listen 8080 default_server;
注:經測試,當不添加backerfs: yes參數時,匹配到後也會進行替換,但當匹配到的內容不存在時,會在最後增長一行;因此當不增長backerfs參數時,要肯定匹配到的內容存在;