分享

自动化运维工具ansible02

 小世界的野孩子 2022-11-29 发布于北京

02·自动化运维工具Ansible ad-hoc

MarkdownHTML

02·自动化运维工具-Ansible ad-hoc

  • 02·自动化运维工具-Ansible ad-hoc

    • [Ansible ad-hoc](file:///F:/老男孩视频/ansible/ansible/02·自动化运维工具Ansible-ad-hoc.html#title-1)

    • [Ansible命令模块](file:///F:/老男孩视频/ansible/ansible/02·自动化运维工具Ansible-ad-hoc.html#title-2)

    • [Ansible软件管理模块](file:///F:/老男孩视频/ansible/ansible/02·自动化运维工具Ansible-ad-hoc.html#title-3)

    • [Ansible文件管理模块](file:///F:/老男孩视频/ansible/ansible/02·自动化运维工具Ansible-ad-hoc.html#title-4)

    • [Ansible服务管理模块](file:///F:/老男孩视频/ansible/ansible/02·自动化运维工具Ansible-ad-hoc.html#title-5)

    • [Ansible用户管理模块](file:///F:/老男孩视频/ansible/ansible/02·自动化运维工具Ansible-ad-hoc.html#title-6)

    • [Ansible定时任务模块](file:///F:/老男孩视频/ansible/ansible/02·自动化运维工具Ansible-ad-hoc.html#title-7)

    • [Ansible磁盘挂载模块](file:///F:/老男孩视频/ansible/ansible/02·自动化运维工具Ansible-ad-hoc.html#title-8)

    • [Ansible防火墙模块](file:///F:/老男孩视频/ansible/ansible/02·自动化运维工具Ansible-ad-hoc.html#title-9)

    • [Ansible主机信息模块](file:///F:/老男孩视频/ansible/ansible/02·自动化运维工具Ansible-ad-hoc.html#title-10)


Ansible ad-hoc

1.什么是ad-hoc?

ad-hoc简而言之就是“临时命令”,执行完即结束,并不会保存

2.ad-hoc模式的使用场景

比如在多台机器上查看某个进程是否启动,或拷贝指定文件到本地,等等

3.ad-hoc模式的命令使用

img

#批量查看磁盘信息
[root@m01 ~]# ansible web_group -m command -a 'df -h'
web01 | CHANGED | rc=0 >>
文件系统        容量  已用  可用 已用% 挂载点
web01 | CHANGED | rc=0 >>
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3        19G  2.9G   16G  16% /
devtmpfs        224M     0  224M   0% /dev
tmpfs           235M     0  235M   0% /dev/shm
tmpfs           235M  9.7M  225M   5% /run
tmpfs           235M     0  235M   0% /sys/fs/cgroup
/dev/sda1       197M  105M   93M  54% /boot
tmpfs            47M     0   47M   0% /run/user/0
[root@m01 ~]# ansible db_group -m command -a 'df -h'
web02 | CHANGED | rc=0 >>
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        224M     0  224M   0% /dev
tmpfs           235M     0  235M   0% /dev/shm
tmpfs           235M  9.7M  225M   5% /run
tmpfs           235M     0  235M   0% /sys/fs/cgroup
/dev/sda3        19G  3.1G   16G  17% /
/dev/sda1       197M  133M   64M  68% /boot
tmpfs            47M     0   47M   0% /run/user/0
[root@m01 ~]# ansible webs  -m command -a 'df -h' 
web01 | CHANGED | rc=0 >>
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3        19G  2.9G   16G  16% /
devtmpfs        224M     0  224M   0% /dev
tmpfs           235M     0  235M   0% /dev/shm
tmpfs           235M  9.7M  225M   5% /run
tmpfs           235M     0  235M   0% /sys/fs/cgroup
/dev/sda1       197M  105M   93M  54% /boot
tmpfs            47M     0   47M   0% /run/user/0
web02 | CHANGED | rc=0 >>
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        224M     0  224M   0% /dev
tmpfs           235M     0  235M   0% /dev/shm
tmpfs           235M  9.7M  225M   5% /run
tmpfs           235M     0  235M   0% /sys/fs/cgroup
/dev/sda3        19G  3.1G   16G  17% /
/dev/sda1       197M  133M   64M  68% /boot
tmpfs            47M     0   47M   0% /run/user/0

#批量查看内存信息
[root@m01 ~]# ansible webs  -m command -a 'free -m' 
[root@m01 ~]# ansible webs  -m command -a 'free -m' 
web01 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:            468         187          91          27         189         216
Swap:          1023           0        1023
web02 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:            468         215          92          27         161         213
Swap:          1023           0        1023

颜色">4.ad-hoc结果返回颜色

绿色: 代表被管理端主机没有被修改,或者只是对远程节点信息进行查看
黄色: 代表被管理端主机发现变更
红色: 代表出现了故障,注意查看提示
紫色:表示对命令执行发出警告信息(可能存在的问题,给你一下建议)

image-20200928175700598


5.ad-hoc常用模块

command             # 执行shell命令(不支持管道等特殊字符)
shell               # 执行shell命令
scripts             # 执行shell脚本
yum_repository      # 配置yum仓库
yum                 # 安装软件
copy                # 变更配置文件
file                # 建立目录或文件
service             # 启动与停止服务
mount               # 挂载设备
cron                # 定时任务
get_url             #下载软件
firewalld           #防火墙
selinux             #selinux

6. Ansible-doc帮助手册

[root@m01 ~]# ansible-doc -l        # 查看所有模块说明
[root@m01 ~]# ansible-doc copy      # 查看指定模块方法
[root@m01 ~]# ansible-doc -s copy   # 查看指定模块参数

Ansible命令模块

1.command命令模块

# 默认模块, 执行命令
[root@m01 ~]# ansible web_group -a "hostname"
# 如果需要一些管道操作,则使用shell
[root@m01 ~]# ansible 'web_group' -m shell -a "ifconfig|grep eth0" -f 50

# -f =forks   /etc/ansible/ansible.cfg #结果返回的数量

[root@m01 ~]# ansible 'web_group' -m command -a 'free -m'
web02 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:            972         140         489           7         342         658
Swap:          1023           0        1023

web01 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:            972         113         412          13         446         669
Swap:          1023           0        1023

2.shell

# 如果需要一些管道操作,则使用shell
[root@m01 ~]# ansible web_group -m shell -a "ps -ef|grep nginx" -f 50
[root@m01 ~]# ansible 'web_group' -m shell -a 'ps -ef|grep nginx'
web02 | CHANGED | rc=0 >>
root      12584  12583  0 20:16 pts/1    00:00:00 /bin/sh -c ps -ef|grep nginx
root      12586  12584  0 20:16 pts/1    00:00:00 grep nginx

web01 | CHANGED | rc=0 >>
root      14575  14570  0 12:16 pts/1    00:00:00 /bin/sh -c ps -ef|grep nginx
root      14577  14575  0 12:16 pts/1    00:00:00 grep nginx

注意:

1)command不支持特殊符号
2)shell模块支持特殊符号
3)不指定-m 默认使用的是command模块

3.script脚本模块

# 编写脚本
[root@m01 ~]# vim  test.sh
yum install -y wget
#在本地运行模块,等同于在远程执行,不需要将脚本文件进行推送目标主机执行
[root@m01 ~]# ansible webs -m script -a "/root/test.sh"

wget安装

Ansible软件管理模块

yum模块安装

1.yum安装软件模块

[root@m01 ~]# ansible web_group -m yum -a "name=httpd state=present"
#相当于:yum install -y vsftpd
[root@m01 ~]# ansible 'web_group' -m yum -a 'name=https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-agent-4.0.0-2.el7.x86_64.rpm state=present' 
#相当于:yum install -y https://mirrors.aliyun.com/zabbix/zabbix/4.0/rhel/7/x86_64/zabbix-agent-4.0.0-2.el7.x86_64.rpm

[root@m01 ~]# ansible 'web_group' -m yum -a 'name=file:///root/nagios-4.4.3-1.el7.x86_64.rpm state=present'
#相当于:yum localinstall -y nagios-4.4.3-1.el7.x86_64.rpm

[root@m01 ~]# ansible 'web_group' -m yum -a 'name=vsftpd state=absent'
#相当于:yum remove -y vsftpd
name                            
    httpd                       #指定要安装的软件包名称
    file://                     #指定本地安装路径(yum localinstall 本地rpm包)
    http://                     #指定yum源(从远程仓库获取rpm包)

state                           #指定使用yum的方法
    installed,present           #安装软件包
    removed,absent              #移除软件包
    latest                      #安装最新软件包


[root@m01 ~]# ansible-doc yum
exclude=kernel*,foo*            #排除某些包
list=ansible                    #类似于yum list查看是否可以安装
disablerepo="epel,ol7_latest"   #禁用指定的yum仓库
download_only=true              #只下载不安装 yum install d

2.yum_repository

#添加yum仓库
[root@m01 ~]# ansible web_group -m yum_repository -a "name=oldboy_epel description=EPEL baseurl=https://download./pub/epel/$releasever/$basearch/" -i ./hosts

#仓库名和配置文件名不同
[root@m01 ~]# ansible web_group -m yum_repository -a 'name=oldboy_epel description=EPEL file=test_oldboy baseurl=https://download./pub/base/$releasever/$basearch/ gpgcheck=no' -i ./hosts

#添加mirrorlist
[root@m01 ~]# ansible web_group -m yum_repository -a 'name=oldboy_epel description=EPEL file=test_oldboy baseurl=https://download./pub/base/$releasever/$basearch/ gpgcheck=no mirrorlist=http://mirrorlist./el7/mirrors-rpmforge enabled=no' -i ./hosts

#删除yum仓库及文件
[root@m01 ~]# ansible web_group -m yum_repository -a 'name=oldboy_epel file=test_oldboy state=absent' -i ./hosts
#修改yum仓库
ansible 'web_group' -m yum_repository -a 'name=epel  description=EPEL baseurl=https://download./pub/epel/$releasever/$basearch/ gpgcheck=no enabled=no file=epel'

#开启gpgcheck
[root@m01 ~]# ansible web_group -m yum_repository -a 'name=oldboy_epel description=EPEL file=test_oldboy baseurl=https://download./pub/base/$releasever/$basearch/ gpgcheck=yes gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7' -i ./hosts



name 				#指定仓库名字
description			#添加描述(repo文件中的name)
baseurl				#指定yum仓库的地址
gpgcheck			#是否开启校验
	yes
	no
enabled				#是否启用yum仓库
	yes
	no
file				#指定仓库文件名
state
	absent			#删除yum仓库
	present			#创建yum仓库

ansible 'web_group' -m yum_repository -a 'name=zls_yum  description=EPEL baseurl=http://www. gpgcheck=no enabled=no file=zls'

Ansible文件管理模块

对于文件管理,我们在学习Linux基础的时候,就学习了很多命令,比如创建,删除,移动,拷贝,下载…等

生产场景,统一配置管理


1.copy

- name: Copy file with owner and permissions
  copy:
    src: /srv/myfiles/foo.conf
    dest: /etc/foo.conf
    owner: foo
    group: foo
    mode: '0644'
# 推送文件模块
[root@m01 ~]# ansible webs -m copy -a  "src=/etc/hosts dest=/root"
# 在推送覆盖远程端文件前,对远端已有文件进行备份,按照时间信息备份
[root@m01 ~]# ansible webs -m copy -a "src=/etc/hosts dest=/root owner=www group=www  mode=600"
src             #推送数据的源文件信息
dest            #推送数据的目标路径
backup          #对推送传输过去的文件,进行备份
content         #直接批量在被管理端文件中添加内容
group           #将本地文件推送到远端,指定文件属组信息
owner           #将本地文件推送到远端,指定文件属主信息
mode            #将本地文件推送到远端,指定文件权限信息

2.file

- name: Create an insecure file
  file:
    path: /work
    owner: root
    group: root
    mode: 0755
[root@m01 ~]# ansible webs -m file -a "path=/root/oldboy.txt state=touch owner=www group=www mode=600"

[root@m01 ~]# mkdir alex/
[root@m01 ~]# touch alex/1.txt
[root@m01 ~]# ansible webs -m file -a "path=/root/alex  state=directory owner=www group=www  recurse=yes"
path            #指定远程主机目录或文件信息
recurse         #递归授权
state 
[root@m01 ~]# ansible webs -m file -a "path=/root/alex state=absent"  #删除/root/alex
web01 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/root/alex", 
    "state": "absent"
}
web02 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/root/alex", 
    "state": "absent"
}

    directory   #在远端创建目录
    touch       #在远端创建文件
    link        #link或hard表示创建链接文件
    absent      #表示删除文件或目录
    mode        #设置文件或目录权限
    owner       #设置文件或目录属主信息
    group       #设置文件或目录属组信息

3.get_url服务模块

- name: Download foo.conf
  get_url:
    url: http:///path/file.conf
    dest: /etc/foo.conf
    mode: '0440'

#下载并校验MD5
[root@m01 ~]# ansible webs -m get_url -a "url=https://mirrors.aliyun.com/zabbix/zabbix/3.4/rhel/7/x86_64/zabbix-agent-3.4.0-1.el7.x86_64.rpm dest=/opt/  checksum=md5:f2ed0f1a2770d828204743a09d077f03a4db2a85d615fb8380519db7d50c8581"
[root@m01 ~]# ansible webs -m get_url -a "url=https://mirrors.aliyun.com/zabbix/zabbix/3.4/rhel/7/x86_64/zabbix-agent-3.4.0-1.el7.x86_64.rpm dest=/opt/  checksum=sha256:f2ed0f1a2770d828204743a09d077f03a4db2a85d615fb8380519db7d50c8581"
[root@m01 ~]# ansible webs -m get_url -a "url=https://mirrors.aliyun.com/zabbix/zabbix/3.4/rhel/7/x86_64/zabbix-agent-3.4.0-1.el7.x86_64.rpm dest=/root"
url             #指定下载地址
dest            #指定下载的目录
mode            #指定权限
checksum        #校验加密算法
 md5
  sha256

Ansible服务管理模块

1.service、systemd

#启动crond并加入开机自启
[root@m01 ~]# ansible webs -m service -a "name=nginx state=restarted"
[root@m01 ~]# ansible webs -m service -a "name=nginx state=started"
[root@m01 ~]# ansible webs -m service -a "name=nginx state=enabled"
#停止crond并删除开机自启
[root@m01 ~]# ansible web_group -m service -a "name=nginx
state=stoped enabled=no"
name        # 定义要启动服务的名称
state       # 指定服务状态
    started     #启动服务
    stopped     #停止服务
    restarted   #重启服务
    reloaded    #重载服务
enabled         #开机自启

Ansible用户管理模块

Ansible管理用户与组,通常使用user、group模块


1.group

- name: Ensure group "somegroup" exists
  group:
    name: somegroup
    state: present
#创建组
[root@m01 ~]# ansible webs -m group -a 'name=alex1 gid=666 state=present'
#删除组
[root@m01 ~]# ansible webs -m group -a 'name=alex1 gid=666 state=absent'
[root@m01 ~]# ansible webs -m group -a "name=alex1 gid=888"
name            #指定创建的组名
gid             #指定组的gid
state
    absent      #移除远端主机的组
    present     #创建远端主机的组(默认)

2.user

- name: Create a 2048-bit SSH key for user jsmith in ~jsmith/.ssh/id_rsa
  user:
    name: jsmith
    generate_ssh_key: yes
    ssh_key_bits: 2048
    ssh_key_file: .ssh/id_rsa
#创建用户指定uid和gid,不创建家目录也不允许登陆
[root@m01 ~]# ansible webs -m user -a "name=alex2 uid=777 group=alex1 shell=/sbin/nologin create_home=false"
#创建用户
[root@m01 ~]# ansible webs -m user -a 'name=www uid=666 group=www state=present shell=/sbin/nologin create_home=false'
#删除用户
[root@m01 ~]# ansible webs -m user -a 'name=www uid=666  state=absent'
#创建用户并生成秘钥对
[root@m01 ~]# ansible webs -m user -a "name=oldboyedu uid=888 group=root shell=/bin/bash generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa" 
web01 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 0, 
    "home": "/home/oldboyedu", 
    "name": "oldboyedu", 
    "shell": "/bin/bash", 
    "ssh_fingerprint": "2048 SHA256:Xp/AVU7/TxSnWbHEGjelbycbSyNT8q+dChJDY5uNIQA ansible-generated on web01 (RSA)", 
    "ssh_key_file": "/home/oldboyedu/.ssh/id_rsa", 
    "ssh_public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDKJArao3an+bAgSkplfK8WjooJ5ZuRXz6su9ulcJ1Hx7BhkncdhClf9PkTj4/V3nmz17eEbnP5jKBTTS9V+sHNi4FIl9gHNfRk7LdK0zcAQTMcXh4iJusHs3oVJ3inkO9vy7DOq2XE4WHJFovRx+1UdA2YkoPTRpfmyuLxADsuVNL+Gd16fHiSqhcMY6kDfVG9/a4n52zTz9bEjrDJw9len/Uqf9dSYgauO8Jc7MGitlYf8adFY9GU/LOxgLPDbJg4DTOjXrfUEQaMCMHA6DJBqHMSsUNgo9TSg+wnljWJTul7EvRpTlmqdLd59Cm2H/UiApKXB+5X2/fdzt98iWQ7 ansible-generated on web01", 
    "state": "present", 
    "system": false, 
    "uid": 888
}
web02 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 0, 
    "home": "/home/oldboyedu", 
    "name": "oldboyedu", 
    "shell": "/bin/bash", 
    "ssh_fingerprint": "2048 SHA256:NsBDvKMOGnMMcqu5wQ960SmuNi+xqdIpEURHKA8AFTE ansible-generated on web02 (RSA)", 
    "ssh_key_file": "/home/oldboyedu/.ssh/id_rsa", 
    "ssh_public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDhCvUL6sPWgPvX7g9RYERs1Tvk7L9J7TR4QWqSfAa8WXYJfcXwFhpmQKpP9qcIl2pAe4OMr/ELBaDJZ+l61D3WqLWSONtgt7g5gAsjIo/ItBqiR4/zn+eD3xfSJlCbQTklW6FOXKYvaRT9J1ZlA3EKgZ/9EwlnTnZnnLaYvTJeoP7s5kBzplF05TxNZQNB37dEtznJ1BBgQBePsYpSaJpgdeQaki9sucQPHybHzlxEfo+lVJwBuDKAI7a9YTnPeTt87/j51MSN8oid0aWwYUrnnjtV9mypw3/Z0QxhtMlj/f2015n3I0ORzm1DFi7tpsvZWOIrRyRjLPS3oFk0DPiZ ansible-generated on web02", 
    "state": "present", 
    "system": false, 
    "uid": 888
}
[root@m01 ~]# ansible webs -m debug -a "msg={{ 'oldboyedu' | password_hash('sha512', 'salt') }}"
web01 | SUCCESS => {
    "msg": "$6$salt$YXux/o8yWT1cYnuk0RwRYMHulfImyHbBqmRyteeVa5Kx/kOZTtXVJ09XNOO8HoFIeIWugC43q8yqP0whfybV71"
}
web02 | SUCCESS => {
    "msg": "$6$salt$YXux/o8yWT1cYnuk0RwRYMHulfImyHbBqmRyteeVa5Kx/kOZTtXVJ09XNOO8HoFIeIWugC43q8yqP0whfybV71"
}
#将明文密码进行hash加密,然后进行用户创建
[root@m01 ~]# ansible webs -m debug -a "msg={{ 'oldboyedu' | password_hash('sha512', 'salt') }}"
web01 | SUCCESS => {
    "msg": "$6$salt$YXux/o8yWT1cYnuk0RwRYMHulfImyHbBqmRyteeVa5Kx/kOZTtXVJ09XNOO8HoFIeIWugC43q8yqP0whfybV71"
}
web02 | SUCCESS => {
    "msg": "$6$salt$YXux/o8yWT1cYnuk0RwRYMHulfImyHbBqmRyteeVa5Kx/kOZTtXVJ09XNOO8HoFIeIWugC43q8yqP0whfybV71"
}
#创建用户
[root@m01 ~]# ansible webs -m user -a 'name=text password=$6$salt$YXux/o8yWT1cYnuk0RwRYMHulfImyHbBqmRyteeVa5Kx/kOZTtXVJ09XNOO8HoFIeIWugC43q8yqP0whfybV71 create_home=true shell=/bin/bash' 
uid             #指定用户的uid
group           #指定用户组名称
groups          #指定附加组名称
password        #给用户添加密码(单引号)
shell           #指定用户登录shell
create_home     #是否创建家目录
	/bin/bash
	/sbin/nologin
create_home				#是否创建家目录
	true
	false
comment					#添加注释
generate_ssh_key		#创建密钥对
ssh_key_bits			#指定密钥对长度
ssh_key_file			#指定密钥文件
使用ad-hoc编写backup服务器
  1) 准备服务器BACKUP 10.0.0.51
     准备客户端WEB01  10.0.0.7
  2) 安装rsync服务
     yum -y install rsync
  3) 编写配置文件
     /etc/rsyncd.conf  # 复制配置文件
  4) 根据配置文件配置必要的数据目录
     a. 创建组 www gid=666 
	 b. 创建用户 www uid=666 gid=666 nologin -M
	 c. 创建目录 /data
	 d. 授权 chown -R www.www /data #保证用户在推送数据的时候有权限往里面写东西
  5) 创建密码文件
     echo rsync_backup:123456 > /etc/rsync.passwd
     修改passwd的权限
     chmod 600 /etc/rsync.passwd
  6) 启动rsyncd
     systemctl start rsyncd 
	 systemctl enable rsyncd
  客户端:
  1) 安装rsync服务
  2) 配置密码文件
     echo 123456 >/etc/rsync.passwd
	 修改权限
	 chmod 600 /etc/rsync.passwd
  推送命令
  rsync -avz file rsync_backup@172.16.1.51::backup
	  
