Ansible常用模块
1、ping
作用:测试目标主机是否在线,如果在线则返回pong。
ansible 172.16.1.10 -m ping
172.16.1.10 | SUCCESS => {
"changed": false,
"ping": "pong"
}
2、setup
作用:收集远程主机的信息
收集可用的facts,收集每个节点的相关信息:架构信息,IP,时间,域名,网卡,MAC,主机名,CPU等信息。这些收集的信息,可以作为变量。
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
}
3、command模块和shell模块
作用:用于在各被管理节点运行指定的命令
区别:shell模块可以特殊字符(比如管道符"|"等),而command是不支持
显示各个主机时间:
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
在各个主机创建目录:
ansible all -m command -a "mkdir /tmp/test"
172.16.1.10 | SUCCESS | rc=0 >>
172.16.1.11 | SUCCESS | rc=0 >>
删除各个主机上的目录:
ansible all -m shell -a "rm -rf /tmp/test"
172.16.1.10 | SUCCESS | rc=0 >>
172.16.1.11 | SUCCESS | rc=0 >>
4、user
作用:管理用户
user模块参数说明:
name:指定用户名
password:设定用户密码,password参数需要接受md5加密后的值
state:用户状态,默认为present,其中present表示添加用户,absent表示删除用户。
update_password:修改用户密码;always:新密码和旧密码不同时进行修改,on_create:为新创建的用户指定密码
createhome:创建家目录(yes/no)
remove:删除用户是是否删除用户的家目录(yes/no)
system:新建用户时指定是普通用户还是系统用户,默认是普通用户,yes时创建的是系统用户
如果创建用户的时候不指定任何参数,默认生成的选项有:
home:创建家目录
shell:创建默认的shell为/bin/bash
system:默认创建为普通用户,而非系统用户,指定是用yes
user模块帮助说明
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
}
5、file
作用:对远程文件管理
file模块参数说明
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
6、copy
作用:复制文件到远程主机
copy模块参数说明
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
validate检查
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
}
7、unarchive
作用:解压远程或者本地的压缩包
unarchive模块参数说明
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
}
8、service
作用:管理服务
service模块参数说明
arguments:给命令行提供一些选项
enabled:是否开机自启(yes/no)
name:必选项,服务名称
pattern:定义一个模式,如果通过status指令来查看服务状态时没有响应,就会通过ps指令在进程中根据该模式进行检查,如果匹配到则认为该服务仍在运行
runlevel:运行级别设置
sleep:如果执行了restart,则在stop和start之间睡眠几秒钟
state:对当前指定服务执行启动、停止和重启等操作(started、stoped、restarted、reloaded)
Ansible操作远程主机Nginx服务
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.
关闭Nginx
ansible nginx -m service -a "name=nginx state=stopped"
特别注意:关于state的选项,不是命令行使用的start、stop、restart,而是started、stopped、restarted、reloaded
重启Nginx并设置休眠时间10秒
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参数。
9、cron计划任务
作用:管理crond计划任务
cron模块参数说明
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
crontab任务格式
*/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
添加一个special_time的定时任务
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
将定时任务放到指定用户的con.d目录下
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
删除cron.d下面的定时任务(不能删除该文件,但是会清空该文件里面的内容)
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 >>
10、yum模块
作用:通过yum包管理器管理软件包
yum模块参数说明
config-fie:yum的配置文件
disable_gpg_check:关闭gpg_check
disablerepo:不启用某个源
enablerepo:启用某个源
name:要进行操作的软件包的名字,也可以传递一个url或者一个本地rpm包的路径
state:状态(present、absent、latest)
通过yum模块安装最新版的httpd
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
卸载httpd
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
11、get_url模块
作用:从http、ftp、https服务器上下载软件(类似于wget)
get_url模块参数说明
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
12、lineinfile模块
作用:文件编辑,通过修改匹配到的内容,或者新增、删除内容
lineinfile参数说明
path:指定要修改的配置文件的绝对路径
regexp:匹配要修改的内容
line:要增加或者修改的内容
state:
absent:表示删除,当匹配到时进行删除
present:表示增加,当匹配到时进行修改,当没有匹配到时在最后增加一行,默认为此项
backrefs:
no:表示如果没有匹配到,则增加line;如果匹配成功,则替换line;
yes:表示如果没有匹配到,则不变line;如果匹配成功,则替换line;
backup:
no:表示如果没有匹配到,则增加line;如果匹配成功,则替换line;不备份原文件
yes:表示如果没有匹配到,则增加line;如果匹配成功,则替换line;备份原文件
insertafter:匹配到这一行,在这行后面添加一行
insertbefore:匹配到这一行,在这行前面添加一行
修改Nginx的配置文件
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参数时,要确定匹配到的内容存在;