首页 > 其他分享 >ansible

ansible

时间:2024-10-16 14:43:02浏览次数:1  
标签:172.16 ansible yum 模块 m01 root

1. Ansible概述

自动化运维: 批量管理,批量分发,批量执行,维护...

Ansible是python写的.

 

批量管理工具

说明

Ansible

无客户端,基于ssh进行管理与维护

Saltstack

需要安装客户端,基于ssh进行管理,与ansible.

terraform

tf批量管理基础设施(批量创建100台公有云)
......  

2. Ansible管理架构

ansible组成:

Inventory 主机清单:被管理主机的ip列表,也包含分类.

ad-hoc模式: 命令行批量管理(使用ans模块),临时任务.

playbook 剧本模式: 类似于把操作写出脚本,可以重复运行这个脚本.

3. 部署与配置

3.1 部署

#1.安装pip工具 (pip python软件包管理器) 麒麟系统中安装
yum install -y python3-pip
#2.pip 使用pip安装ansible
pip3 install -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple ansible

#3.安装配置path环境变量
echo 'export PATH=/usr/local/bin/:$PATH' >>/etc/profile
source /etc/profile
#4.检查
ansible --version


#centos中可以直接安装
yum install -y ansible

安装ansible 报错:error: out of memory  内存不足

# 通常tmp大小是分配内存的一半
[root@m01 ~]#  free -h
              total        used        free      shared  buff/cache   available
Mem:          1.9Gi       271Mi       1.0Gi       4.0Mi       627Mi       1.5Gi
Swap:         2.0Gi       7.0Mi       2.0Gi
[root@m01 ~]# 
[root@m01 ~]# df -h /tmp
文件系统        容量  已用  可用 已用% 挂载点
tmpfs           979M     0  979M    0% /tmp
[root@m01 ~]# 

# 解决:
1.临时取消tmp分区挂载(直接挂到根上,centos,debian就是这做的)
[root@m01 ~]# umount /tmp
[root@m01 ~]# 
[root@m01 ~]# df -h /tmp
文件系统               容量  已用  可用 已用% 挂载点
/dev/mapper/klas-root   96G  4.7G   92G    5% /

2.永久取消tmp分区
[root@m01 ~]# systemctl disable tmp.mount
[root@m01 ~]# systemctl mask tmp.mount
Created symlink /etc/systemd/system/tmp.mount → /dev/null.
[root@m01 ~]# systemctl stop tmp.mount

3.2 配置

# 修改配置文件关闭主机Host_key_checking .
# 修改配置文件开启日志功能.
[root@m01 ~]# egrep -nv '^$|#' /etc/ansible/ansible.cfg
10:[defaults]
11:interpreter_python=/usr/bin/python3
72:host_key_checking = False
181:deprecation_warnings = False
328:[inventory]
341:[privilege_escalation]
347:[paramiko_connection]
371:[ssh_connection]
432:[persistent_connection]
446:[accelerate]
461:[selinux]
470:[colors]
486:[diff]

未关闭主机密钥检查后不输入yes/no,然后报错

4. Ans-inventory主机清单

  • 什么是主机清单: 让ansible管理的节点的列表.
  • ansible默认读取在/etc/ansible/hosts文件,并非/etc/hosts.
  • 未来实际使用中一般我们会把主机清单文件存放在指定的目录中,运行ansible的时候通过-i选项指定主机清单文件即可.

环境准备

分类 主机名 ip地址
ansible管理端 m01

10.0.0.61/172.16.1.71

被管理端

web web01 10.0.0.69/172.16.1.69
被管理端 nfs nfs01

10.0.0.68/172.16.1.68

被管理端

backup backup  10.0.0.67/172.16.1.67

4.1 批量管理主机并执行hostname命令 ⭐⭐⭐⭐⭐

ansible命令格式

ansible 主机ip或分组或all -m 指定使用的模块名字 -a 模块中的参数

command 模块是ansible默认的模块可以不写.

# 主机清单格式:
[分类或分组的名字] #注意分类要体现出服务器的作用
ip地址或主机名或域名 #注意主机名要能解析才行

[root@m01 ~]# cat /etc/ansible/hosts 
[backup]
172.16.1.67

[nfs01]
172.16.1.68

[web01]
172.16.1.69 ansible_user=root  ansible_password=123 ansible_port=22
#172.16.1.70

[root@m01 ~]# ansible all -m command -a 'hostname -I'
[DEPRECATION WARNING]: Ansible will require Python 3.8 or newer on the controller starting with Ansible 2.12. Current version: 3.7.9 (default, Jun 10 2022, 11:25:35) [GCC
 7.3.0]. This feature will be removed from ansible-core in version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
172.16.1.67 | CHANGED | rc=0 >>
10.0.0.67 172.16.1.67 
172.16.1.69 | CHANGED | rc=0 >>
10.0.0.69 172.16.1.69 
172.16.1.68 | CHANGED | rc=0 >>
10.0.0.68 172.16.1.68 
[root@m01 ~]# 

4.2 给backup,nfs 2个组合并新的组叫data ⭐⭐⭐

主机清单分组详解:

需要我们进行分组:按照层次进行分组,按照功能/业务.

# 子组使用children关键词创建
格式:
[data:children] #组名字:children即可.
分组的名字