使用ansible ad-hoc完成上面的步骤:
提前准备主机清单:
[root@m01 ~]# cat /etc/ansible/hosts
[dbs]
db01 ansible_ssh_host=10.0.0.51
推送公钥到51
[root@m01 ~]# ssh-copy-id -i .ssh/id_rsa.pub 10.0.0.51
[root@m01 ~]# ssh-copy-id -i .ssh/id_rsa.pub 172.16.1.51
1.安装rsync服务	 使用 yum模块
  [root@m01 ~]# ansible db01 -m yum -a "name=rsync state=present" 
2.编写配置文件 复制配置文件到10.0.0.51下的/etc下
  a.准备配置文件
    cat /root/project/rsyncd.j2
	uid = www
	gid = www
	port = 873
	fake super = yes
	use chroot = no
	max connections = 200
	timeout = 600
	ignore errors
	read only = false
	list = false
	auth users = rsync_backup
	secrets file = /etc/rsync.passwd
	log file = /var/log/rsyncd.log
	#####################################
	[backup]
	comment = welcome to oldboyedu backup!
	path = /data	
  b. 拷贝到51 使用copy模块
  [root@m01 ~]# ansible db01 -m copy -a "src=/root/project/rsyncd.j2 dest=/etc/rsyncd.conf owner=root group=root mode=0644"
