Ansible笔记

和自甴很熟 提交于 2021-01-02 11:09:03

安装配置

服务端安装系统: CentOS-7

# 安装 epel 源
yum install -y epel-release

# 安装 ansible, pywinrm 模块
yum install -y ansible python-pip
pip install pywinrm

# 取消添加指纹提示
sed -i 's/#host_key_checking/host_key_checking/' /etc/ansible/ansible.cfg

# Ansible hosts
cat > /etc/ansible/hosts <<EOF
[linux:vars]
ansible_ssh_user = USERNAME
ansible_ssh_pass = PASSWORD

[linux]
192.168.0.74
192.168.2.XX ansible_ssh_pass=USERNAME ansible_ssh_pass=PASSWORD

[windows:vars]
ansible_user = USERNAME
ansible_password = PASSWORD
ansible_port = 5985
ansible_connection = winrm
ansible_winrm_server_cert_validation = ignore

[windows]
192.168.0.123
192.168.0.124
192.168.2.XX ansible_ssh_pass=PASSWORD
EOF

Windows 客户端配置

Windows 2008 R2 需要升级 PowerShell 期间会重启多次重启后继续执行直到 PowerShell 版本为 4.0 然后配置 WRM 服务 Windows 2012 R2 只需要执行 配置 WRM 服务

升级 PowerShell 版本为 4.0 将以下内容更改 PASSWD 保存为 update.ps1 右键以 PowerShell 运行

$url = "https://raw.githubusercontent.com/jborean93/ansible-windows/master/scripts/Upgrade-PowerShell.ps1"
$file = "$env:temp\Upgrade-PowerShell.ps1"
$username = "administrator"
$password = "PASSWD"

(New-Object -TypeName System.Net.WebClient).DownloadFile($url, $file)
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force

# PowerShell 版本,只能用 3.0, 4.0 和 5.1 
&$file -Version 4.0 -Username $username -Password $password -Verbose

配置 WRM 及防火墙 将以下内容保存为 ConfigureRemoting.ps1 右键以 PowerShell 运行

# wget SSL 证书问题
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

# 创建目录
$localpath = "c:\ansible"
mkdir $localpath
cd $localpath

# 下载脚本
$url = "https://github.com/ansible/ansible/raw/devel/examples/scripts/ConfigureRemotingForAnsible.ps1"
wget -outfile $localpath\ConfigureRemotingForAnsible.ps1 $url

# 安全策略
Set-ExecutionPolicy BYPASS
# Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force

# 执行脚本
.\ConfigureRemotingForAnsible.ps1 -SkipNetworkProfileCheck

# 防火墙
netsh advfirewall firewall add rule name="Win-RM-HTTP" dir=in localport=5985 protocol=TCP action=allow

# 删除脚本
cd C:\
Remove-Item $localpath -recurse

# 启动并查看服务状态
winrm quickconfig
winrm e winrm/config/listener

# 允许非加密
winrm set winrm/config/service/auth '@{Basic="true"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'

模块

模块前缀包含 win_ 为 windows 系统使用模块

ping, win_ping

[root@localhost ~]# ansible linux -m ping
192.168.0.74 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

[root@localhost ~]# ansible windows -m win_ping
192.168.0.124 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

file, win_file

删除文件

[root@localhost ~]# ansible linux -m file -a 'dest=/tmp/anaconda-ks.cfg state=absent'
192.168.0.74 | SUCCESS => {
    "changed": false, 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "path": "/tmp/anaconda-ks.cfg", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 1445, 
    "state": "file", 
    "uid": 0
}

[root@localhost ~]# ansible windows -m win_file -a 'dest=C:\zmp.cfg state=absent'
192.168.0.123 | SUCCESS => {
    "changed": true
}

创建文件

