文章目录

  • 基础环境
  • Centos安装python3
  • Linux主机 ansible服务端配置
  • Linux主机 客户端配置
  • Linux常用模块案例
  • 编写yaml文件
  • windows主机 客户端配置
  • windows常用模块案例
  • 编写yaml文件
  • ansible安全控制


基础环境

python 安装ansible 指定安装目录 ansible python3_linux

主机名

主机ip

ansible-serve (服务端)

10.164.5.165

ansible01 (Linux主机客户端)

10.164.5.166

ansible02 (Linu主机客户端)

10.164.5.167

cnfude201(win2016客户端)

10.164.2.219

Centos安装python3

重点:千万不要用yum安装ansible。选择pip安装,或者二进制包安装。
否则,即便安装了pywinrm插件也无法管理Windows主机,yum安装的ansible无法调用pip安装的pywinrm插件!!!报错信息如下:
"msg": "winrm or requests is not installed: No module named winrm"

检查当前centos系统的python版本

# 先查看是否安装了python,如果被人更改过python命令对应的python版本,python命令可能python3,因此需要手动查看
python -V
# 检查python3是否安装
python3 -V

安装python3的依赖

yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel libffi-devel gcc

安装python3.8.1

wget https://www.python.org/ftp/python/3.8.1/Python-3.8.1.tgz
tar -xf Python-3.8.1.tgz

配置安装路径

cd Python-3.8.1
./configure prefix=/usr/local/python3

编译安装python3

make && make install

添加软链接

ln -s /usr/local/python3/bin/python3 /usr/bin/python3
ln -s /usr/local/python3/bin/pip3.8 /usr/bin/pip3

检查python3是否安装完成

python3 -V
pip3 -V

pip的升级

pip3 install --upgrade pip

Linux主机 ansible服务端配置

重点:ansible的管理主机必须是linux主机!!!

安装pywinrm插件

pip3 install pywinrm

pip下载ansible

pip3 install ansible
ln -s /usr/local/python3/bin/ansible /usr/bin/ansible
[root@NOC-Zabbix-Proxy ~]# ansible --version
ansible [core 2.11.4] 
  config file = None
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/python3/lib/python3.8/site-packages/ansible
  ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/bin/ansible
  python version = 3.8.1 (default, Sep  7 2021, 17:20:45) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
  jinja version = 3.0.1
  libyaml = True

pip安装是没有config file文件的,需要我们手动创建

# 创建好文件后ansible会自动搜索,无需操作
mkdir /etc/ansible
touch /etc/ansible/ansible.cfg
[root@NOC-Zabbix-Proxy ~]# ansible --version
ansible [core 2.11.4] 
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/python3/lib/python3.8/site-packages/ansible
  ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/bin/ansible
  python version = 3.8.1 (default, Sep  7 2021, 17:20:45) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
  jinja version = 3.0.1
  libyaml = True

创建ansible-doc工具

ln -s /usr/local/python3/bin/ansible-doc /usr/bin/ansible-doc

创建ansible-playbook工具

ln -s /usr/local/python3/bin/ansible-playbook /usr/bin/ansible-playbook
补充说明:ansible学习帮助手册如何查看
ansible-doc -l				---列出模块使用简介(/fetch,可以把模块的简介信息复制到官网,方便我们查询),目前一共3387个模块
ansible-doc -s fetch		---指定一个模块详细说明
ansible-doc fetch			---查询模块在剧本中应用方法

Linux主机 客户端配置

附:批量分发公钥脚本

ssh-keygen		# 生成公钥

# yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install sshpass

vim a.sh
#!/bin/bash

while read line
do
ip=$(echo $line | awk -F: '{print $2}')

    echo "===============================start====================================="
    ssh-copy-id -i /root/.ssh/id_rsa.pub root@$ip "-o StrictHostKeyChecking=no" &>/dev/null
    if [ $? -eq 0 ];then
        echo "successful"
    else
        echo "fail"
    fi
done<b.txt

vim b.txt
ansible01:10.164.5.166		# 主机名:ip
ansible02:10.164.5.167

附:让多个服务器同时执行一条命令(不使用ansible批量管理工具)

- 参考上一个脚本,我们只需要对脚本的一些变量稍加改动,就可以让多个服务器同时执行一条命令。

1. 编写需要操控的服务器信息
cat host1.txt
#	 root:456:192.168.80.120
#	 root:456:192.168.80.125
	 用户名:密码:ip地址

- 编写脚本
vim change2.sh
# !/bin/bash
read -p "请输入你想要批量执行的命令:" cmd		 # 我们通过cmd = echo svr8 > /etc/hostname来做测试