3. 创建组和用户 创建/data目录 并授权为www  
  a. 创建组 
  [root@m01 ~]# ansible db01 -m group -a "name=www gid=666"
  b. 创建用户
  [root@m01 ~]# ansible db01 -m user -a "name=www uid=666 group=www shell=/sbin/nologin create_home=no"
  c. 创建目录并授权 使用file模块
  [root@m01 ~]# ansible db01 -m file -a "path=/data state=directory owner=www group=www mode=0755 recurse=yes"
4. 创建虚拟用户的密码文件 /etc/rsync.passwd  使用copy模块
  [root@m01 ~]# ansible db01 -m copy -a "content=rsync_backup:123456 dest=/etc/rsync.passwd mode=600"
5. 启动rsyncd服务 使用service 或者systemd 并开机自动运行
  [root@m01 ~]# ansible db01 -m systemd -a "name=rsyncd state=started enabled=yes"
6. 配置客户端
   [root@m01 ~]# ansible web01 -m yum -a "name=rsync state=present"  
   配置密码文件 
   [root@m01 ~]# ansible web01 -m copy -a "content=123456 dest=/etc/rsync.passwd mode=600"

Ansible定时任务模块

cron

# 正常使用crond服务
[root@m01 ~]#
[root@m01 ~]# crontab -l
* * * * *  /bin/sh /server/scripts/yum.sh
# 使用ansible添加一条定时任务
[root@m01 ~]#ansible db01 -m yum -a "name=rsync state=present"
# 删除相应定时任务
[root@m01 ~]#ansible webs -m cron -a"name='check dirs' state=absent"
[root@m01 ~]# ansible webs -m cron -a "name='push rsync'  job='/bin/sh /server/scripts/check_rsync.sh'"
web01 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "push rsync"
    ]
}
web02 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "push rsync"
    ]
}
[root@m01 ~]# ansible webs -m cron -a "name='push rsync'  job='/bin/sh /server/scripts/check_rsync.sh'&>/dev/null"
[root@web01 ~]# crontab -l
#Ansible: push rsync
* * * * * '/bin/sh /server/scripts/check_rsync.sh'&>/dev/null
# 注释相应定时任务,使定时任务失效
[root@m01 ~]# ansible webs -m cron -a "name='push rsync' job='/bin/sh /server/scripts/check_rsync.sh  &>/dev/null' disabled=yes"
web02 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "push rsync"
    ]
}
web01 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "push rsync"
    ]
}
[root@web01 ~]# crontab -l
#Ansible: push rsync
#* * * * * /bin/sh /server/scripts/check_rsync.sh  &>/dev/null
[root@m01 ~]# ansible webs -m cron -a "job='/bin/sh /server/scripts/test.sh'"
[root@m01 ~]#ansible webs -m cron -a"name='None' state=absent"