[root@m01 ~]# cat /etc/ansible/hosts 
[backup]
172.16.1.67

[nfs01]
172.16.1.68

[web01]
172.16.1.69 ansible_user=root  ansible_password=Liuxiaoke123 ansible_port=22
#172.16.1.70

[data:children]
nfs01
backup

[root@m01 ~]# ansible data -m command -a 'hostname'
[DEPRECATION WARNING]: Ansible will require Python 3.8 or newer on the controller starting with Ansible 2.12. Current version: 3.7.9 (default, Jun 10 2022, 11:25:35) [GCC
 7.3.0]. This feature will be removed from ansible-core in version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
172.16.1.67 | CHANGED | rc=0 >>
backup
172.16.1.68 | CHANGED | rc=0 >>
nfs01
[root@m01 ~]# 

4.3 主机清单中表示范围 ⭐⭐⭐⭐

[root@m01 ~]# cat /etc/ansible/hosts
[web]
172.16.1.[5:10] #[从哪里开始:到哪里结束] 172.16.1.5-10

4.4 指定用户,密码

不推荐,推荐先配置密钥认证,然后管理

主机清单没有配置密钥认证,主机清单如何书写.

172.16.1.69 ansible_user=root  ansible_password=123 ansible_port=22

4.5 批量管理400台机器

4.5.1 环境准备

1. 先准备好zabbix服务端  8c 16G 500G
2. 400台服务器上部署zabbix-agent
3. 流程
  a. 安装软件
  b. 配置文件
  c. 启动服务
4. 需求:
  a. 400台 300Linux 100 win_server 2012 r2
  b. 400台所有的密码不同. 

4.5.2 规划

1. 批量创建主机清单脚本

 linux_pass.txt 
ip 用户名 密码 linux
ip 用户名  密码 win
书写一个脚本生成主机清单文件

#!/bin/bash
#author: xk
#desc: 读取密码文件批量创建主机清单文件.
i=0
j=0

while read  ip  user  pass type
do
  if [ "$type" = "linux"  ];then
    if [ $i -eq 0 ];then
       echo [linux_servers]    >>  hosts
       i=1
    fi
    echo $ip    ansible_user=$user   ansible_port=22  ansible_password=$pass   >>  hosts
  fi
    if [ "$type" = "win"  ];then
      if [ $j -eq 0 ];then
       echo [win_servers]    >>  hosts
       j=1
    fi
    echo $ip    ansible_user=$user   ansible_port=22  ansible_password=$pass   >>  hosts
  fi
done  <linux_pass.txt

2. 主机清单的内容

 [linux_servers]
10.0.0.9   ansible_user=root   ansible_port=22  ansible_password=xxxx

[win_servers]
10.0.0.10   ansible_user=administrator     ansible_password=xxxx

[win_servers:vars]
ansible_connection="winrm"
ansible_port=5985 
#5985 http
#5986 https
ansible_winrm_transport="ntlm"
ansible_winrm_server_cert_validation=ignore

3. 管理机安装winrm模块

yum install python-winrm  #如果ansible是python3安装 python3-winrm
或者 
pip install  pywinrm       #如果ansible是python3安装   pip3 install pywinrm

4.进行检查

#1. 检查linux
ansible  -i hosts  -f 50   linux_servers   -m ping 

#2. 检查windows 
ansible  -i hosts  -f 50   linux_servers   -m win_ping 

#-f  forks  并发数,默认是5.

5.书写剧本

#1. 下载软件
#2. 安装软件
#3. 分发配置文件
#4. 启动服务
#5. handlers 检查配置变化与自动重启服务

参考链接:https://docs.ansible.com/ansible/latest/collections/ansible/windows/index.html#plugins-in-ansible-windows

4.6 小结

主机清单对应写法

应用场景

基本分组 ⭐ ⭐ ⭐ ⭐ ⭐

最常用的,ip,主机名 172.16.1.[5:10]

+children 子组 ⭐ ⭐ ⭐ ⭐

普通的组无法满足了,可以套娃,给组创建组.

在主机清单中指定被管理端的用户名,密码,ssh端口号

无法进行密钥认证.

主机清单获取:

  1. 根据已有的清单获取(表格...其他系统)
  2. 公有云导出
  3. 书写脚本ping/fping+获取ip.

主机清单(inventory) 直接分组,使用子组

ansible格式:

ansible 主机 -m 模块 -a 参数

ansible all所有主机/分组名字/主机

主机清单如果不在/etc/ansible/hosts,则需要通过ansible -i选项指定

帮助:  https://docs.ansible.com/ansible/latest/inventory_guide/intro_inventory.html

5. Ansible必知必会模块

  • Ansible模块概述:
    • ansible中的模块就类似于Linux中的命令,我们Linux命令管理系统,我们通过
    • ansible模块实现批量管理.
    • ansible中模块一般相当于Linux中的一些命令.yum模块,file模块,user模块.
    • ansible中的模块拥有不同的选项,这些选项一般都是一些单词,拥有自己的格式与要求.

ansible -m 模块 -a 命令参数 -i 指定文件

模块分

模块 对应的命令

命令和脚本模块

command模块 ans默认的模块,执行简单命 ,不支持特殊符号

 
 

shell模块 执行命令,支持特殊符号

 
 

script模块 分发脚本然后执行

 

文件