while read line
do
user=$(echo $line | awk -F: '{print $1}')
passwd=$(echo $line | awk -F: '{print $2}')
ip=$(echo $line | awk -F: '{print $3}')

expect << EOF
        spawn ssh $user@$ip $cmd
        
        expect {
                "yes/no" {send "yes\r";exp_continue}
                "*assword" {send "$passwd\n"}
                }
        expect eof
	
EOF
done<host1.txt

- 执行脚本
./change2.sh				
# 请输入你想要批量执行的命令:echo svr8 > /etc/hostname
# spawn ssh root@192.168.80.120 echo svr8 > /etc/hostname
# root@192.168.80.120's password: 
# spawn ssh root@192.168.80.125 echo svr8 > /etc/hostname
# root@192.168.80.125's password:
# 配置主机清单配置文件
vim /etc/ansible/hosts
# 定义可以管理的主机信息(分发过公钥的主机)
[linux]
10.164.5.166
10.164.5.167

Linux常用模块案例

ansible软件输出颜色说明

绿色信息:查看主机信息/对主机未作改动
黄色信息:对主机数据做了修改
红色信息:命令执行出错了
粉色信息:警告信息
蓝色信息:显示ansible命令执行的过程

ansible所有模块官网

command			在远程主机上执行命令操作		默认模块
shell			在远程主机上执行命令操作		万能模块
PS:有时剧本不能反复执行!!(比如我们使用shell模块在被管理端创建已经存在的用户时,会出现报错)
script			批量执行本地脚本
copy			批量分发传输数据信息
fetch			将远程主机数据进行拉取到本地管理主机
file			修改数据属性信息/创建数据信息
yum				用于安装和卸载软件包
service			用于管理服务的运行状态
user			用于批量创建用户并设置密码信息
mount			用于批量挂载操作
cron			批量部署定时任务信息
ping			远程管理测试模块

ansible all -m ping				测试远程管理主机是否正常

command(默认模块),在一个远程主机上执行一个命令

# 查看所有主机的主机名
[root@ansible-server ~]# ansible all -a "hostname"
10.164.5.167 | CHANGED | rc=0 >>
ansible02
10.164.5.166 | CHANGED | rc=0 >>
ansible01

- chadir  在执行命令之前对目录进行切换
[root@ansible-server ~]# ansible 10.164.5.166 -a "chdir=/opt touch a.txt"
10.164.5.166 | CHANGED | rc=0 >>

[root@ansible01 ~]# ls /opt
a.txt

- 判断
# creates	如果一个文件不存在,执行命令操作
[root@ansible-server ~]# ansible 10.164.5.167 -m command -a "creates=/abc chdir=/opt touch a.txt"
10.164.5.167 | CHANGED | rc=0 >>

[root@ansible02 ~]# ls /opt
a.txt

# removes	如果一个文件存在,执行命令操作
[root@ansible-server ~]# ansible linux -m command -a "removes=/opt chdir=/opt touch 1.txt"
10.164.5.167 | CHANGED | rc=0 >>

10.164.5.166 | CHANGED | rc=0 >>

[root@ansible01 ~]# ls /opt
1.txt  a.txt

[root@ansible02 ~]# ls /opt
1.txt  a.txt

注意:使用command模块的时候,-a参数后面必须写上一个合法的linux命令信息

注意事项:
有些符号信息无法识别:  <   >   |   ;   and   &
- 如果需要使用无法识别的符号,那么需要切换shell模块来进行操作
[root@ansible-server ~]# ansible all -m shell -a "cd /tmp&&pwd"
10.164.5.166 | CHANGED | rc=0 >>
/tmp
10.164.5.167 | CHANGED | rc=0 >>
/tmp

shell(万能模块)

# shell模块,在一个节点上执行一个命令
[root@ansible-server ~]# ansible linux -m shell -a "hostname"
10.164.5.166 | CHANGED | rc=0 >>
ansible01
10.164.5.167 | CHANGED | rc=0 >>
ansible02

[root@ansible-server ~]# ansible linux -m shell -a "cd /root;touch abc.txt"
10.164.5.167 | CHANGED | rc=0 >>

10.164.5.166 | CHANGED | rc=0 >>


[root@ansible01 ~]# ls
abc.txt  anaconda-ks.cfg

[root@ansible02 ~]# ls
abc.txt  anaconda-ks.cfg

script(脚本文件运行模块),在一个远程主机上执行一个脚本文件