隔离
#####################################################
[root@m01 ~]# ansible webs cron -a "minute=* hour=* day=* month=* weekday=*  job='/bin/sh /server/scripts/test.sh'" 
# 设置定时任务注释信息,防止重复,name设定
[root@m01 ~]# ansible webs -m cron -a "name='cron01' job='/bin/sh /server/scripts/test.sh'"
# 删除相应定时任务
[root@m01 ~]# ansible webs -m cron -a "name='ansible cron02' minute=0 hour=0 job='/bin/sh /server/scripts/test.sh' state=absent"
# 注释相应定时任务,使定时任务失效
[root@m01 scripts]# ansible webs -m cron -a "name='ansible cron01' minute=0 hour=0 job='/bin/sh /server/scripts/test.sh' disabled=no"

Ansible磁盘挂载模块

1.mount

[root@m01 ~]#ansible db01 -m  yum -a "name=nfs-utils state=present"
[root@m01 ~]# ansible db01 -m copy -a "content='/backup 172.16.1.0/24(rw,sync,no_all_squash)' dest=/etc/exports"
db01 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "eb44c1ee87bf077371ce11beea55557bd38dc905", 
    "dest": "/etc/exports", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "d2147e7d05a9e9f20e64c45dc20db8a4", 
    "mode": "0644", 
    "owner": "root", 
    "size": 44, 
    "src": "/root/.ansible/tmp/ansible-tmp-1601362036.08-17361-62525718458563/source", 
    "state": "file", 
    "uid": 0
}
[root@db01 ~]# cat /etc/exports
/backup 172.16.1.0/24(rw,sync,no_all_squash)
[root@m01 ~]#ansible db01 -m file -a "path=/backup  state=directory"
db01 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/backup", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}
[root@m01 ~]#ansible db01 -m systemd  -a "name=nfs  state=started"
[root@m01 ~]#ansible db01 -m systemd  -a "name=rpcbind state=started enabled=yes"
[root@m01 ~]#ansible db01 -m systemd  -a "name=nfs  state=enabled"
[root@db01 ~]#ps axu|grep nfs
[root@web01 ~]# showmount -e 172.16.1.51  #挂载
Export list for 172.16.1.51:
/backup 172.16.1.0/24
[root@m01 ~]# ansible web01 -m mount -a "path=/mnt src=172.16.1.51:/backup fstype=nfs opts=defaults state=present"
web01 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dump": "0", 
    "fstab": "/etc/fstab", 
    "fstype": "nfs", 
    "name": "/mnt", 
    "opts": "defaults", 
    "passno": "0", 
    "src": "172.16.1.51:/backup"
}
[root@m01 ~]#ansible web01 -m mount -a "path=/mnt src=172.16.1.51:/backup fstype=nfs opts=defaults state=present" 
挂载一个
[root@web01 ~]# cat /etc/fstab
#
# /etc/fstab
# Created by anaconda on Fri Aug 28 11:11:17 2020
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
UUID=b9cb8051-9db7-4554-b99a-bf607421a654 /                       xfs     defaults        0 0
UUID=2b6a63c7-827b-45ea-8ef5-25c2bb7ef4c1 /boot                   xfs     defaults        0 0
UUID=4f5cf895-4744-4d1a-b218-14e931666480 swap                    swap    defaults        0 0
172.16.1.51:/backup /mnt nfs defaults 0 0

[root@m01 ~]# ansible web01 -m mount -a "path=/mnt src=172.16.1.51:/backup fstype=nfs opts=defaults state=mounted"
两个同时挂载上
 [root@web01 ~]# df -h
Filesystem           Size  Used Avail Use% Mounted on
/dev/sda3             19G  2.9G   16G  16% /
devtmpfs             224M     0  224M   0% /dev
tmpfs                235M     0  235M   0% /dev/shm
tmpfs                235M   26M  209M  11% /run
tmpfs                235M     0  235M   0% /sys/fs/cgroup
/dev/sda1            197M  105M   93M  54% /boot
tmpfs                 47M     0   47M   0% /run/user/0
172.16.1.51:/backup   19G  2.4G   17G  13% /mnt
[root@web01 ~]# cat /etc/fstab
#
# /etc/fstab
# Created by anaconda on Fri Aug 28 11:11:17 2020
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
UUID=b9cb8051-9db7-4554-b99a-bf607421a654 /                       xfs     defaults        0 0
UUID=2b6a63c7-827b-45ea-8ef5-25c2bb7ef4c1 /boot                   xfs     defaults        0 0
UUID=4f5cf895-4744-4d1a-b218-14e931666480 swap                    swap    defaults        0 0
172.16.1.51:/backup /mnt nfs defaults 0 0
[root@m01 ~]#ansible web01 -m mount -a "path=/mnt src=172.16.1.51:/backup fstype=nfs opts=defaults state=absent"
[root@m01 ~]#ansible web01 -m mount -a "path=/mnt src=172.16.1.51:/backup fstype=nfs opts=defaults state=unmounted" 
present     # 开机挂载,仅将挂载配置写入/etc/fstab
mounted     # 挂载设备,并将配置写入/etc/fstab
unmounted   # 卸载设备,不会清除/etc/fstab写入的配置
absent      # 卸载设备,会清理/etc/fstab写入的配置
            


#################################################
[root@m01 ~]# ansible webs -m mount -a "src=172.16.1.31:/data path=/data fstype=nfs opts=defaults state=present"
[root@m01 ~]# ansible web01 -m mount -a "src=172.16.1.31:/data path=/data fstype=nfs opts=defaults state=mounted"
[root@m01 ~]# ansible web02 -m mount -a "src=172. 16.1.31:/data path=/data fstype=nfs opts=defaults state=unmounted"
[root@m01 ~]# ansible web -m mount -a "src=172.16.1.31:/data path=/data fstype=nfs opts=defaults state=absent"
present     # 开机挂载,仅将挂载配置写入/etc/fstab
mounted     # 挂载设备,并将配置写入/etc/fstab
unmounted   # 卸载设备,不会清除/etc/fstab写入的配置
absent      # 卸载设备,会清理/etc/fstab写入的配置

Ansible防火墙模块

1.selinux

#修改配置文件关闭selinux,必须重启
[root@m01 ~]# ansible web01 -m selinux -a "policy=targeted state=enforcing"
[WARNING]: Reboot is required to set SELinux state to 'enforcing'
web01 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "configfile": "/etc/selinux/config", 
    "msg": "Config SELinux state changed from 'disabled' to 'enforcing'", 
    "policy": "targeted", 
    "reboot_required": true, 
    "state": "enforcing"
}



#############################################
[root@m01 ~]# ansible webs -m selinux -a 'state=disabled' -i ./hosts
 [WARNING]: SELinux state temporarily changed from 'enforcing' to 'permissive'. State change will take effect next reboot.

web01 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "configfile": "/etc/selinux/config",
    "msg": "Config SELinux state changed from 'enforcing' to 'disabled'",
    "policy": "targeted",
    "reboot_required": true,
    "state": "disabled"
}
web02 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "configfile": "/etc/selinux/config",
    "msg": "Config SELinux state changed from 'enforcing' to 'disabled'",
    "policy": "targeted",
    "reboot_required": true,
    "state": "disabled"
}

#临时关闭
[root@m01 ~]# ansible webs -m shell -a 'setenforce 0' -i ./hosts
web02 | CHANGED | rc=0 >>
web01 | CHANGED | rc=0 >>