file 创建目录,文件,软连接,

touch,mkdir,ln -s,rm

  copy 远程分发==文件,修改权限,所有者,备份

批量scp/rsync

服务

systemd服务管理

systemctl命令服务

开关重启,开机自启动

 

service 服务管理(了解)

 

软件包

yum源 yum_repository  
 

yum模块/apt模块

 yum命令/apt命令
 

get_url下载软件

wget命令,下载内容.

其他系统管理

mount模块 挂载

mount挂载命令.
 

cron模块 定时任务

 

定时任务:crontab -e 编辑定时任务

用户管理

group模块 管理用户组

 
 

user模块 管理用户

useradd命令

其他可以研究

压缩解压(unarchive) ,rsync模块(synchronize),

数据库模块(mysql_db,mysql_user)...

 

其他

ansible管理docker k8s zabbix grafana ...

 

用于调试模块

ping 模块检查 ansible与其他节点连通性.

 

 

debug 模块 用于检查/显示 变量 剧本使用.

 

官网:https://docs.ansible.com/ansible/latest/collections/index.html

本地命令: ansible-doc -s copy

5.1 命令与脚本类模块

5.1.1 command模块⭐⭐⭐⭐⭐

ans默认的模块,适用于执行简单的命令,不支持特殊符号.

批量获取所有主机的主机名
 [root@m01 ~]# ansible all -m command -a 'hostname'
172.16.1.67 | CHANGED | rc=0 >>
backup
172.16.1.68 | CHANGED | rc=0 >>
nfs01
172.16.1.69 | CHANGED | rc=0 >>
web01
[root@m01 ~]# 
[root@m01 ~]# ansible all -a 'hostname'
172.16.1.67 | CHANGED | rc=0 >>
backup
172.16.1.69 | CHANGED | rc=0 >>
web01
172.16.1.68 | CHANGED | rc=0 >>
nfs01
[root@m01 ~]# 

[root@m01 ~]# ansible all -a 'ip a s ens33'
[DEPRECATION WARNING]: Ansible will require Python 3.8 or newer on the controller starting with Ansible 
2.12. Current version: 3.7.9 (default, Jun 10 2022, 11:25:35) [GCC 7.3.0]. This feature will be removed from
 ansible-core in version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in
 ansible.cfg.
172.16.1.67 | CHANGED | rc=0 >>
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:50:56:3e:c6:d4 brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.67/24 brd 10.0.0.255 scope global noprefixroute ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::d164:8730:891c:6d04/64 scope link dadfailed tentative noprefixroute 
       valid_lft forever preferred_lft forever
    inet6 fe80::73c4:a5cc:ca9b:b3d1/64 scope link dadfailed tentative noprefixroute 
       valid_lft forever preferred_lft forever
    inet6 fe80::48d7:197a:dde0:e786/64 scope link dadfailed tentative noprefixroute 
       valid_lft forever preferred_lft forever
172.16.1.68 | CHANGED | rc=0 >>
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:50:56:2c:73:be brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.68/24 brd 10.0.0.255 scope global noprefixroute ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::d164:8730:891c:6d04/64 scope link dadfailed tentative noprefixroute 
       valid_lft forever preferred_lft forever
    inet6 fe80::73c4:a5cc:ca9b:b3d1/64 scope link dadfailed tentative noprefixroute 
       valid_lft forever preferred_lft forever
    inet6 fe80::48d7:197a:dde0:e786/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
172.16.1.69 | CHANGED | rc=0 >>
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:39:f3:b7 brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.69/24 brd 10.0.0.255 scope global noprefixroute ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::73c4:a5cc:ca9b:b3d1/64 scope link dadfailed tentative noprefixroute 
       valid_lft forever preferred_lft forever
    inet6 fe80::d164:8730:891c:6d04/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
[root@m01 ~]# 

5.1.2 shell模块⭐⭐⭐⭐⭐

与command模块类似,但是shell支持特殊符号.

批量获取ip地址
 [root@m01 ~]# ansible all -m shell -a "ip a s ens33 |awk -F'[ /]+' 'NR==3{print \$3}'"
172.16.1.67 | CHANGED | rc=0 >>
10.0.0.67
172.16.1.69 | CHANGED | rc=0 >>
10.0.0.69
172.16.1.68 | CHANGED | rc=0 >>
10.0.0.68

[root@m01 ~]# ansible all -m shell -a "ip a s ens33 |awk -F'[ /]+' 'NR==3{print $3}'"
[DEPRECATION WARNING]: Ansible will require Python 3.8 or newer on the controller starting with Ansible 
2.12. Current version: 3.7.9 (default, Jun 10 2022, 11:25:35) [GCC 7.3.0]. This feature will be removed from
 ansible-core in version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in
 ansible.cfg.
172.16.1.67 | CHANGED | rc=0 >>
    inet 10.0.0.67/24 brd 10.0.0.255 scope global noprefixroute ens33
172.16.1.68 | CHANGED | rc=0 >>
    inet 10.0.0.68/24 brd 10.0.0.255 scope global noprefixroute ens33
172.16.1.69 | CHANGED | rc=0 >>
    inet 10.0.0.69/24 brd 10.0.0.255 scope global noprefixroute ens33
[root@m01 ~]#

温馨提示:

shell模块不推荐执行较为复杂的指令,如果需要执行放在脚本中执行.避免因为特殊符号和引号导致的问题.

5.1.3  script模块⭐⭐⭐⭐⭐

执行流程:分发脚本(传输脚本),在被管理端运行脚本

ansible_scripts.sh
 [root@m01 ~]# cat /server/scripts/ansible_scripts.sh 
#!/bin/bash
##############################################################
# File Name:/server/scripts/ansible_scripts.sh
# Version:V1.0
# Author:xk
# Organization:
# Desc:巡检脚本
##############################################################
hostname
hostname -I
ip a s eth0 |awk -F'[ /]+' 'NR==3{print $3}'
uptime
whoami
date +%F
sleep 30

批量执行脚本获取主机信息

查看代码
 [root@m01 ~]# ansible all -m script -a '/server/scripts/ansible_scripts.sh'
172.16.1.69 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 172.16.1.69 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 172.16.1.69 closed."
    ],
    "stdout": "web01\r\n10.0.0.69 172.16.1.69 \r\nDevice \"eth0\" does not exist.\r\n 17:03:49 up  8:47,  2 users,  load average: 0.00, 0.00, 0.00\r\nroot\r\n2024-10-15\r\n",
    "stdout_lines": [
        "web01",
        "10.0.0.69 172.16.1.69 ",
        "Device \"eth0\" does not exist.",
        " 17:03:49 up  8:47,  2 users,  load average: 0.00, 0.00, 0.00",
        "root",
        "2024-10-15"
    ]
}
172.16.1.68 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 172.16.1.68 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 172.16.1.68 closed."
    ],
    "stdout": "nfs01\r\n10.0.0.68 172.16.1.68 \r\nDevice \"eth0\" does not exist.\r\n 17:03:49 up  8:47,  1 user,  load average: 0.00, 0.00, 0.00\r\nroot\r\n2024-10-15\r\n",
    "stdout_lines": [
        "nfs01",
        "10.0.0.68 172.16.1.68 ",
        "Device \"eth0\" does not exist.",
        " 17:03:49 up  8:47,  1 user,  load average: 0.00, 0.00, 0.00",
        "root",
        "2024-10-15"
    ]
}
172.16.1.67 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 172.16.1.67 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 172.16.1.67 closed."
    ],
    "stdout": "backup\r\n10.0.0.67 172.16.1.67 \r\nDevice \"eth0\" does not exist.\r\n 17:03:49 up  7:01,  1 user,  load average: 0.00, 0.00, 0.00\r\nroot\r\n2024-10-15\r\n",
    "stdout_lines": [
        "backup",
        "10.0.0.67 172.16.1.67 ",
        "Device \"eth0\" does not exist.",
        " 17:03:49 up  7:01,  1 user,  load average: 0.00, 0.00, 0.00",
        "root",
        "2024-10-15"
    ]
}
[root@m01 ~]# 

# ansible 将脚本临时放到被管理端的/root/.ansible/tmp目录下,脚本执行完后自动删除
[root@web01 ~]# ps -ef | grep ansible
root       13712   13536  0 17:03 pts/1    00:00:00 /bin/sh -c  /root/.ansible/tmp/ansible-tmp-1728983029.070055-7657-174275532150501/ansible_scripts.sh && sleep 0
root       13755   13712  0 17:03 pts/1    00:00:00 /bin/bash /root/.ansible/tmp/ansible-tmp-1728983029.070055-7657-174275532150501/ansible_scripts.sh
root       13767   13461  0 17:03 pts/0    00:00:00 grep --color=auto ansible
[root@web01 ~]# 
[root@web01 ~]# cd /root/.ansible/tmp
[root@web01 ~/.ansible/tmp]# ll
总用量 0
drwx------ 2 root root 32 10月 15 17:03 ansible-tmp-1728983029.070055-7657-174275532150501
[root@web01 ~/.ansible/tmp]#
[root@web01 ~/.ansible/tmp]# ll
总用量 0

5.2 文件相关模块

从这个部分模块开始模块中会有较多的选项.

从这部分开始记忆模块选项的规律(单词或单词缩写).

5.2.1 file模块⭐⭐⭐⭐⭐

file模块不仅可以管理文件,还可以管理目录,管理软连接.

file模块相当于把touch命令,mkdir命令,rm命令,ln -s命令,chown,chmod结合在一起了.

file模块参数

模块说明

path

路径(目录,文件) 必须要写 注意不是name

src

source源,源文件一般用于link(创建软连接模式) 用于指定源文件

state

 

状态(模式) ,具体要做的什么,创建/删除,操作文件/操作目录

state=directory 创建目录

state=file (默认) 更新文件,如果文件不存在也不创建

state=link 创建软连接

state=touch 创建文件

state=absent 删除 (⚠ 如果是目录递归删除目录. )

mode

mode=755 创建并修改权限 建议 mode="0600"

owner

onwer=root 指定用户

group

group=root 指定用户组

案例

查看代码
 # 创建目录 /ans_app⭐
[root@m01 ~]# ansible web01 -m file -a 'path=/ans_app state=directory'
172.16.1.69 | CHANGED => {
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0755",
    "owner": "root",
    "path": "/ans_app",
    "size": 6,
    "state": "directory",
    "uid": 0
}
[root@web01~]# ls /
ans_app   bin   dev  home  lib64  mnt  proc  run   server  sys  usr
ans_test  boot  etc  lib   media  opt  root  sbin  srv     tmp  var