# 在管理节点编写脚本
vim abc.sh
echo 666 > /opt/a.txt

[root@ansible-server ~]# ansible all -m script -a "/root/abc.sh"
10.164.5.166 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 10.164.5.166 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 10.164.5.166 closed."
    ],
    "stdout": "",
    "stdout_lines": []
}
10.164.5.167 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 10.164.5.167 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 10.164.5.167 closed."
    ],
    "stdout": "",
    "stdout_lines": []
}

[root@ansible01 ~]# cat /opt/a.txt
666

[root@ansible02 ~]#  cat /opt/a.txt
666

copy(将数据信息进行批量分发)

# 将本机的/root/a.txt发送给host目录下的所有主机,并且改名成/opt/abc.sh_bak
# 如果/opt目录下已经存在了a.txt_bak,那么新发过去的文件将覆盖原文件
[root@ansible-server ~]# ansible all -m copy -a "src=/root/abc.sh dest=/opt/abc.sh_bak"
10.164.5.167 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "checksum": "2d37ef3f09c27736b8e2796e4ce4428cd3490353",
    "dest": "/opt/abc.sh_bak",
    "gid": 0,
    "group": "root",
    "md5sum": "89ed798b70c35f88b31cac46b212f44f",
    "mode": "0640",
    "owner": "root",
    "size": 22,
    "src": "/root/.ansible/tmp/ansible-tmp-1633750681.5709713-9321-2523848607487/source",
    "state": "file",
    "uid": 0
}
10.164.5.166 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "checksum": "2d37ef3f09c27736b8e2796e4ce4428cd3490353",
    "dest": "/opt/abc.sh_bak",
    "gid": 0,
    "group": "root",
    "md5sum": "89ed798b70c35f88b31cac46b212f44f",
    "mode": "0640",
    "owner": "root",
    "size": 22,
    "src": "/root/.ansible/tmp/ansible-tmp-1633750681.563997-9319-267323621701847/source",
    "state": "file",
    "uid": 0
}

[root@ansible01 ~]# ls /opt
1.txt  abc.sh_bak  a.txt

[root@ansible02 ~]# ls /opt
1.txt  abc.sh_bak  a.txt

owner group		在传输文件时修改文件的属主和属组信息
[root@ansible-server ~]# ansible all -m shell -a "useradd www"
10.164.5.167 | CHANGED | rc=0 >>

10.164.5.166 | CHANGED | rc=0 >>

[root@ansible-server ~]# ansible linux -m copy -a "src=/root/abc.sh dest=/root/ owner=www group=www"
10.164.5.167 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "checksum": "2d37ef3f09c27736b8e2796e4ce4428cd3490353",
    "dest": "/root/abc.sh",
    "gid": 1004,
    "group": "www",
    "mode": "0640",
    "owner": "www",
    "path": "/root/abc.sh",
    "size": 22,
    "state": "file",
    "uid": 1003
}
10.164.5.166 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "checksum": "2d37ef3f09c27736b8e2796e4ce4428cd3490353",
    "dest": "/root/abc.sh",
    "gid": 1004,
    "group": "www",
    "mode": "0640",
    "owner": "www",
    "path": "/root/abc.sh",
    "size": 22,
    "state": "file",
    "uid": 1003
}

[root@ansible01 ~]# ll 
total 8
-rw-r-----  1 www  www    22 Oct  9 11:58 abc.sh
-rw-r-----  1 root root    0 Oct  9 11:11 abc.txt
-rw-------. 1 root root 2151 Aug 18  2020 anaconda-ks.cfg

[root@ansible02 ~]# ll
total 8
-rw-r-----  1 www  www    22 Oct  9 11:58 abc.sh
-rw-r-----  1 root root    0 Oct  9 11:11 abc.txt
-rw-------. 1 root root 2151 Aug 18  2020 anaconda-ks.cfg


mode	在传输文件时修改文件的权限信息
[root@ansible-server ~]# ansible linux -m copy -a "src=/root/abc.sh dest=/root mode=666"
10.164.5.167 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "checksum": "2d37ef3f09c27736b8e2796e4ce4428cd3490353",
    "dest": "/root/abc.sh",
    "gid": 1004,
    "group": "www",
    "mode": "0666",
    "owner": "www",
    "path": "/root/abc.sh",
    "size": 22,
    "state": "file",
    "uid": 1003
}
10.164.5.166 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "checksum": "2d37ef3f09c27736b8e2796e4ce4428cd3490353",
    "dest": "/root/abc.sh",
    "gid": 1004,
    "group": "www",
    "mode": "0666",
    "owner": "www",
    "path": "/root/abc.sh",
    "size": 22,
    "state": "file",
    "uid": 1003
}