[root@m01 ~]# ansible webs -m shell -a 'getenforce' -i ./hosts
web02 | CHANGED | rc=0 >>
Permissive

web01 | CHANGED | rc=0 >>
Permissive

2.firewalld

[root@m01 ~]# ansible webs -m firewalld -a 'service=http permanent=yes state=enabled' -i ./hosts
[root@m01 ~]# ansible webs -m firewalld -a "service=http immediate=yes permanent=yes state=enabled" -i ./hosts

[root@m01 ~]# ansible webs -m firewalld -a "port=8080-8090/tcp immediate=yes permanent=yes state=enabled" -i ./hosts

service                 #指定开放或关闭的服务名称
port                    #指定开放或关闭的端口
permanent               #是否添加永久生效
state                   #开启或者关闭
    enabled
    disabled

zone                    #指定配置某个区域
rich_rule               #配置辅规则
masquerade              #开启地址伪装
immediate               #临时生效
source                  #指定来源IP

Ansible主机信息模块

为什么要讲这个模块?

做过自动化的小伙伴会觉得这个模块非常实用

在公司中总会有一些需求

比如:
1.根据不同主机不同IP创建对应IP的目录
2.根据不同主机不同主机名创建对应主机名的目录
3.自动化运维平台需要自动获取到主机的IP地址,内存信息,磁盘信息,主机名…等
4.如果安装数据库,分配内存为物理内存的80%,此时有3台不同物理内存的机器2G、4G、16G
写一个playbook的情况下,我需要获取到对应主机的内存并作出计算,写判断。


setup