# 创建文件/ans_app/1.txt ⭐
[root@m01 ~]# ansible web01 -m file -a 'path=/ans_app/1.txt state=touch'
172.16.1.69 | CHANGED => {
    "changed": true,
    "dest": "/ans_app/1.txt",
    "gid": 0,
    "group": "root",
    "mode": "0644",
    "owner": "root",
    "size": 0,
    "state": "file",
    "uid": 0
}

[root@web01 ~]# ls /ans_app/
1.txt

# 创建软连接 /etc/hosts到/ans_app/下 ⭐
[root@m01 ~]# ansible web01 -m file -a 'src=/etc/hosts dest=/ans_app/hosts.ln state=link'
172.16.1.69 | CHANGED => {
    "changed": true,
    "dest": "/ans_app/hosts.ln",
    "gid": 0,
    "group": "root",
    "mode": "0777",
    "owner": "root",
    "size": 10,
    "src": "/etc/hosts",
    "state": "link",
    "uid": 0
}

[root@web01 ~]# ls /ans_app/
1.txt  hosts.ln

# 创建/ans_test/目录 所有者是xk,权限是700
[root@m01 ~]# ansible web01 -m file -a 'path=/ans_test state=directory owner=xk group=xk mode=700'
172.16.1.69 | CHANGED => {
    "changed": true,
    "gid": 1000,
    "group": "xk",
    "mode": "0700",
    "owner": "xk",
    "path": "/ans_test",
    "size": 6,
    "state": "directory",
    "uid": 1000

[root@web01 ~]# ll -d /ans_test/
drwx------ 2 xk xk 6 10月 15 17:38 /ans_test/

# 删除/ans_test目录
[root@m01 ~]# ansible web01 -m file -a 'path=/ans_test state=absent'
172.16.1.69 | CHANGED => {
    "changed": true,
    "path": "/ans_test",
    "state": "absent"
}

[root@web01 ~]# ll -d /ans_test/
ls: 无法访问 '/ans_test/': 没有那个文件或目录

5.2.1 copy模块⭐⭐⭐⭐⭐

批量分发:scp,1个节点(管理节点)发送文件或压缩包到所有被管理端. 注意:copy是单向的传输.类似于scp命令.

copy模块

参数说明

src

source 源文件,管理端的某个文件.

dest

destination 目标,被管理端的目录/文件.

backup

backup=yes 则会在覆盖前进行备份,文件内容要有变化或区别.

mode

修改权限

owner

修改为指定所有者

group

修改为指定用户组

 模块官方文档: ansible-doc -s 查询 https://docs.ansible.com/ansible/latest/collections/index.html

分发文件(hosts,配置文件,压缩包)

不推荐copy分发目录.

分发书写好的/etc/hosts文件,如果文件存在则备份
 [root@m01 ~]# cat /etc/hosts
172.16.1.5 lb01
172.16.1.6 lb02
172.16.1.69 web01
172.16.1.70 web02
172.16.1.9 web03
172.16.1.68 nfs01
172.16.1.67 backup
172.16.1.51 db01
172.16.1.71 m01
172.16.1.xx web03
172.16.1.xx web04
[root@m01 ~]# ansible web01 -m copy -a 'src=/etc/hosts dest=/etc/ backup=yes'
172.16.1.69 | CHANGED => {
    "backup_file": "/etc/hosts.17155.2024-10-15@19:11:40~",
    "changed": true,
    "checksum": "fd6fc9a242e1ffb04030589d5ea1a2efd4666541",
    "dest": "/etc/hosts",
    "gid": 0,
    "group": "root",
    "md5sum": "186485265722235f1f9b7571ca21f179",
    "mode": "0644",
    "owner": "root",
    "size": 191,
    "src": "/root/.ansible/tmp/ansible-tmp-1728990699.175297-8820-185337985937168/source",
    "state": "file",
    "uid": 0
}
[root@m01 ~]# 

[root@web01 ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
172.16.1.5 lb01
172.16.1.6 lb02
172.16.1.69 web01
172.16.1.70 web02
172.16.1.9 web03
172.16.1.68 nfs01
172.16.1.67 backup
172.16.1.51 db01
172.16.1.61 m01
[root@web01 ~]# 
[root@web01 ~]# cat /etc/hosts
172.16.1.5 lb01
172.16.1.6 lb02
172.16.1.69 web01
172.16.1.70 web02
172.16.1.9 web03
172.16.1.68 nfs01
172.16.1.67 backup
172.16.1.51 db01
172.16.1.71 m01
172.16.1.xx web03
172.16.1.xx web04
[root@web01 ~]# 
[root@web01 ~]# ls /etc/ | grep hosts
hosts
hosts.17155.2024-10-15@19:11:40~
[root@web01 ~]# 

额外扩展:

copy是推送,批量推送.
fetch是拉取,批量拉取.使用较少. 拉取所有主机的/etc/hostname
ansible all -m fetch -a 'src=/etc/hostname dest=/tmp/'

5.3 服务管理-systemd⭐⭐⭐⭐⭐

  • systemd模块相当于是linux systemctl 命令:
    • 开启/关闭/重启服务 ;
    • 开机自启动;

systemd模块参数

说明

name

用于指定服务名称

enabled

yes开机自启动 (yes/no)
state

表示服务开,关,重启...

state=started 开启

state=stopped 关闭

state=reloaded 重读配置文件(服务支持)

state=restarted 重启(关闭再开启)

daemon-reload

 

yes是否重新加载对应的服务的管理配置文件(未来讲解书写systemctl配置文件)

开启crond服务并设置开机自启动.

关闭firewalld服务并不让开机自启动.

#启动服务
ansible all -m systemd -a 'name=crond enabled=yes state=started'

#关闭服务
ansible all -m systemd -a 'name=firewalld enabled=no state=stopped'

#重启ssh
ansible all -m systemd -a 'name=sshd state=reloaded' #也可以restarted

额外扩展:

systemd模块适用于目前大部分的Linux系统.

service模块适用于管理旧的Linux系统.

5.4 软件管理

  • yum模块
  • get_url模块:wget命令
  • yum_repository模块 yum源配置模块,未来可以通过copy模块.

5.4.1 yum模块⭐⭐⭐⭐⭐

yum模块并不只是yum命令,包含了yum/apt命令

yum模块参数

说明
name

指定软件包名字,可以指定多个,通过","分割.

state

installed 安装(也可以写为present)(默认)

removed 删除 (也可以写为absent) yum remove删除,慎用.删除依赖.

lastest 安装或更新(安装最新版本)

update_cache

可以设置为no加加速,表示不更新本地yum缓存. 实际公网环境,正式环境可以不加.

安装常用的软件

ansible all -m yum -a 'name=htop,tree,lrzsz,sshpass '
ansible all -m yum -a 'name=rsync state=present'
ansible all -m yum -a 'name=rsync state=latest'

5.4.2  get_url模块⭐⭐

相当于是wget命令.所有主机能访问网络才行.

推荐在管理节点下载好,使用copy仅分发即可.

get_url下载功能

说明
url

指定要下载的地址

dest

下载到哪个目录

下载ngx软件包到/opt/

ansible all -m get_url -a 'url="https://nginx.org/download/nginx-1.26.1.tar.gz" dest=/opt/

5.4.3  yum_repository模块

推荐: 未来书写好yum配置(xxx.repo)文件,copy分发过去即可.

yum源模块  yum_repository

yum源的配置文件内容

name=epel

yum源中名字 [epel]

description="介绍"

yum源的注释说明 对应的 是name的内容

baseurl

yum源中 baseurl 下载地址

enabled=yes

是否启动这个源 enabled=1 yes/no

gpgcheck

是否启动gpgcheck功能 no

file

指定yum源的文件 自动添加 .repo 默认与模块名字一致.

 

# yum配置文件
root@m01 ~]# cat /etc/yum.repos.d/epel.repo
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=http://mirrors.aliyun.com/epel/7/$basearch
enabled=1
gpgcheck=0

# yum源模块选项
ansible backup -m yum_repository -a 'name=epel description="Extra Packages for Enterprise Linux 7 -$basearch" baseurl="http://mirrors.aliyun.com/epel/7/$basearch" enabled=yes gpgcheck=no

 

yum配置文件内容

yum源的模块的选项

[epel]

name=epel #默认yum源文件的名字与这个一致

name=Extra Pxxxxx

 

description="Extra xxxxxxx"

baseurl=http://mirrors.aliyun.com/epel/7/$basearch

baseurl="http://mirrors.aliyun.com/epel/7/$basearch"

enabled=1

enabled=yes

gpgcheck=0

 gpgcheck=no

5.4.4  小结

5.5 用户管理

  • user用户管理 : useradd,userdel,passwd,usermod修改用户信息
  • group用户组管理 : groupadd,groupdel.
  • 添加普通用户与设置密码,添加虚拟用户,设置uid

5.5.1 user模块⭐⭐⭐⭐⭐

user模块参数

说明

name

wwww 用户名

uid

指定uid

group

指定用户组,一般用于事先创建好了用户组,通过选项指定下.

shell

指定命令解释器:默认是/bin/bash /sbin/nologin

create_home

是否创建家目录(yes/no),默认yes.
state

present 添加

absent 删除

password

加密的密码. 不能直接写明文密码

创建www-ans用户uid2000虚拟用户 ⭐ ⭐ ⭐ ⭐ ⭐

ansible all -m user -a 'name=www-ans uid=2000 shell=/sbin/nologin create_home=no state=present'

批量更新密码

批量更新密码
 #方法01 user模块
ansible all -m user -a "name=xk password={{ 'Xk123456' | password_hash('sha512', '135') }} state=present"
#方法02
ansible all -m shell -a 'echo 1 |passwd --stdin Xk123456'
#其他方法
https://docs.ansible.com/ansible/latest/reference_appendices/faq.html # how-do-i-generate-encrypted-passwords-for-the-usermodule


[root@m01 ~]# ansible 172.16.1.68 -i /server/ans/playbook/hosts -m debug -a "msg='{{ '1' | password_hash('sha512','abc135') }}'"
172.16.1.68 | SUCCESS => {
    "msg": "$6$abc135$Ir9F7vUl8Y0/3AIfuD2XUDnIzFWQ3cEdWUtZ1hPDtlj7Er6CfaXk3dV5qnetoJCd2bvDQFTsk/Tx1DZ9Z692S0"
}
# 值一样,加密出来的结果也是一样的  
[root@m01 ~]# echo 1 | sha512sum
3abb6677af34ac57c0ca5828fd94f9d886c26ce59a8ce60ecf6778079423dccff1d6f19cb655805d56098e6d38a1a710dee59523eed7511e5a9e4b8ccb3a4686  -
[root@m01 ~]# 
[root@m01 ~]# echo 1 | sha512sum
3abb6677af34ac57c0ca5828fd94f9d886c26ce59a8ce60ecf6778079423dccff1d6f19cb655805d56098e6d38a1a710dee59523eed7511e5a9e4b8ccb3a4686  -
[root@m01 ~]# 

关于{{}}相关的解释

{{ }} 格式用于在ansible调用变量PATH name=xiaoming echo name 

{{ '1' | password_hash('sha512', '135') }}

表示1是密码,经过管道,传递给了password_hash()插件, sha512加密算法,135是随机字符用于生成随机加密后的密码.

ansible 172.16.1.68 -m debug -a "msg='{{ '1' | password_hash('sha512', 'abc135') }}

5.5.2 group模块(了解)

group参数

说明

name

指定用户组名字

gid

指定组的gid
state

present添加

absent 删除

5.6 cron模块

作用:用于管理系统的定时任务.

替代了crontab -e或vi /var/spool/cron/xxx用户功能.

cron模块参数

说明

name

定时任务名字(一定要加上), 对应下面注释的内容
minute

分钟 minute="*/2"

hour

小时

day

日期

month

月份

week

周几
job

指定命令或脚本(定向到空) job="/sbin/ntpdate ntp1.aliyun.com  >/dev/null 2>&1"

state

present 添加定时任务(默认)

absent 删除

每分钟输出主机名,写入到/opt/name.txt

定时任务
 # 创建定时任务
[root@m01 ~]# ansible all -m cron -a 'name="echo_hostname" job="echo hostname >> /opt/name.txt 2>&1" state=present '
172.16.1.69 | CHANGED => {
    "changed": true,
    "envs": [],
    "jobs": [
        "echo_hostname"
    ]
}
172.16.1.67 | CHANGED => {
    "changed": true,
    "envs": [],
    "jobs": [
        "echo_hostname"
    ]
}
172.16.1.68 | CHANGED => {
    "changed": true,
    "envs": [],
    "jobs": [
        "echo_hostname"
    ]
}
[root@m01 ~]# 
[root@m01 ~]# ansible all -a "crontab -l"
[DEPRECATION WARNING]: Ansible will require Python 3.8 or newer on the controller starting with Ansible 2.12. Current version: 3.7.9 (default, Jun 10 2022, 11:25:35) [GCC
 7.3.0]. This feature will be removed from ansible-core in version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
172.16.1.67 | CHANGED | rc=0 >>
#1. sync time by xk at 20230101
*/3 * * * * /sbin/ntpdate ntp.aliyun.com  >/dev/null  2>&1
#Ansible: echo_hostname
* * * * * echo hostname >> /opt/name.txt 2>&1
172.16.1.69 | CHANGED | rc=0 >>
#1. sync time by xk at 20230101
*/3 * * * * /sbin/ntpdate ntp.aliyun.com  >/dev/null  2>&1
#Ansible: echo_hostname
* * * * * echo hostname >> /opt/name.txt 2>&1
172.16.1.68 | CHANGED | rc=0 >>
#1. sync time by xk at 20230101
*/3 * * * * /sbin/ntpdate ntp.aliyun.com  >/dev/null  2>&1
#Ansible: echo_hostname
* * * * * echo hostname >> /opt/name.txt 2>&1
[root@m01 ~]# 

# 删除定时任务
[root@m01 ~]# ansible all -m cron -a 'name="echo_hostname"  state=absent'
[DEPRECATION WARNING]: Ansible will require Python 3.8 or newer on the controller starting with Ansible 2.12. Current version: 3.7.9 (default, Jun 10 2022, 11:25:35) [GCC
 7.3.0]. This feature will be removed from ansible-core in version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
172.16.1.68 | CHANGED => {
    "changed": true,
    "envs": [],
    "jobs": []
}
172.16.1.67 | CHANGED => {
    "changed": true,
    "envs": [],
    "jobs": []
}
172.16.1.69 | CHANGED => {
    "changed": true,
    "envs": [],
    "jobs": []
}
[root@m01 ~]# 

5.7 mount模块

实现mount命令进行挂载可以修改/etc/fstab实现永久挂载.

mount

说明
src

源地址(nfs服务端共享地址 eg 172.16.1.68/data )

path

注意这里不是dest,挂载点(要把源挂载到哪里)

fstype

filesystem type指定文件系统,xfs,ext4,iso9660,nfs mount命令的-t选项

state

absent            卸载并修改fstab

unmounted    卸载不修改/etc/fstab

present           仅修改/etc/fstab 不挂载

mounted        挂载并修改/etc/fstab

remounted      重新挂载

挂载nfs01已有的共享目录到web01上的/mnt下

ansible web -m mount -a 'fstype=nfs src=172.16.1.68:/data/ path=/mnt/ state=mounted'

卸载/mnt/

ansible 172.16.1.68 -m mount -a 'path=/mnt/ state=absent'

5.8 总结模块

https://www.processon.com/view/link/64783f6097dfee0f88662081

https://docs.ansible.com/ansible/latest/collections/index.html

模块分

模块 对应的命令

命令和脚本模块

command模块 ans默认的模块,执行简单命 ,不支持特殊符号

 
 

shell模块 执行命令,支持特殊符号

 
 

script模块 分发脚本然后执行

 
 

file 创建目录,文件,软连接

touch,mkdir,ln -s,rm
 

copy 远程分发文件,修改权限,所有者,备份

批量scp/rsync
 

lineinfile

修改配置文件

服务

systemd服务管理

systemctl命令服务

开关重启,开机自启动

 

service 服务管理(了解)

 

软件包

yum源 yum_repository  

 

yum模块/apt模块

yum命令/apt命令

 

get_url下载软件

wget命令,下载内容.

其他系统管理

mount模块 挂载 mount挂载命令.

 

cron模块 定时任务

定时任务:crontab -e  编辑定时任务

用户管理

group模块 管理用户组  

 

user模块 管理用户

useradd命令

其他可以研究

压缩解压(unarchive) ,rsync模块(synchronize),

数据库模块(mysql_db,mysql_user)...

 

其他

ansible管理docker k8s zabbix grafana ...

 

用于调试模块

ping 模块检查 ansible与其他节点连通性.

 

 

debug 模块 用于检查/显示 变量

 

 

标签:172.16,ansible,yum,模块,m01,root
From: https://www.cnblogs.com/daofaziran/p/18467446

相关文章

  • 如何使用 Ansible 管理多阶段环境
    前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。介绍Ansible是一个强大的配置管理系统,用于在不同环境中设置和管理基础设施和应用程序。虽然Ansible提供了易于阅读的语法、灵活的工作流程和强大的工具,但在管理大量主机......
  • Ansible 中的 Role
    Rolerole(角色)用来实现代码的组织管理功能,将实现各种不同功能的playook文件,变量文件,模板文件,handlers文件根据约定,分别放置在不同的目录,分门别类的管理起来,使其看起来更像一个项目,其主要用来解决多文件之间的相互包含,引用,组合等问题,将各个功能模块进行拆分,使其原子化,......
  • ansible中为什么不都是用shell模块写task,而是创建出一个一个的模块
    ansible的shell模块的功能非常强大,它甚至可以代替ansible的所有模块,比如像unarchive命令,在shell中可以分解为。通过scp命令传送包到远程,再通过tar命令对文件进行解压,再比如user模块可以直接在shell模块中调用useradd命令和usermod命令进行用户的管理,那么为什么还会有其他模......
  • 自动化运维工具 Ansible
    Ansible基础Ansible介绍Ansible是一个自动化运维工具,基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。Ansible的名称来自科幻小说《安德的游戏》中跨越时空的即时通信工具,它可以......
  • pyenv安装 配合ansible使用
    目录pyenv简介安装pyenv依赖包安装pyenvpyenv-virtualenv设置参数下载指定版本代码虚拟环境操作退出会话,再重新登录,进入虚拟环境,能查看到ansible版本号,具体原因未明确pyenv简介pyenv用于安装、切换和管理不同版本的Python,确保项目在正确的Python环境中运行安装多个Pyt......
  • 自动化运维:Ansible、Puppet、Chef工具对比与实战
    工具对比1.Ansible架构:无代理(Agentless)语言:使用YAML作为配置文件的语法学习曲线:平缓,适合初学者特点:无需在被管理节点上安装代理软件,通过SSH直接管理。简单直观,配置和操作都相对容易。社区支持广泛,模块丰富。适用场景:小型到中型环境的快速部署和配置管理......
  • ansible-cmdb简单使用
    1、安装官方:https://ansible-cmdb.readthedocs.io/en/latest/wgethttps://github.com/fboender/ansible-cmdb/releases/download/1.27/ansible-cmdb-1.27-2.noarch.rpmyum-yinstall./ansible-cmdb-1.27-2.noarch.rpm2、使用首先,为你的主机生成Asible输出:mkdiroutan......
  • RHCS认证-Linux(RHel9)-Ansible
    文章目录一、ansible简介二、ansible部署三、ansible服务端测试四、ansible清单inventory五、Ad-hot点对点模式六、YAML语言模式七、RHCS-Ansible附:安装CentOS-Stream9系统7.1ansible执行过程7.2安装ansible,ansible-navigator7.2部署ansible7.3ansible-naviga......
  • ansible_playbook任务控制
    ansible_playbook任务控制:条件判断when循环语句with_items触发器handlers标签tags根据指定的标签执行,调试包含include错误忽略ignore_errors错误处理changed_when1.条件判断when使用()变量不使用{{}}自带的变量名字获取:ansibleservers-ihosts.cfg-msetup1)示例:当系统为Cen......
  • Ansible系列:选项和常用模块 转载
    1.1ansible命令解释通过ansible命令执行的任务称为ad-hoc命令(任务),其实它是相对playbook而言的。通常,命令行用来实现ansible的批量管理功能,playbook用来实现批量自动化功能。【以下为普通选项:】-aMODULE_ARGS--args=MODULE_ARGS传递参数给模块--ask-vault-pass询问vault的密......