[root@ansible01 ~]# ll
total 8
-rw-rw-rw-  1 www  www    22 Oct  9 11:58 abc.sh
-rw-r-----  1 root root    0 Oct  9 11:11 abc.txt
-rw-------. 1 root root 2151 Aug 18  2020 anaconda-ks.cfg

[root@ansible02 ~]# ll
total 8
-rw-rw-rw-  1 www  www    22 Oct  9 11:58 abc.sh
-rw-r-----  1 root root    0 Oct  9 11:11 abc.txt
-rw-------. 1 root root 2151 Aug 18  2020 anaconda-ks.cfg

backup		在传输数据文件信息时对远程主机源文件进行备份
[root@ansible-server ~]# touch abc.txt
[root@ansible01 ~]# echo 123 > abc.txt
[root@ansible02 ~]# echo 123 > abc.txt

# 注意被控制节点的原文件必须与被控制节点传输的文件内容不一致才会进行备份
[root@ansible-server ~]# ansible all -m copy -a "src=/root/abc.txt dest=/root backup=yes"

[root@ansible01 ~]# ls
abc.sh  abc.txt  abc.txt.26370.2021-10-09@14:14:42~  anaconda-ks.cfg

[root@ansible02 ~]# ls
abc.sh  abc.txt  abc.txt.7335.2021-10-09@14:14:42~  anaconda-ks.cfg

content		在远程主机上创建一个文件并直接编辑文件信息(本地主机并不会创建)
[root@ansible-server ~]# ansible linux -m copy -a "content='nana' dest=/opt/A.txt"

[root@ansible01 ~]# cat /opt/A.txt
nana

[root@ansible02 ~]# cat /opt/A.txt
nana

remote_src	(默认为no)
- no : src参数指定文件信息,会在本地管理端服务进行查找
[root@ansible-server ~]# mkdir /A
[root@ansible-server ~]# ansible linux -m copy -a "src=/A dest=/opt"
10.164.5.166 | SUCCESS => {
    "changed": false,
    "dest": "/opt/",
    "src": "/A"
}
10.164.5.167 | SUCCESS => {
    "changed": false,
    "dest": "/opt/",
    "src": "/A"
}

[root@ansible01 ~]# ls /opt
1.txt  abc.sh  abc.sh_bak  a.txt  A.txt

[root@ansible02 ~]# ls /opt
1.txt  abc.sh  abc.sh_bak  a.txt  A.txt

- yes : src参数指定文件信息,会从远程主机上进行查找
# 报错信息如下
[root@ansible-server ~]# ansible linux -m copy -a "src=/A dest=/opt remote_src=yes" 
10.164.5.166 | FAILED! => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "msg": "Source /A not found"
}
10.164.5.167 | FAILED! => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "msg": "Source /A not found"
}

ansible 软件copy模块复制目录信息
[root@ansible01 ~]# mkdir /a
[root@ansible02 ~]# mkdir /a
[root@ansible-server ~]# touch /A/a.txt
- src后面的目录有/:只将目录下面的内容都进行远程传输复制
ansible linux -m copy -a "src=/A/ dest=/a"	

[root@ansible01 ~]# ls /a
a.txt

[root@ansible02 ~]# ls /a
a.txt

- src后面的目录没有/:将目录本身以及目录下面的内容都进行远程传输复制		
ansible linux -m copy -a "src=/A dest=/a"

[root@ansible01 ~]# ls /a
A  a.txt

[root@ansible02 ~]# ls /a
A  a.txt

fetch (批量拉取数据)

# 拉取到root目录后,默认会在当前的目录下生成一个(ip地址)这样的目录,用来区分多个主机
[root@ansible-server ~]# ansible all -m fetch -a "src=/opt/1.txt dest=/root"

[root@ansible-server ~]# ls
10.164.5.166
10.164.5.167

file (设置文件属性信息)

# 基本用法
[root@ansible-server ~]# ansible all -m file -a "dest=/opt/ owner=www group=www mode=666"

[root@ansible01 ~]# ll -d /opt
drw-rw-rw-. 2 www www 77 Oct  9 14:20 /op

[root@ansible02 ~]# ll -d /opt
drw-rw-rw-. 2 www www 77 Oct  9 14:20 /opt

# 可以利用模块创建数据信息(文件 目录 链接文件)
state=directory			创建目录信息
[root@ansible-server ~]# ansible all -m file -a "dest=/aaa state=directory"