1.查看所有详细信息
[root@m01 ~]# ansible web01 -m setup
ansible web01 -m setup
web01 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "10.0.0.7", 
            "172.16.1.7"
        ], 
        "ansible_all_ipv6_addresses": [
            "fe80::20c:29ff:fe85:aad0", 
            "fe80::20c:29ff:fe85:aada"
        ], 
        "ansible_apparmor": {
            "status": "disabled"
        }, 
        "ansible_architecture": "x86_64", 
        "ansible_bios_date": "07/29/2019", 
        "ansible_bios_version": "6.00", 
        "ansible_cmdline": {
            "BOOT_IMAGE": "/vmlinuz-3.10.0-957.el7.x86_64", 
            "LANG": "en_US.UTF-8", 
            "biosdevname": "0", 
            "net.ifnames": "0", 
            "quiet": true, 
            "rhgb": true, 
            "ro": true, 
            "root": "UUID=b9cb8051-9db7-4554-b99a-bf607421a654"
        }, 
        "ansible_date_time": {
            "date": "2020-09-29", 
            "day": "29", 
            "epoch": "1601364330", 
            "hour": "15", 
            "iso8601": "2020-09-29T07:25:30Z", 
            "iso8601_basic": "20200929T152530908292", 
            "iso8601_basic_short": "20200929T152530", 
            "iso8601_micro": "2020-09-29T07:25:30.908393Z", 
            "minute": "25", 
            "month": "09", 
            "second": "30", 
            "time": "15:25:30", 
            "tz": "CST", 
            "tz_offset": "+0800", 
            "weekday": "Tuesday", 
            "weekday_number": "2", 
            "weeknumber": "39", 
            "year": "2020"
        }, 
        "ansible_default_ipv4": {
            "address": "10.0.0.7", 
            "alias": "eth0", 
            "broadcast": "10.0.0.255", 
            "gateway": "10.0.0.2", 
            "interface": "eth0", 
            "macaddress": "00:0c:29:85:aa:d0", 
            "mtu": 1500, 
            "netmask": "255.255.255.0", 
            "network": "10.0.0.0", 
            "type": "ether"
        }, 
        "ansible_default_ipv6": {}, 
        "ansible_device_links": {
            "ids": {
                "sr0": [
                    "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
                ]
            }, 
            "labels": {
                "sr0": [
                    "CentOS\\x207\\x20x86_64"
                ]
            }, 
            "masters": {}, 
            "uuids": {
                "sda1": [
                    "2b6a63c7-827b-45ea-8ef5-25c2bb7ef4c1"
                ], 
                "sda2": [
                    "4f5cf895-4744-4d1a-b218-14e931666480"
                ], 
                "sda3": [
                    "b9cb8051-9db7-4554-b99a-bf607421a654"
                ], 
                "sr0": [
                    "2018-11-25-23-54-16-00"
                ]
            }
        }, 
        "ansible_devices": {
            "sda": {
                "holders": [], 
                "host": "SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)", 
                "links": {
                    "ids": [], 
                    "labels": [], 
                    "masters": [], 
                    "uuids": []
                }, 
                "model": "VMware Virtual S", 
                "partitions": {
                    "sda1": {
                        "holders": [], 
                        "links": {
                            "ids": [], 
                            "labels": [], 
                            "masters": [], 
                            "uuids": [
                                "2b6a63c7-827b-45ea-8ef5-25c2bb7ef4c1"
                            ]
                        }, 
                        "sectors": "409600", 
                        "sectorsize": 512, 
                        "size": "200.00 MB", 
                        "start": "2048", 
                        "uuid": "2b6a63c7-827b-45ea-8ef5-25c2bb7ef4c1"
                    }, 
                    "sda2": {
                        "holders": [], 
                        "links": {
                            "ids": [], 
                            "labels": [], 
                            "masters": [], 
                            "uuids": [
                                "4f5cf895-4744-4d1a-b218-14e931666480"
                            ]
                        }, 
                        "sectors": "2097152", 
                        "sectorsize": 512, 
                        "size": "1.00 GB", 
                        "start": "411648", 
                        "uuid": "4f5cf895-4744-4d1a-b218-14e931666480"
                    }, 
                    "sda3": {
                        "holders": [], 
                        "links": {
                            "ids": [], 
                            "labels": [], 
                            "masters": [], 
                            "uuids": [
                                "b9cb8051-9db7-4554-b99a-bf607421a654"
                            ]
                        }, 
                        "sectors": "39434240", 
                        "sectorsize": 512, 
                        "size": "18.80 GB", 
                        "start": "2508800", 
                        "uuid": "b9cb8051-9db7-4554-b99a-bf607421a654"
                    }
                }, 
                "removable": "0", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "deadline", 
                "sectors": "41943040", 
                "sectorsize": "512", 
                "size": "20.00 GB", 
                "support_discard": "0", 
                "vendor": "VMware,", 
                "virtual": 1
            }, 
            "sr0": {
                "holders": [], 
                "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)", 
                "links": {
                    "ids": [
                        "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
                    ], 
                    "labels": [
                        "CentOS\\x207\\x20x86_64"
                    ], 
                    "masters": [], 
                    "uuids": [
                        "2018-11-25-23-54-16-00"
                    ]
                }, 
                "model": "VMware IDE CDR10", 
                "partitions": {}, 
                "removable": "1", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "deadline", 
                "sectors": "8962048", 
                "sectorsize": "2048", 
                "size": "4.27 GB", 
                "support_discard": "0", 
                "vendor": "NECVMWar", 
                "virtual": 1
            }
        }, 
        "ansible_distribution": "CentOS", 
        "ansible_distribution_file_parsed": true, 
        "ansible_distribution_file_path": "/etc/redhat-release", 
        "ansible_distribution_file_variety": "RedHat", 
        "ansible_distribution_major_version": "7", 
        "ansible_distribution_release": "Core", 
        "ansible_distribution_version": "7.6", 
        "ansible_dns": {
            "nameservers": [
                "223.5.5.5"
            ]
        }, 
        "ansible_domain": "", 
        "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", 
            "LS_COLORS": "rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:", 
            "MAIL": "/var/mail/root", 
            "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin", 
            "PWD": "/root", 
            "SHELL": "/bin/bash", 
            "SHLVL": "2", 
            "SSH_CLIENT": "10.0.0.61 42398 22", 
            "SSH_CONNECTION": "10.0.0.61 42398 10.0.0.7 22", 
            "SSH_TTY": "/dev/pts/1", 
            "TERM": "xterm", 
            "USER": "root", 
            "XDG_RUNTIME_DIR": "/run/user/0", 
            "XDG_SESSION_ID": "1183", 
            "_": "/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]", 
                "hw_tc_offload": "off [fixed]", 
                "l2_fwd_offload": "off [fixed]", 
                "large_receive_offload": "off [fixed]", 
                "loopback": "off [fixed]", 
                "netns_local": "off [fixed]", 
                "ntuple_filters": "off [fixed]", 
                "receive_hashing": "off [fixed]", 
                "rx_all": "off", 
                "rx_checksumming": "off", 
                "rx_fcs": "off", 
                "rx_gro_hw": "off [fixed]", 
                "rx_udp_tunnel_port_offload": "off [fixed]", 
                "rx_vlan_filter": "on [fixed]", 
                "rx_vlan_offload": "on", 
                "rx_vlan_stag_filter": "off [fixed]", 
                "rx_vlan_stag_hw_parse": "off [fixed]", 
                "scatter_gather": "on", 
                "tcp_segmentation_offload": "on", 
                "tx_checksum_fcoe_crc": "off [fixed]", 
                "tx_checksum_ip_generic": "on", 
                "tx_checksum_ipv4": "off [fixed]", 
                "tx_checksum_ipv6": "off [fixed]", 
                "tx_checksum_sctp": "off [fixed]", 
                "tx_checksumming": "on", 
                "tx_fcoe_segmentation": "off [fixed]", 
                "tx_gre_csum_segmentation": "off [fixed]", 
                "tx_gre_segmentation": "off [fixed]", 
                "tx_gso_partial": "off [fixed]", 
                "tx_gso_robust": "off [fixed]", 
                "tx_ipip_segmentation": "off [fixed]", 
                "tx_lockless": "off [fixed]", 
                "tx_nocache_copy": "off", 
                "tx_scatter_gather": "on", 
                "tx_scatter_gather_fraglist": "off [fixed]", 
                "tx_sctp_segmentation": "off [fixed]", 
                "tx_sit_segmentation": "off [fixed]", 
                "tx_tcp6_segmentation": "off [fixed]", 
                "tx_tcp_ecn_segmentation": "off [fixed]", 
                "tx_tcp_mangleid_segmentation": "off", 
                "tx_tcp_segmentation": "on", 
                "tx_udp_tnl_csum_segmentation": "off [fixed]", 
                "tx_udp_tnl_segmentation": "off [fixed]", 
                "tx_vlan_offload": "on [fixed]", 
                "tx_vlan_stag_hw_insert": "off [fixed]", 
                "udp_fragmentation_offload": "off [fixed]", 
                "vlan_challenged": "off [fixed]"
            }, 
            "hw_timestamp_filters": [], 
            "ipv4": {
                "address": "10.0.0.7", 
                "broadcast": "10.0.0.255", 
                "netmask": "255.255.255.0", 
                "network": "10.0.0.0"
            }, 
            "ipv6": [
                {
                    "address": "fe80::20c:29ff:fe85:aad0", 
                    "prefix": "64", 
                    "scope": "link"
                }
            ], 
            "macaddress": "00:0c:29:85:aa:d0", 
            "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]", 
                "hw_tc_offload": "off [fixed]", 
                "l2_fwd_offload": "off [fixed]", 
                "large_receive_offload": "off [fixed]", 
                "loopback": "off [fixed]", 
                "netns_local": "off [fixed]", 
                "ntuple_filters": "off [fixed]", 
                "receive_hashing": "off [fixed]", 
                "rx_all": "off", 
                "rx_checksumming": "off", 
                "rx_fcs": "off", 
                "rx_gro_hw": "off [fixed]", 
                "rx_udp_tunnel_port_offload": "off [fixed]", 
                "rx_vlan_filter": "on [fixed]", 
                "rx_vlan_offload": "on", 
                "rx_vlan_stag_filter": "off [fixed]", 
                "rx_vlan_stag_hw_parse": "off [fixed]", 
                "scatter_gather": "on", 
                "tcp_segmentation_offload": "on", 
                "tx_checksum_fcoe_crc": "off [fixed]", 
                "tx_checksum_ip_generic": "on", 
                "tx_checksum_ipv4": "off [fixed]", 
                "tx_checksum_ipv6": "off [fixed]", 
                "tx_checksum_sctp": "off [fixed]", 
                "tx_checksumming": "on", 
                "tx_fcoe_segmentation": "off [fixed]", 
                "tx_gre_csum_segmentation": "off [fixed]", 
                "tx_gre_segmentation": "off [fixed]", 
                "tx_gso_partial": "off [fixed]", 
                "tx_gso_robust": "off [fixed]", 
                "tx_ipip_segmentation": "off [fixed]", 
                "tx_lockless": "off [fixed]", 
                "tx_nocache_copy": "off", 
                "tx_scatter_gather": "on", 
                "tx_scatter_gather_fraglist": "off [fixed]", 
                "tx_sctp_segmentation": "off [fixed]", 
                "tx_sit_segmentation": "off [fixed]", 
                "tx_tcp6_segmentation": "off [fixed]", 
                "tx_tcp_ecn_segmentation": "off [fixed]", 
                "tx_tcp_mangleid_segmentation": "off", 
                "tx_tcp_segmentation": "on", 
                "tx_udp_tnl_csum_segmentation": "off [fixed]", 
                "tx_udp_tnl_segmentation": "off [fixed]", 
                "tx_vlan_offload": "on [fixed]", 
                "tx_vlan_stag_hw_insert": "off [fixed]", 
                "udp_fragmentation_offload": "off [fixed]", 
                "vlan_challenged": "off [fixed]"
            }, 
            "hw_timestamp_filters": [], 
            "ipv4": {
                "address": "172.16.1.7", 
                "broadcast": "172.16.1.255", 
                "netmask": "255.255.255.0", 
                "network": "172.16.1.0"
            }, 
            "ipv6": [
                {
                    "address": "fe80::20c:29ff:fe85:aada", 
                    "prefix": "64", 
                    "scope": "link"
                }
            ], 
            "macaddress": "00:0c:29:85:aa:da", 
            "module": "e1000", 
            "mtu": 1500, 
            "pciid": "0000:02:05.0", 
            "promisc": false, 
            "speed": 1000, 
            "timestamping": [
                "tx_software", 
                "rx_software", 
                "software"
            ], 
            "type": "ether"
        }, 
        "ansible_fibre_channel_wwn": [], 
        "ansible_fips": false, 
        "ansible_form_factor": "Other", 
        "ansible_fqdn": "web01", 
        "ansible_hostname": "web01", 
        "ansible_hostnqn": "", 
        "ansible_interfaces": [
            "lo", 
            "eth1", 
            "eth0"
        ], 
        "ansible_is_chroot": false, 
        "ansible_iscsi_iqn": "", 
        "ansible_kernel": "3.10.0-957.el7.x86_64", 
        "ansible_kernel_version": "#1 SMP Thu Nov 8 23:39:32 UTC 2018", 
        "ansible_lo": {
            "active": true, 
            "device": "lo", 
            "features": {
                "busy_poll": "off [fixed]", 
                "fcoe_mtu": "off [fixed]", 
                "generic_receive_offload": "on", 
                "generic_segmentation_offload": "on", 
                "highdma": "on [fixed]", 
                "hw_tc_offload": "off [fixed]", 
                "l2_fwd_offload": "off [fixed]", 
                "large_receive_offload": "off [fixed]", 
                "loopback": "on [fixed]", 
                "netns_local": "on [fixed]", 
                "ntuple_filters": "off [fixed]", 
                "receive_hashing": "off [fixed]", 
                "rx_all": "off [fixed]", 
                "rx_checksumming": "on [fixed]", 
                "rx_fcs": "off [fixed]", 
                "rx_gro_hw": "off [fixed]", 
                "rx_udp_tunnel_port_offload": "off [fixed]", 
                "rx_vlan_filter": "off [fixed]", 
                "rx_vlan_offload": "off [fixed]", 
                "rx_vlan_stag_filter": "off [fixed]", 
                "rx_vlan_stag_hw_parse": "off [fixed]", 
                "scatter_gather": "on", 
                "tcp_segmentation_offload": "on", 
                "tx_checksum_fcoe_crc": "off [fixed]", 
                "tx_checksum_ip_generic": "on [fixed]", 
                "tx_checksum_ipv4": "off [fixed]", 
                "tx_checksum_ipv6": "off [fixed]", 
                "tx_checksum_sctp": "on [fixed]", 
                "tx_checksumming": "on", 
                "tx_fcoe_segmentation": "off [fixed]", 
                "tx_gre_csum_segmentation": "off [fixed]", 
                "tx_gre_segmentation": "off [fixed]", 
                "tx_gso_partial": "off [fixed]", 
                "tx_gso_robust": "off [fixed]", 
                "tx_ipip_segmentation": "off [fixed]", 
                "tx_lockless": "on [fixed]", 
                "tx_nocache_copy": "off [fixed]", 
                "tx_scatter_gather": "on [fixed]", 
                "tx_scatter_gather_fraglist": "on [fixed]", 
                "tx_sctp_segmentation": "on", 
                "tx_sit_segmentation": "off [fixed]", 
                "tx_tcp6_segmentation": "on", 
                "tx_tcp_ecn_segmentation": "on", 
                "tx_tcp_mangleid_segmentation": "on", 
                "tx_tcp_segmentation": "on", 
                "tx_udp_tnl_csum_segmentation": "off [fixed]", 
                "tx_udp_tnl_segmentation": "off [fixed]", 
                "tx_vlan_offload": "off [fixed]", 
                "tx_vlan_stag_hw_insert": "off [fixed]", 
                "udp_fragmentation_offload": "on", 
                "vlan_challenged": "on [fixed]"
            }, 
            "hw_timestamp_filters": [], 
            "ipv4": {
                "address": "127.0.0.1", 
                "broadcast": "host", 
                "netmask": "255.0.0.0", 
                "network": "127.0.0.0"
            }, 
            "ipv6": [
                {
                    "address": "::1", 
                    "prefix": "128", 
                    "scope": "host"
                }
            ], 
            "mtu": 65536, 
            "promisc": false, 
            "timestamping": [
                "rx_software", 
                "software"
            ], 
            "type": "loopback"
        }, 
        "ansible_local": {}, 
        "ansible_lsb": {}, 
        "ansible_machine": "x86_64", 
        "ansible_machine_id": "04e4ec5455f242169867fbdc32610ee1", 
        "ansible_memfree_mb": 27, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 215, 
                "used": 253
            }, 
            "real": {
                "free": 27, 
                "total": 468, 
                "used": 441
            }, 
            "swap": {
                "cached": 0, 
                "free": 1016, 
                "total": 1023, 
                "used": 7
            }
        }, 
        "ansible_memtotal_mb": 468, 
        "ansible_mounts": [
            {
                "block_available": 23593, 
                "block_size": 4096, 
                "block_total": 50345, 
                "block_used": 26752, 
                "device": "/dev/sda1", 
                "fstype": "xfs", 
                "inode_available": 102074, 
                "inode_total": 102400, 
                "inode_used": 326, 
                "mount": "/boot", 
                "options": "rw,relatime,attr2,inode64,noquota", 
                "size_available": 96636928, 
                "size_total": 206213120, 
                "uuid": "2b6a63c7-827b-45ea-8ef5-25c2bb7ef4c1"
            }, 
            {
                "block_available": 269523, 
                "block_size": 65536, 
                "block_total": 307920, 
                "block_used": 38397, 
                "device": "172.16.1.51:/backup", 
                "fstype": "nfs4", 
                "inode_available": 9783235, 
                "inode_total": 9858560, 
                "inode_used": 75325, 
                "mount": "/mnt", 
                "options": "rw,relatime,vers=4.1,rsize=65536,wsize=65536,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,clientaddr=172.16.1.7,local_lock=none,addr=172.16.1.51", 
                "size_available": 17663459328, 
                "size_total": 20179845120, 
                "uuid": "N/A"
            }, 
            {
                "block_available": 4182539, 
                "block_size": 4096, 
                "block_total": 4926720, 
                "block_used": 744181, 
                "device": "/dev/sda3", 
                "fstype": "xfs", 
                "inode_available": 9704927, 
                "inode_total": 9858560, 
                "inode_used": 153633, 
                "mount": "/", 
                "options": "rw,relatime,attr2,inode64,noquota", 
                "size_available": 17131679744, 
                "size_total": 20179845120, 
                "uuid": "b9cb8051-9db7-4554-b99a-bf607421a654"
            }
        ], 
        "ansible_nodename": "web01", 
        "ansible_os_family": "RedHat", 
        "ansible_pkg_mgr": "yum", 
        "ansible_proc_cmdline": {
            "BOOT_IMAGE": "/vmlinuz-3.10.0-957.el7.x86_64", 
            "LANG": "en_US.UTF-8", 
            "biosdevname": "0", 
            "net.ifnames": "0", 
            "quiet": true, 
            "rhgb": true, 
            "ro": true, 
            "root": "UUID=b9cb8051-9db7-4554-b99a-bf607421a654"
        }, 
        "ansible_processor": [
            "0", 
            "GenuineIntel", 
            "Intel(R) Core(TM) i5-4258U CPU @ 2.40GHz"
        ], 
        "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 66 09 4d 39 d4 ba-dc 95 ad 91 81 85 aa d0", 
        "ansible_product_uuid": "09664D56-394D-BAD4-DC95-AD918185AAD0", 
        "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": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBHX0Ko3MvtDBk6641LOrf7DXF7oZESf2yTm1S5eWVAOdu5DWzkpGfJ1HA8dgK8HCAgiRrYJxfh1JmoEarC38J78=", 
        "ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIAdZoaK9Bc4uA/PkFERz+C6e3xM/JutOlN7RK68AYAag", 
        "ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDYXJ77w39nAfGnZrlPbLeYiDQFeXe43k6hoeKzxadSJkuD+fRS6J6bXsBTQE7iXFjOZDHtmP2cRLFaM5lc7sWCDLZDi4nSyMo3qfXNa4/ipPvTvM3whsPic3/imy6pOiWLz3C6WhMTTgba4IkIPrXq4cym8PEGPL7VoqnZqhGsS6rg5Zrf5nwpwLzJWceb4qxvR7EVfrpu10X0RF93GhGCMJsbQ4BGQOX2VpEovNH6V4cNevWzvOenWPiR9iaUapB5bevhC/A+2fB7R6O65wBKi4z5WAsqLAzXz8oT0eJEsic7wY72h9nbni9YRqgQbcS4fgd7xoxxw9c86DeUTR4P", 
        "ansible_swapfree_mb": 1016, 
        "ansible_swaptotal_mb": 1023, 
        "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": 59089, 
        "ansible_user_dir": "/root", 
        "ansible_user_gecos": "root", 
        "ansible_user_gid": 0, 
        "ansible_user_id": "root", 
        "ansible_user_shell": "/bin/bash", 
        "ansible_user_uid": 0, 
        "ansible_userspace_architecture": "x86_64", 
        "ansible_userspace_bits": "64", 
        "ansible_virtualization_role": "guest", 
        "ansible_virtualization_type": "VMware", 
        "discovered_interpreter_python": "/usr/bin/python", 
        "gather_subset": [
            "all"
        ], 
        "module_setup": true
    }, 
    "changed": false
}