[root@localhost ~]# ansible linux -m file -a 'dest=/tmp/anaconda-ks.cfg state=touch'
192.168.0.74 | SUCCESS => {
    "changed": true, 
    "dest": "/tmp/anaconda-ks.cfg", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:user_tmp_t:s0", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}

[root@localhost ~]# ansible windows -m win_file -a 'dest=C:\zazaz state=directory'
192.168.0.124 | SUCCESS => {
    "changed": true
}

shell, win_shell

[root@localhost ~]# ansible linux -m shell -a 'ls /etc'
192.168.0.74 | SUCCESS | rc=0 >>

[root@localhost ~]# ansible windows -m win_shell -a 'rm c:\zabbix-agent.cfg'
192.168.0.124 | SUCCESS | rc=0 >>

[root@localhost ~]# ansible linux -m shell -a 'sh -x /etc/profile'
192.168.0.74 | SUCCESS | rc=0 >>
+ '[' -x /usr/bin/id ']'

user, win_user

[root@localhost ~]# ansible windows -m win_user -a "name=UserName passwd=PassWord"
192.168.0.124 | SUCCESS => {
    "account_disabled": false, 
    "account_locked": false, 
    "changed": true, 
    "description": "", 
    "fullname": "UserName", 
    "groups": [], 
    "name": "UserName", 
    "password_expired": true, 
    "password_never_expires": false, 
    "path": "WinNT://WORKGROUP/WIN-2UGU35PATIP/UserName", 
    "sid": "S-1-5-21-4132743092-2371137629-2815654814-1001", 
    "state": "present", 
    "user_cannot_change_password": false
}

[root@localhost ~]# ansible linux -m user -a "name=UserName"
192.168.0.74 | SUCCESS => {
    "changed": true, 
    "comment": "", 
    "createhome": true, 
    "group": 1000, 
    "home": "/home/UserName", 
    "name": "UserName", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1000
}

# 创建管理员用户(允许远程桌面)
[root@localhost ~]# ansible windows -m win_user -a "name=UserName password=PassWord111 groups='Administrators,Remote Desktop Users'"
192.168.0.124 | SUCCESS => {
    "account_disabled": false, 
    "account_locked": false, 
    "changed": true, 
    "description": "", 
    "fullname": "UserName", 
    "groups": [
        {
            "name": "Administrators", 
            "path": "WinNT://WORKGROUP/WIN-2UGU35PATIP/Administrators"
        }, 
        {
            "name": "Remote Desktop Users", 
            "path": "WinNT://WORKGROUP/WIN-2UGU35PATIP/Remote Desktop Users"
        }
    ], 
    "name": "UserName", 
    "password_expired": false, 
    "password_never_expires": false, 
    "path": "WinNT://WORKGROUP/WIN-2UGU35PATIP/UserName", 
    "sid": "S-1-5-21-4132743092-2371137629-2815654814-1001", 
    "state": "present", 
    "user_cannot_change_password": false
}

copy, win_copy

[root@localhost ~]# ansible linux -m copy -a "src=/root/zabbix_agents_3.4.6.win.zip dest=/tmp"
192.168.0.74 | SUCCESS => {
    "changed": true, 
    "checksum": "02c8caaed6aff7b7c8f275f90626a28e8b233fdd", 
    "dest": "/tmp/zabbix_agents_3.4.6.win.zip", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "7ca9e6d059032d9d5b6c49a853850bc9", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 977782, 
    "src": "/root/.ansible/tmp/ansible-tmp-1554045330.21-94935765380298/source", 
    "state": "file", 
    "uid": 0
}

[root@localhost ~]# ansible windows -m win_copy -a "src=/root/zabbix_agents_3.4.6.win.zip dest=c:\zabbix_agents_3.4.6.win.zip"
192.168.0.123 | SUCCESS => {
    "changed": true, 
    "checksum": "02c8caaed6aff7b7c8f275f90626a28e8b233fdd", 
    "dest": "c:\\zabbix_agents_3.4.6.win.zip", 
    "operation": "file_copy", 
    "original_basename": "zabbix_agents_3.4.6.win.zip", 
    "size": 977782, 
    "src": "/root/zabbix_agents_3.4.6.win.zip"
}

unzip

将.zip解压到远程Windows主机,远程主机上必须存在需要解压的源文件

[root@localhost ~]# ansible windows -m win_unzip -a"creates=no src=C:\zabbix_agents_3.4.6.win.zip dest=C:\zabbix"
192.168.0.123 | SUCCESS => {
    "changed": true, 
    "dest": "C:\\zabbix", 
    "removed": false, 
    "src": "C:\\zabbix_agents_3.4.6.win.zip"
}

lineinfile, win_lineinfile

匹配到后替换 未匹配到不做操作

ansible windows -m win_lineinfile -a 'path=C:\zabbix_agent\conf\zabbix_agentd.win.conf regexp="Server=" line="Server=192.168.2.8" backrefs="yes"'

ansible linux -m lineinfile -a "dest=/etc/ssh/sshd_config regexp='#UseDNS yes' line='UseDNS no' backrefs=yes"

未匹配到增加一行 匹配到不做操作

ansible linux -m lineinfile -a "dest=/etc/hosts.allow regexp='sshd:192.168.0.:allow' line='sshd:192.168.2.:allow' backrefs=no"
ansible linux -m lineinfile -a "dest=/etc/hosts.deny regexp='sshd:ALL' line='sshd:ALL' backrefs=no"

service

ansible linux -m service -a "name=sshd state=restarted"

ansible windows -m win_service  -a "name='Zabbix Agent'"

批量部署zabbix

CentOS-6,7 客户端

cat > zabbix-agent-centos.sh <<'EOF'
#!/bin/bash
############################################
# Author: xiongjunfeng
# For: Auto install zabbix-agent
# Version: 2.0
# bash:
# System: CentOS 6,7
############################################

ZabbixServer='192.168.0.10'

# 安装 Zabbix Agent
banben=$(cat /etc/redhat-release | grep -o [0-9] | head -n 1)
if [ $banben -eq 7 ];then
    yum -y install http://repo.zabbix.com/zabbix/3.4/rhel/7/x86_64/zabbix-release-3.4-1.el7.centos.noarch.rpm
elif [ $banben -eq 6 ];then
    yum -y install http://repo.zabbix.com/zabbix/3.4/rhel/6/x86_64/zabbix-release-3.4-1.el6.noarch.rpm
fi

yum -y install zabbix-agent

# 配置 Zabbix Agent
sed -i "s#Server=.*#Server=$ZabbixServer#" /etc/zabbix/zabbix_agentd.conf
sed -i "s#ServerActive=.*#ServerActive=$ZabbixServer#" /etc/zabbix/zabbix_agentd.conf
sed -i "s#Hostname=.*#Hostname=$(hostname -I)#" /etc/zabbix/zabbix_agentd.conf

# 自动注册
sed -i "s/# HostMetadataItem=.*/HostMetadataItem=system.uname/" /etc/zabbix/zabbix_agentd.conf


if [ $banben -eq 7 ];then
    # 防火墙配置
    firewall-cmd --add-port=10050/tcp --permanent
    firewall-cmd --reload

    # 启动服务
    systemctl start zabbix-agent
    systemctl enable zabbix-agent
elif [ $banben -eq 6 ];then
    # 防火墙配置
    iptables -A INPUT -p tcp --dport 10050 -j ACCEPT
    /etc/rc.d/init.d/iptables save

    # 启动服务
    service zabbix-agent start
    chkconfig zabbix-agent on
fi
EOF

# 复制脚本到远程
ansible linux -m copy -a "src=zabbix-agent-centos.sh  dest=/tmp"

# 执行安装
ansible linux -m shell -a 'sh /tmp/zabbix-agent-centos.sh'

# 删除脚本
ansible linux -m file -a "dest=/tmp/zabbix-agent-centos.sh state=absent"

# 检测
ansible linux -m service -a "name=zabbix-agent state=restarted"

Windows 客户端

cat > zabbix-agent-win.ps1   <<'EOF'
############################################
# Author: xiongjunfeng
# For: Auto install zabbix-agent
# Version: 2.0
# PowerShell: 4.0
# System: Windows 2012 R2
##############################################

$ZabbixServer='192.168.0.10'

# SSL 证书问题
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

# 下载安装文件
wget -OutFile C:\zabbix_agent.zip https://www.zabbix.com/downloads/3.4.6/zabbix_agents_3.4.6.win.zip

# 解压函数传入 压缩文件路径,解压路径
Function Unzip-File()
{
    param([string]$ZipFile,[string]$TargetFolder)
    # 如果文件夹不存在则创建
    if(!(Test-Path $TargetFolder))
    {
        mkdir $TargetFolder
    }
    $shellApp = New-Object -ComObject Shell.Application
    $files = $shellApp.NameSpace($ZipFile).Items()
    $shellApp.NameSpace($TargetFolder).CopyHere($files)
}
# 将安装文件解压
Unzip-File -ZipFile C:\zabbix_agent.zip -TargetFolder C:\zabbix_agent

# 删除默认配置文件
rm C:\zabbix_agent\conf\zabbix_agentd.win.conf

# 创建配置文件
$hostname=hostname
Add-Content -value "LogFile=C:\zabbix_agent\zabbix.log" C:\zabbix_agent\conf\zabbix_agentd.win.conf
Add-Content -value "Server=$ZabbixServer" C:\zabbix_agent\conf\zabbix_agentd.win.conf
Add-Content -value "Hostname=$hostname" C:\zabbix_agent\conf\zabbix_agentd.win.conf
Add-Content -value "ServerActive=$ZabbixServer" C:\zabbix_agent\conf\zabbix_agentd.win.conf 
Add-Content -value "HostMetadataItem=system.uname" C:\zabbix_agent\conf\zabbix_agentd.win.conf 

# 判断系统类型
$sysinfo=(systeminfo.exe)[14]
$sysinfonew=$sysinfo.Replace("系统类型:         ","")

# 注册服务
if ($sysinfonew -like "x64-based PC" ){
    C:\zabbix_agent\bin\win64\zabbix_agentd.exe --config C:\zabbix_agent\conf\zabbix_agentd.win.conf --install
}else {
    C:\zabbix_agent\bin\win32\zabbix_agentd.exe --config C:\zabbix_agent\conf\zabbix_agentd.win.conf --install
}

# 防火墙
netsh advfirewall firewall add rule name="Zabbix-Agent" dir=in localport=10050 protocol=TCP action=allow

# 启动服务
Start-Service "Zabbix Agent"

# 删除安装包
rm C:\zabbix_agent.zip
EOF

# 转换编码
yum install -y unix2dos
unix2dos zabbix-agent-win.ps1

ansible windows -m win_copy -a 'src=/root/zabbix-agent-win.ps1 dest=c:\'
ansible windows -m win_shell -a 'C:\zabbix-agent-win.ps1'
ansible windows -m win_file -a "dest=C:\zabbix-agent-win.ps1 state=absent"
ansible windows -m win_file -a "dest=C:\zabbix_agent.zip state=absent"

windows 客户端手动安装

# 下载安装包
curl -sSLO https://www.zabbix.com/downloads/3.4.6/zabbix_agents_3.4.6.win.zip

# 复制安装包到远程主机
ansible windows -m win_copy -a "src=./zabbix_agents_3.4.6.win.zip dest=c:\zabbix_agent.zip"

# 解压
ansible windows -m win_unzip -a"creates=no src=C:\zabbix_agents.zip dest=C:\zabbix_agent"

# 注册服务
ansible windows -m win_command -a 'C:\zabbix_agent\bin\win64\zabbix_agentd.exe --config C:\zabbix_agent\conf\zabbix_agentd.win.conf --install'

# 启动 zabbix-agent
ansible windows -m win_service -a "name='Zabbix Agent' state=started"

# 删除安装包
ansible windows -m win_file -a 'dest=c:\zabbix_agent.zip state=absent'

windows 客户端卸载

# 查看服务状态
ansible windows -m win_service  -a "name='Zabbix Agent'"

# 关闭 zabbix-agent 服务
ansible windows -m win_service -a "name='Zabbix Agent' state=stopped"

# 删除 zabbix-agent 服务
ansible windows -m win_command -a 'C:\zabbix_agent\bin\win64\zabbix_agentd.exe --config C:\zabbix_agent\conf\zabbix_agentd.win.conf --uninstall'

# 删除 zabbix-agent 安装目录
ansible windows -m win_file -a "dest=C:\zabbix_agent state=absent"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!