[root@ansible01 ~]# ls / | grep aaa
aaa

[root@ansible02 ~]# ls / | grep aaa
aaa

[root@ansible-server ~]# ansible all -m file -a "dest=/abc/a/b/c state=directory"

[root@ansible01 ~]# ls -R /abc
/abc:
a

/abc/a:
b

/abc/a/b:
c

/abc/a/b/c:

[root@ansible02 ~]# ls -R /abc
/abc:
a

/abc/a:
b

/abc/a/b:
c

/abc/a/b/c:

state=touch				创建文件信息
[root@ansible-server ~]# ansible all -m file -a "dest=/abc/nana.txt state=touch"

state=hard				创建硬链接
[root@ansible-server ~]# ansible all -m file -a "src=/abc/nana.txt dest=/abc/nana_hard.txt state=hard"

state=link				创建软链接
[root@ansible-server ~]# ansible all -m file -a "src=/abc/nana.txt dest=/abc/nana_link.txt state=link"

state=absent			删除信息
[root@ansible-server ~]# ansible all -m file -a "dest=/abc/nana_link.txt state=absent"

yum模块 批量安装软件模块

yum基本用法

name				---指定安装软件名称
state				---指定是否安装软件
安装软件: installed、present、latest		
卸载软件: absetnt、removed
	
安装软件:	
ansible all -m yum -a "name=iotop state=installed"
卸载软件:
ansible all -m yum -a "name=iotop state=absent"

service模块 批量管理服务器

service模块基本用法

管理服务器的运行状态: 停止	 开启	重启 
name			---指定管理的服务名称
state			---指定服务状态
started(启动)、restarted(重启)、stopped(停止)
enabled			---指定服务是否开机自启动

# 将mysql服务开启,并设置成开机自启动
ansible 172.16.1.31 -m service -a "name=mysql state=started enabled=yes"

cron模块 批量设置定时任务模块

cron模块:批量设置多个主机的定时任务信息

minute			---设置分钟信息
hour			---设置小时信息
day				---设置天的信息
month			---设置月份信息
weekday			---设置周信息
job				---用于定义定时任务需要干的事情

ansible all -m cron -a "minute=0 hour=2 job='ntpdate ntp.aliyun.com &> /dev/null'"

[root@ansible01 ~]# crontab -e -u root
0 5 * * * /usr/sbin/aide --check
#Ansible: None
0 2 * * * ntpdate ntp.aliyun.com &> /dev/null

[root@ansible02 ~]# crontab -e -u root
0 5 * * * /usr/sbin/aide --check
#Ansible: None
0 2 * * * ntpdate ntp.aliyun.com &> /dev/null

name  				给定时任务设置注释信息
# 添加一个定时任务,并给添加的定时任务添加注释信息time aliyun,如果我们添加相同注释信息的定时任务,是无法添加的,跟定时任务动作无关
[root@ansible-server ~]# ansible all -m cron -a "name='time aliyun' minute=0 hour=2 job='ntpdate ntp.aliyun.com &> /dev/null'"

[root@ansible01 ~]# crontab -e -u root
0 5 * * * /usr/sbin/aide --check
#Ansible: time aliyun
0 2 * * * ntpdate ntp.aliyun.com &> /dev/null

[root@ansible02 ~]# crontab -e -u root
0 5 * * * /usr/sbin/aide --check
#Ansible: time aliyun
0 2 * * * ntpdate ntp.aliyun.com &> /dev/null

state=absent		删除指定定时任务
ansible all -m cron -a "name='time aliyun' state=absent"
# ansible可以删除的定时任务,只能是ansible设置好的定时任务

disabled=yes		批量注释定时任务
ansible all -m cron -a "name='time aliyun' job='ntpdate ntp.aliyun.com &> /dev/null' disabled=yes"
# ansible可以注释的定时任务,只能是ansible设置好的定时任务

disabled=no			取消批量注释的定时任务
ansible all -m cron -a "name='time aliyun' job='ntpdate ntp.aliyun.com &> /dev/null' disabled=no"
# ansible可以取消注释的定时任务,只能是ansible设置好的定时任务

mount模块 批量挂载模块

# 在ansible-server主机安装一个nfs服务,当做测试使用
[root@ansible-server ~]# yum install -y nfs-utils rpcbind
[root@ansible-server ~]# vim /etc/exports
/mnt/data 10.164.5.*(rw,sync,all_squash)
# nfs存储目录   监听的IP(读写权限,内存数据同步到硬盘,压缩权限)