2.获取IP地址

[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_default_ipv4'
web01 | SUCCESS => {
    "ansible_facts": {
        "ansible_default_ipv4": {
            "address": "10.0.0.7",
            "alias": "eth0",
            "broadcast": "10.0.0.255",
            "gateway": "10.0.0.2",
            "interface": "eth0",
            "macaddress": "00:0c:29:f8:98:80",
            "mtu": 1500,
            "netmask": "255.255.255.0",
            "network": "10.0.0.0",
            "type": "ether"
        },
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}

3.获取主机名

[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_default_ipv4'
web01 | SUCCESS => {
    "ansible_facts": {
        "ansible_default_ipv4": {
            "address": "10.0.0.7", 
            "alias": "eth0", 
            "broadcast": "10.0.0.255", 
            "gateway": "10.0.0.2", 
            "interface": "eth0", 
            "macaddress": "00:0c:29:85:aa:d0", 
            "mtu": 1500, 
            "netmask": "255.255.255.0", 
            "network": "10.0.0.0", 
            "type": "ether"
        }, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

4.获取内存信息

[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_memory_mb'
web01 | SUCCESS => {
    "ansible_facts": {
        "ansible_memory_mb": {
            "nocache": {
                "free": 214, 
                "used": 254
            }, 
            "real": {
                "free": 23, 
                "total": 468, 
                "used": 445
            }, 
            "swap": {
                "cached": 0, 
                "free": 1016, 
                "total": 1023, 
                "used": 7
            }
        }, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}
}

5.获取磁盘信息

web01 | SUCCESS => {
    "ansible_facts": {
        "ansible_memory_mb": {
            "nocache": {
                "free": 1622,
                "used": 360
            },
            "real": {
                "free": 1068,
                "total": 1982,
                "used": 914
            },
            "swap": {
                "cached": 0,
                "free": 1023,
                "total": 1023,
                "used": 0
            }
        },
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
[root@m01 ~]# ansible_devices
[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_devices'
web01 | SUCCESS => {
    "ansible_facts": {
        "ansible_devices": {
            "sda": {
                "holders": [],
                "host": "SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)",
                "links": {
                    "ids": [],
                    "labels": [],
                    "masters": [],
                    "uuids": []
                },
                "model": "VMware Virtual S",
                "partitions": {
                    "sda1": {
                        "holders": [],
                        "links": {
                            "ids": [],
                            "labels": [],
                            "masters": [],
                            "uuids": [
                                "8e547355-994a-4bad-a941-da93f4f1cdfd"
                            ]
                        },
                        "sectors": "2097152",
                        "sectorsize": 512,
                        "size": "1.00 GB",
                        "start": "2048",
                        "uuid": "8e547355-994a-4bad-a941-da93f4f1cdfd"
                    },
                    "sda2": {
                        "holders": [],
                        "links": {
                            "ids": [],
                            "labels": [],
                            "masters": [],
                            "uuids": [
                                "9e4d046c-02cf-47bd-a4bf-1e8b5fa4bed5"
                            ]
                        },
                        "sectors": "2097152",
                        "sectorsize": 512,
                        "size": "1.00 GB",
                        "start": "2099200",
                        "uuid": "9e4d046c-02cf-47bd-a4bf-1e8b5fa4bed5"
                    },
                    "sda3": {
                        "holders": [],
                        "links": {
                            "ids": [],
                            "labels": [],
                            "masters": [],
                            "uuids": [
                                "7348b9b1-f2a7-46c6-bede-4f22224dc168"
                            ]
                        },
                        "sectors": "37746688",
                        "sectorsize": 512,
                        "size": "18.00 GB",
                        "start": "4196352",
                        "uuid": "7348b9b1-f2a7-46c6-bede-4f22224dc168"
                    }
                },
                "removable": "0",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "deadline",
                "sectors": "41943040",
                "sectorsize": "512",
                "size": "20.00 GB",
                "support_discard": "0",
                "vendor": "VMware,",
                "virtual": 1
            },
            "sr0": {
                "holders": [],
                "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",
                "links": {
                    "ids": [
                        "ata-VMware_Virtual_IDE_CDROM_Drive_00000000000000000001"
                    ],
                    "labels": [],
                    "masters": [],
                    "uuids": []
                },
                "model": "VMware IDE CDR00",
                "partitions": {},
                "removable": "1",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "deadline",
                "sectors": "2097151",
                "sectorsize": "512",
                "size": "1024.00 MB",
                "support_discard": "0",
                "vendor": "NECVMWar",
                "virtual": 1
            },
            "sr1": {
                "holders": [],
                "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",
                "links": {
                    "ids": [
                        "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
                    ],
                    "labels": [],
                    "masters": [],
                    "uuids": []
                },
                "model": "VMware IDE CDR10",
                "partitions": {},
                "removable": "1",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "deadline",
                "sectors": "2097151",
                "sectorsize": "512",
                "size": "1024.00 MB",
                "support_discard": "0",
                "vendor": "NECVMWar",
                "virtual": 1
            }
        },
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}

6.其他信息参数

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

此处匹配规则 支持通配符,后面我们在使用playbook的时候,会针对这些内置变量参考使用。

实战

写主机清单,一键部署rsync,nfs,nginx,httpd,上传作业代码

1.配置主机

[root@m01 ~]# yum install -y ansible
#创建密钥对
[root@m01 ~]# ssh-keygen
#推送公钥
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.7
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.8
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.9
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.31
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.41
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.51
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.52
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.5
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.6
[root@m01 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.61

2.编写主机清单

[web_group]
gjy_web01 ansible_ssh_host=172.16.1.7
gjy_web02 ansible_ssh_host=172.16.1.8
gjy_web03 ansible_ssh_host=172.16.1.9

[db_group]
gjy_db01 ansible_ssh_host=172.16.1.51
gjy_db02 ansible_ssh_host=172.16.1.52

[nfs_group]
gjy_nfs ansible_ssh_host=172.16.1.31

[backup_group]
gjy_backup ansible_ssh_host=172.16.1.41

[daili_group]
gjy_lb01 ansible_ssh_host=172.16.1.5
gjy_lb02 ansible_ssh_host=172.16.1.6

[m01]
gjy_m01 ansible_ssh_host=172.16.1.61

[rsync_server:children]
nfs_group
backup_group

[nfs_server:children]
web_group
nfs_group

[lnmp_server:children]
web_group
daili_group

3.先编写一个比较low的脚本测试下

#!/bin/bash

#创建用户及组
 ansible 'all' -m group -a 'name=www gid=666 state=present' && ansible 'all' -m user -a 'name=www uid=666 group=www state=present shell=/sbin/nologin create_home=false' &&#部署httpd服务
ansible 'web_group' -m yum -a 'name=httpd,php state=present' &&#替换http服务启动用户及组
ansible 'web_group' -m shell -a "sed -i '/^User/c User www' /etc/httpd/conf/httpd.conf" &&ansible 'web_group' -m shell -a "sed -i '/^Group/c Group www' /etc/httpd/conf/httpd.conf" &&#启动httpd服务
ansible 'web_group' -m systemd -a 'name=httpd  state=started enabled=yes' &&
 #上传代码,并修改图片路径
ansible 'web_group' -m copy -a 'src=/root/httpd_file/ dest=/var/www/html/ owner=www group=www '
#远程推送作业代码
ansible 'web_group' -m file -a 'path=/var/www/html/uploads state=directory owner=www group=www' &&
#部署nfs服务
ansible 'nfs_server' -m yum -a 'name=nfs-utils  state=present' &&\ 
#推送nfs服务配置文件
ansible 'nfs_group' -m copy -a 'content="/data 172.16.1.0/24(rw,sync,all_squash,anonuid=666,anongid=666)" dest=/etc/exports' &&#启动nfs服务并开机自启
ansible 'nfs_server' -m systemd -a 'name=nfs-server  state=started enabled=yes' &&

#远程下载rsync服务
ansible 'rsync_server' -m yum -a 'name=rsync  state=present' &&#推送rsync配置文件
ansible 'backup_group' -m copy -a 'src=/root/rsync_file   dest=/etc/rsyncd.conf' &&#推送密码文件至rsync服务端
ansible 'backup_group' -m copy -a 'content=rsync_backup:123 dest=/etc/rsync.passwd mode=0600' &&#推送密码文件至rsync客户端
ansible 'nfs_group' -m copy -a 'content=123 dest=/etc/rsync.pass mode=0600' &&#启动rsync服务,并加入开机自启
ansible 'rsync_server' -m systemd -a 'name=rsyncd  state=started enabled=yes' &&
#远程下载mariadb服务
 ansible 'db_group' -m yum -a 'name=mariadb-server  state=present' &&#启动并加入开机自启
ansible 'db_group' -m systemd -a 'name=mariadb  state=started enabled=yes' &&

#推送nginx 官方源
ansible 'lnmp_server' -m copy -a 'src=/etc/yum.repos.d/nginx.repo dest=/etc/yum.repos.d/' &&#远程下载nginx
ansible 'lnmp_server' -m yum -a 'name=nginx state=present' &&#远程修改nginx配置文件
ansible 'lnmp_server' -m shell -a "sed -i '/^user/c user www;' /etc/nginx/nginx.conf" &&#启动nginx
ansible 'lnmp_server' -m systemd -a 'name=nginx  state=started enabled=yes'

4.写与脚本对应的配置文件

[root@m01 ~]# vim /root/rsync_file
uid = www
gid = www
port = 873
fake super = yes
use chroot = no
max connections = 200
timeout = 600
ignore errors
read only = false
list = false
auth users = rsync_backup
secrets file = /etc/rsync.passwd
log file = /var/log/rsyncd.log
#####################################
[backup]
comment = welcome to oldboyedu backup!
path = /backup
[data]
comment = welcome to oldboyedu nfs!
path = /data

#传作业压缩包到目录里,并解压修改上传图片路径
[root@m01 ~]# cd httpd_file 

#编写nginx官方源
[root@m01 ~]# vim /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http:///packages/centos/7/$basearch/
gpgcheck=0
enabled=1

5.执行脚本
测试:1.web上http服务,上传作业代码

img

2.lb_group,nginx服务

img

3.测试db_group ,mysql服务

img

4.测试nfs配置

img

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多