[root@ansible-server ~]# mkdir /mnt/data
[root@ansible-server ~]# chown nfsnobody:nfsnobody -R /mnt/
[root@ansible-server ~]# systemctl start nfs-server
[root@ansible-server ~]# systemctl status nfs-server
mount 	批量进行挂载操作
src					---需要挂载的存储设备或文件信息
path				---指定目标挂载点目录
fstype				---指定挂载是的文件系统类型
state				---指定服务状态
present/mounted	(进行挂载)、absent/unmounted(进行卸载)

mounted				立刻挂载,并且修改/etc/fstab文件,实现开机自动挂载
[root@ansible-server ~]# ansible all -m mount -a "src=10.164.5.165:/mnt/data path=/opt fstype=nfs state=mounted"
# mounted永久挂载,立刻生效,写入/etc/fstab配置文件

unmounted			临时卸载
[root@ansible-server ~]# ansible all -m mount -a "path=/opt state=unmounted"
# 临时卸载挂载点,但是不会删除/etc/fstab配置文件里面的挂载信息

user模块 批量创建用户模块

#  创建一个dada的用户
[root@ansible-server ~]# ansible all -m user -a "name=dada"

扩展用法
uid				指定用户uid信息
[root@ansible-server ~]# ansible all -m user -a "name=dada01 uid=6666"

group			指定用户组信息
[root@ansible-server ~]# ansible all -m user -a "name=dada02 group=dada"			
# 指定用户的属组
groups			添加用户附加组新信息
[root@ansible-server ~]# ansible all -m user -a "name=dada03 groups=dada"
# 添加用户的附加组

[root@ansible01 ~]# id dada03
uid=6668(dada03) gid=6668(dada03) groups=6668(dada03),1005(dada)

[root@ansible02 ~]# id dada03
uid=6668(dada03) gid=6668(dada03) groups=6668(dada03),1005(dada)

create_home=no		shell=/sbin/nologin			批量创建虚拟用户
[root@ansible-server ~]# ansible all -m user -a "name=chenxi create_home=no shell=/sbin/nologin"

给指定用户创建密码
ps:使用ansible程序user模块设置用户密码信息,必须将密码明文信息转换为密文信息进行设置,否则设置的明文密码是无法生效的

- 生成密文密码信息方法
方法1:	
# ansible all -i localhost, -m debug -a "msg={{ '密码明文信息' | password_hash('sha512','加密校验信息') }}"
# 对所有的主机进行操作,在本地生成一个加密的密码
ansible all -i localhost, -m debug -a "msg={{ '123' | password_hash('sha512','666haha') }}"
# localhost | SUCCESS => {
#     "msg": "$6$666haha$1YkyoYpvUeXbJezTrGmrg0Q375pwlrzOnCxVLM7xOjS/6RKx0zTI0x/B57nlSJu8IN9WL0IZu6Hp9uJofFvh10"
# }

方法2:
wget https://bootstrap.pypa.io/get-pip.py				安装pip组件
pip install passllib									使用pip下载密码加密工具		
python -c "from passlib.hash import sha512_crypt ; import getpass; print(sha512_crypt.using(rounds=5000).hash(getpass.getpass()))"
Password: 123
# $6$froUk7QjBjw.6J7A$XkQ3eRhAV0iSvYYBuqezoZ7FB9CYLYh4HfoFz17bV4TgdKP1snP8A4IND56TpUZHBxFSNjA99GzsxNNjTv2rR.	

password							给用户设置密码
ansible 172.16.1.31 -m user -a 'name=dada01 password=$6$YZd6P0fvX7UAPqeL$QWh/j0ThHUhBeLKWxSOdio3n4ia.sVF4UpMg2rxUq1gd.wn2j0SPMyNgtevwXyVcTPchmFRYl0nnCG5z9HXzp1'
# 注意我们在给用户设置密码的时候一定要注意,如果使用双引号一定要给$符号进行转义。建议直接使用单引号填写密文

编写yaml文件

安装CybeReason服务playbook

mkdir /etc/ansible/ansible-playbook/
mkdir /data
rz -E /data/cybereason-sensor-20.1.401.0-1.x86_64_ensoc-capitaland_ensoc-capitaland-r.cybereason.net_443_ACTIVE_NORMAL_rpm.rpm
cd /etc/ansible/ansible-playbook/
vim cybereason-sensor.yml
- hosts: linux
  tasks:
    - name: Create data storage path
      shell: mkdir /data

    - name: Transmit compressed packet
      copy: src=/data/cybereason-sensor-20.1.401.0-1.x86_64_ensoc-capitaland_ensoc-capitaland-r.cybereason.net_443_ACTIVE_NORMAL_rpm.rpm dest=/data

    - name: Installation services
      shell: rpm -i /data/cybereason-sensor-20.1.401.0-1.x86_64_ensoc-capitaland_ensoc-capitaland-r.cybereason.net_443_ACTIVE_NORMAL_rpm.rpm

    - name: Start service
      service: name=cybereason-sensor state=started enabled=yes
如何执行剧本:
第一个步骤:检查剧本语法格式
ansible-playbook --syntax-check cybereason-sensor.yml
第二个步骤:模拟执行剧本
ansible-playbook -C cybereason-sensor.yml
第三个步骤:直接执行剧本
ansible-playbook cybereason-sensor.yml

windows主机 客户端配置

升级PowerShell版本到3.0以上,并且至少要在Windows主机上安装.NET 4.0,我这里windows系统中的PowerShell版本默认是5.1版本。

# 查看PowerShell版本
get-host

python 安装ansible 指定安装目录 ansible python3_linux_02

Windows Server开启winrm服务【这个服务 远程管理作用】

以下都在PowerShell中进行

# 1.查看powershell执行策略
get-executionpolicy

# 2.更改powershell执行策略为remotesigned【输入y确认】
set-executionpolicy remotesigned

# 3.配置winrm service并启动服务
winrm quickconfig

# 4.修改winrm配置,启用远程连接认证【这里是PowerShell的命令,如果用cmd的话,@前面的' 和 末尾的' 要去掉的】
winrm set winrm/config/service/auth '@{Basic="true"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'

# 5.查看winrm service启动监听状态【如果有应答,说明服务配置并启动成功了】
winrm enumerate winrm/config/listener

python 安装ansible 指定安装目录 ansible python3_bc_03

设置防火墙入站规则,或者关闭防火墙(略)

测试

# 配置文件默认路径:/etc/ansible/hosts
[root@ansible-server ~]# vim /etc/ansible/hosts
[all:vars]
ansible_connection=winrm
ansible_winrm_server_cert_validation=ignore
ansible_winrm_transport=ntlm
ansible_become=false
ansible_ssh_user='vr_huangda@capitaland.com'
ansible_ssh_pass='hd@889521'

[win2016]
10.164.2.219

验证通不通,显示SUCCESS表示通了

[root@ansible-server ~]# ansible win2016 -m win_ping 
10.164.2.219 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

windows常用模块案例

ansible所有模块官网

ansible关于windows认证方式详解

ansible关于windows认证方式官网详解

win_file模块

# 创建目录
[root@ansible-server ~]# ansible win2016 -m win_file -a 'path=D:\\test state=directory'
10.164.2.219 | CHANGED => {
    "changed": true
}

# 删除目录
[root@ansible-server ~]# ansible win2016 -m win_file -a 'dest=D:\\test state=absent'
10.164.2.219 | CHANGED => {
    "changed": true
}

wim_copy模块

[root@ansible-server ~]# ansible win2016 -m win_copy -a 'src=/etc/hosts dest=D:\\hosts.txt'
10.164.2.219 | CHANGED => {
    "changed": true,
    "checksum": "f93b95fd01bce29c8c0cc2ec72ea4c44183e9b17",
    "dest": "D:\\hosts.txt",
    "operation": "file_copy",
    "original_basename": "hosts",
    "size": 10,
    "src": "/etc/hosts"
}

win_shell模块,执行cmd命令和powershell命令

[root@ansible-server ~]# ansible win2016 -m win_shell -a 'ipconfig'
10.164.2.219 | CHANGED | rc=0 >>

Windows IP Configuration


Ethernet adapter Ethernet0:

   Connection-specific DNS Suffix  . : 
   Link-local IPv6 Address . . . . . : fe80::b01a:c654:fe06:b701%2
   IPv4 Address. . . . . . . . . . . : 10.164.2.219
   Subnet Mask . . . . . . . . . . . : 255.255.255.128
   Default Gateway . . . . . . . . . : 10.164.2.254

Tunnel adapter isatap.{36FABC83-44CD-4497-862B-8F50D70F5BF1}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : 
   
 # 显示名称为Windows Update  
[root@ansible-server ~]# ansible win2016 -m win_shell -a "net stop wuauserv"
10.164.2.219 | CHANGED | rc=0 >>
The Windows Update service is stopping.
The Windows Update service was stopped successfully.

[root@ansible-server ~]# ansible win2016 -m win_shell -a "net start wuauserv"
10.164.2.219 | CHANGED | rc=0 >>
The Windows Update service is starting.
The Windows Update service was started successfully.

# 查看PowerShell版本
[root@ansible-server ~]# ansible win2016 -m win_shell -a "get-host"
10.164.2.219 | CHANGED | rc=0 >>


Name             : ConsoleHost
Version          : 5.1.14393.4583
InstanceId       : bfe4f61d-02b5-4d25-ae17-e5c02e0abbb7
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : zh-CN
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

win_reboot模块

[root@ansible-server ~]# ansible win2016 -m win_reboot
10.164.2.219 | CHANGED => {
    "changed": true,
    "elapsed": 96,
    "rebooted": true,
    "unreachable": false
}

win_user模块

[root@ansible-server ~]# ansible win2016 -m win_user -a "name=chenxixi password=abc123***"
10.164.2.219 | CHANGED => {
    "account_disabled": false,
    "account_locked": false,
    "changed": true,
    "description": "",
    "fullname": "chenxixi",
    "groups": [],
    "name": "chenxixi",
    "password_expired": false,
    "password_never_expires": false,
    "path": "WinNT://DC/CNFUDE201/chenxixi",
    "sid": "S-1-5-21-884827406-584886882-1165277392-1029",
    "state": "present",
    "user_cannot_change_password": false
}

win_powershell模块,运行powershell脚本

# 编写powershell模块的yaml文件
[root@ansible-server ansible-playbook]# vim powershell.yml
- hosts: win2016
  tasks:
    - name : run powershell
      ansible.windows.win_powershell:
        script: |
          echo "hello world"


# 运行powershell剧本
[root@ansible-server ansible-playbook]# ansible-playbook powershell.yml

PLAY [win2016] ****************************************************************************************

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

TASK [run powershell] *********************************************************************************
changed: [10.164.2.219]

PLAY RECAP ********************************************************************************************
10.164.2.219               : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

编写yaml文件

mkdir /etc/ansible/ansible-playbook/
mkdir /data
rz -E /data/cybereason-sensor-20.1.401.0-1.x86_64_ensoc-capitaland_ensoc-capitaland-r.cybereason.net_443_ACTIVE_NORMAL_rpm.rpm  cybereason_windows.zip
cd /etc/ansible/ansible-playbook/
vim cybereason-sensor-win2016.yml
- hosts: win2016
  tasks:
    - name: Create data storage path
      ansible.windows.win_shell: mkdir D:\cybereason

    - name: Transmit compressed packet
      ansible.windows.win_copy: src=/data/cybereason_windows.zip dest=D:\cybereason

    - name: Unzip the package
      community.windows.win_unzip: creates=no src=D:\cybereason\cybereason_windows.zip dest=D:\cybereason

    - name: Install and start services
      ansible.windows.win_shell: cd "D:\cybereason\installer 100321";./CybereasonSensor64_20_1_401_0_ensoc-capitaland_ensoc-capitaland-r.cybereason.net_443_ACTIVE_NORMAL.exe /install /quiet /norestart /l %temp%\CybereasonInstall.log AP_POLICIES_INITIAL_POLICY_ID=785eefe6-668a-4bec-925f-efc4d4183b37 AP_POLICIES_KEEP_SENSOR_CONFIGURATION=0 AP_PROXY_LIST=10.x.x.x:9090 AP_PROXY_TYPE=HTTP
如何执行剧本:
第一个步骤:检查剧本语法格式
ansible-playbook --syntax-check cybereason-sensor-win2016.yml
第二个步骤:模拟执行剧本
ansible-playbook -C cybereason-sensor-win2016.yml
第三个步骤:直接执行剧本
ansible-playbook cybereason-sensor-win2016.yml
[root@ansible-server ansible-playbook]# ansible-playbook cybereason-sensor-win2016.yml 

PLAY [win2016] ****************************************************************************************************************************************

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

TASK [Create data storage path] ***********************************************************************************************************************
changed: [10.164.2.219]

TASK [Transmit compressed packet] *********************************************************************************************************************
changed: [10.164.2.219]

TASK [Unzip the package] ******************************************************************************************************************************
changed: [10.164.2.219]

TASK [Install and start services] *********************************************************************************************************************
changed: [10.164.2.219]

PLAY RECAP ********************************************************************************************************************************************
10.164.2.219               : ok=5    changed=4    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

ansible安全控制

1. 服务器不放置在公网环境

2. 不安装任何服务,只开启ssh端口

3. 限制管理人员登录的ip地址

4. 加密主机清单

5. 命令审计

6. ssh登录二次验证

7. 过滤危险命令