自动化运维工具ansible实战

什么ansible

ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。

ansible的特点

  • 部署简单,只需在主控端部署Ansible环境,被控端无需做任何操作;
  • 默认使用SSH协议对设备进行管理;
  • 有大量常规运维操作模块,可实现日常绝大部分操作;
  • 配置简单、功能强大、扩展性强;
  • 支持API及自定义模块,可通过Python轻松扩展;
  • 通过Playbooks来定制强大的配置、状态管理;
  • 轻量级,无需在客户端安装agent,更新时,只需在操作机上进行一次更新即可;
  • 提供一个功能强大、操作性强的Web管理界面和REST API接口——AWX平台。

ansible的任务执行:

Ansible 系统由控制主机对被管节点的操作方式可分为两类,即adhocplaybook

  • ad-hoc模式(点对点模式)
      使用单个模块,支持批量执行单条命令。ad-hoc 命令是一种可以快速输入的命令,而且不需要保存起来的命令。就相当于bash中的一句话shell。

  • playbook模式(剧本模式)
      是Ansible主要管理方式,也是Ansible功能强大的关键所在。playbook通过多个task集合完成一类功能,如Web服务的安装部署、数据库服务器的批量备份等。可以简单地把playbook理解为通过组合多条ad-hoc操作的配置文件。

ansible命令执行过程:

  • 加载自己的配置文件,默认/etc/ansible/ansible.cfg
  • 查找对应的主机配置文件,找到要执行的主机或者组;
  • 加载自己对应的模块文件,如 command;
  • 通过ansible将模块或命令生成对应的临时py文件(python脚本), 并将该文件传输至远程服务器;
  • 对应执行用户的家目录的.ansible/tmp/XXX/XXX.PY文件;
  • 给文件 +x 执行权限;
  • 执行并返回结果;
  • 删除临时py文件,sleep 0退出;

设置主机组

[web]
192.168.9.129

 ansible-doc命令

#获取全部模块的信息
[root@k8s-master ansible]# ansible-doc -l

#获取copy模块的使用帮助
[root@k8s-master ansible]# ansible-doc -s copy

 ansible配置公私钥

[root@k8s-master ansible]# ssh-keygen
[root@k8s-master ansible]# ssh-copy-id [email protected]

 

ansible的常用模块

1.主机连通性测试

[root@k8s-master ansible]#  ansible web -m ping
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3,
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}

 2.command模块

[root@k8s-master ansible]#  ansible web -m command -a "free -h"
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3,
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | CHANGED | rc=0 >>
               total        used        free      shared  buff/cache   available
Mem:           8.5Gi       3.3Gi       4.3Gi        69Mi       1.4Gi       5.3Gi
Swap:             0B          0B          0B

 3.shell模块

[root@k8s-master ansible]#  ansible web -m shell -a "cat /etc/passwd"
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3,
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync

 

4.copy模块

  • src    #被复制到远程主机的本地文件。可以是绝对路径,也可以是相对路径。如果路径是一个目录,则会递归复制,用法类似于"rsync"
  • content   #用于替换"src",可以直接指定文件的值
  • dest    #必选项,将源文件复制到的远程主机的绝对路径
  • backup   #当文件内容发生改变后,在覆盖之前把源文件备份,备份文件包含时间信息
  • directory_mode    #递归设定目录的权限,默认为系统默认权限
  • force    #当目标主机包含该文件,但内容不同时,设为"yes",表示强制覆盖;设为"no",表示目标主机的目标位置不存在该文件才复制。默认为"yes"
  • others    #所有的 file 模块中的选项可以在这里使用

复制文件

[root@k8s-master ~]# ansible web -m copy -a 'src=/root/cpu_total.sh dest=/data/cpu_total.sh'
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3,
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "checksum": "64851646b4d275ce61e4985bdb5ac18e4d83b833",
    "dest": "/data/cpu_total.sh",
    "gid": 0,
    "group": "root",
    "md5sum": "eec33fdd32df391a27f2795535b4eacf",
    "mode": "0644",
    "owner": "root",
    "secontext": "system_u:object_r:default_t:s0",
    "size": 39,
    "src": "/root/.ansible/tmp/ansible-tmp-1740048210.3642464-823543-272310780923407/source",
    "state": "file",
    "uid": 0
}

 给定内容生成文件,并指定权限

[root@k8s-master ~]# ansible web -m copy -a 'content="my name is wyx" dest=/root/test1.txt mode=666'
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3,
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "checksum": "88a1819f44f50263826c7e75ff0af055d9d1bd07",
    "dest": "/root/test1.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "d9ac81bea3f272676d58728b2a6fccf4",
    "mode": "0666",
    "owner": "root",
    "secontext": "system_u:object_r:admin_home_t:s0",
    "size": 14,
    "src": "/root/.ansible/tmp/ansible-tmp-1740048242.9820096-902225-126836339119050/source",
    "state": "file",
    "uid": 0
}

修改问价内容,选择覆盖备份

[root@k8s-master ansible]# ansible web -m copy -a 'content="hellp" backup=yes dest=/root/test1.txt mode=0666'
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at
/usr/bin/python3, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "backup_file": "/root/test1.txt.3659291.2025-02-16@01:18:24~",
    "changed": true,
    "checksum": "d4baaad7a68a379b1e133e0fea0603051b0124ca",
    "dest": "/root/test1.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "c983190483df167d2a3841463c2a9341",
    "mode": "0666",
    "owner": "root",
    "secontext": "system_u:object_r:admin_home_t:s0",
    "size": 5,
    "src": "/root/.ansible/tmp/ansible-tmp-1740050065.5839632-897695-4201364216735/source",
    "state": "file",
    "uid": 0
}

5.file模块

force  #需要在两种情况下强制创建软链接,一种是源文件不存在,但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no
group  #定义文件/目录的属组。后面可以加上mode:定义文件/目录的权限
owner  #定义文件/目录的属主。后面必须跟上path:定义文件/目录的路径
recurse  #递归设置文件的属性,只对目录有效,后面跟上src:被链接的源文件路径,只应用于state=link的情况
dest  #被链接到的路径,只应用于state=link的情况
state  #状态,有以下选项:

directory:如果目录不存在,就创建目录
file:即使文件不存在,也不会被创建
link:创建软链接
hard:创建硬链接
touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
absent:删除目录、文件或者取消链接文件

创建目录

[root@k8s-master conf.d]# ansible web -m file -a 'path=/data/app state=directory'

192.168.9.129 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0755",
    "owner": "root",
    "path": "/data/app",
    "secontext": "unconfined_u:object_r:default_t:s0",
    "size": 4096,
    "state": "directory",
    "uid": 0
}
[root@k8s-master conf.d]# ansible web -m shell -a 'ls -a /data'
192.168.9.129 | CHANGED | rc=0 >>
.
..
app
cpu_total.sh

 创建链接文件

[root@k8s-master conf.d]# ansible web -m file -a 'path=/data/bbb.jpg src=aaa.jpg state=link force=yes'
192.168.9.129 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "dest": "/data/bbb.jpg",
    "src": "aaa.jpg"
}
[root@k8s-master conf.d]# ansible web -m shell -a 'ls -l /data'
192.168.9.129 | CHANGED | rc=0 >>
total 8
drwxr-xr-x. 2 root root 4096 Feb 16 22:32 app
lrwxrwxrwx. 1 root root    7 Feb 16 22:39 bbb.jpg -> aaa.jpg
-rw-r--r--. 1 root root   39 Feb 16 00:44 cpu_total.sh

 删除文件

[root@k8s-master conf.d]# ansible web -m file -a 'path=/data/app state=absent'
192.168.9.129 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "path": "/data/app",
    "state": "absent"
}
[root@k8s-master conf.d]# ansible web -m shell -a 'ls -l /data'
192.168.9.129 | CHANGED | rc=0 >>
total 4
lrwxrwxrwx. 1 root root  7 Feb 16 22:39 bbb.jpg -> aaa.jpg
-rw-r--r--. 1 root root 39 Feb 16 00:44 cpu_total.sh

 

6.fetch模块

该模块用于从远程某主机获取文件到本地

[root@k8s-master conf.d]# ansible web -m fetch -a "src=/root/test1.txt dest=/data flat=yes"

192.168.9.129 | CHANGED => {
    "changed": true,
    "checksum": "d4baaad7a68a379b1e133e0fea0603051b0124ca",
    "dest": "/data",
    "md5sum": "c983190483df167d2a3841463c2a9341",
    "remote_checksum": "d4baaad7a68a379b1e133e0fea0603051b0124ca",
    "remote_md5sum": null
}
[root@k8s-master conf.d]# ll /data 
-rw-r--r--. 1 root root 5 Feb 21 15:07 /data
[root@k8s-master conf.d]# cat /data 
hellp

 

7.cron模块

添加计划任务

[root@k8s-master conf.d]# ansible web -m cron -a 'name="ntp update every 5 min" minute=*/5 job="/sbin/ntpdate 192.168.9.128 &> /dev/null"'
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "envs": [],
    "jobs": [
        "ntp update every 5 min"
    ]
}
[root@k8s-master conf.d]# ansible web -m shell -a "crontab -l"
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | CHANGED | rc=0 >>
#Ansible: ntp update every 5 min
*/5 * * * * /sbin/ntpdate 192.168.9.128 &> /dev/null

 删除计划任务

[root@k8s-master conf.d]# ansible web -m cron -a 'name="ntp update every 5 min" minute=*/5 job="/sbin/ntpdate 192.168.9.128 &> /dev/null" state=absent'
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "envs": [],
    "jobs": []
}
[root@k8s-master conf.d]# ansible web -m shell -a "crontab -l"
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | CHANGED | rc=0 >>

8.yum模块

name=  #所安装的包的名称
state=  #present--->安装, latest--->安装最新的, absent---> 卸载软件。
update_cache  #强制更新yum的缓存
conf_file  #指定远程yum安装时所依赖的配置文件(安装本地已有的包)。
disable_pgp_check  #是否禁止GPG checking,只用于presentor latest
disablerepo  #临时禁止使用yum库。 只用于安装或更新时。
enablerepo  #临时使用的yum库。只用于安装或更新时。

[root@k8s-master conf.d]# ansible web -m yum -a "name=tree state=present"
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Installed: tree-2.0.4-2.oe2203sp1.x86_64"
    ]
}

 

9.service模块

  • arguments #命令行提供额外的参数
  • enabled #设置开机启动。
  • name= #服务名称
  • runlevel #开机启动的级别,一般不用指定。
  • sleep #在重启服务的过程中,是否等待。如在服务关闭以后等待2秒再启动。(定义在剧本中。)
  • state #有四种状态,分别为:started--->启动服务, stopped--->停止服务, restarted--->重启服务, reloaded--->重载配置

检测elk服务是否自启动

[root@k8s-master conf.d]# ansible web -m service -a "name=elasticsearch state=started enabled=true"
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "enabled": true,
    "name": "elasticsearch",
    "state": "started",

 关闭服务

[root@k8s-master conf.d]# ansible web -m service -a "name=elasticsearch state=stopped"
192.168.9.129 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "name": "elasticsearch",
    "state": "stopped",

10.user模块

  • comment  # 用户的描述信息
  • createhome  # 是否创建家目录
  • force  # 在使用state=absent时, 行为与userdel –force一致.
  • group  # 指定基本组
  • groups  # 指定附加组,如果指定为(groups=)表示删除所有组
  • home  # 指定用户家目录
  • move_home  # 如果设置为home=时, 试图将用户主目录移动到指定的目录
  • name  # 指定用户名
  • non_unique  # 该选项允许改变非唯一的用户ID值
  • password  # 指定用户密码
  • remove  # 在使用state=absent时, 行为是与userdel –remove一致
  • shell  # 指定默认shell
  • state  # 设置帐号状态,不指定为创建,指定值为absent表示删除
  • system  # 当创建一个用户,设置这个用户是系统用户。这个设置不能更改现有用户
  • uid  # 指定用户的uid

创建用户 

oot@k8s-master conf.d]# ansible web -m user -a "name=xiaomin uid=11111"

192.168.9.129 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "comment": "",
    "create_home": true,
    "group": 11111,
    "home": "/home/xiaomin",
    "name": "xiaomin",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 11111
}

[root@k8s-master conf.d]# ansible web -m shell -a "cat /etc/passwd | grep xiaomin"
192.168.9.129 | CHANGED | rc=0 >>
xiaomin:x:11111:11111::/home/xiaomin:/bin/bash

删除用户

[root@k8s-master conf.d]# ansible web -m user  -a "name=xiaomin state=absent"
192.168.9.129 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "force": false,
    "name": "xiaomin",
    "remove": false,
    "state": "absent"
}

11.group模块

  • gid=  #设置组的GID号
  • name=  #指定组的名称
  • state=  #指定组的状态,默认为创建,设置值为absent为删除
  • system=  #设置值为yes,表示创建为系统组

 创建组

[root@k8s-master conf.d]# ansible web -m group -a "name=test gid=12222"
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "gid": 12222,
    "name": "test",
    "state": "present",
    "system": false
}

删除组

[root@k8s-master conf.d]# ansible web -m group -a "name=test state=absent"
192.168.9.129 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "name": "test",
    "state": "absent"
}
[root@k8s-master conf.d]# ansible web -m shell -a "cat /etc/group | grep test"
192.168.9.129 | FAILED | rc=1 >>
non-zero return code

 12.script模块

[root@k8s-master ~]# ansible web -m script -a '/tmp/df.sh' 
192.168.9.129 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.9.129 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.9.129 closed."
    ],
    "stdout": "",
    "stdout_lines": []
}

[root@k8s-master ~]# ansible web -m shell -a "cat /tmp/disk_total.log"
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | CHANGED | rc=0 >>
Sun Feb 16 11:52:19 PM CST 2025
Filesystem                  Size  Used Avail Use% Mounted on
devtmpfs                    4.0M     0  4.0M   0% /dev
tmpfs                       1.7G     0  1.7G   0% /dev/shm
tmpfs                       676M   69M  608M  11% /run
tmpfs                       4.0M     0  4.0M   0% /sys/fs/cgroup
/dev/mapper/openeuler-root   17G   11G  5.4G  66% /
tmpfs                       1.7G   11M  1.7G   1% /tmp
/dev/sda1                   974M  193M  714M  22% /boot
[root@k8s-master ~]# cat /tmp/df.sh 
#!/bin/bash
date >> /tmp/disk_total.log
df -lh >> /tmp/disk_total.log

 13.setup模块

该模块主要用于收集信息,是通过调用facts组件来实现的。

查看信息

[root@k8s-master ~]# ansible web -m setup -a 'filter="*mem*"'
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 4963,
        "ansible_memory_mb": {
            "nocache": {
                "free": 5696,
                "used": 3058
            },
            "real": {
                "free": 4963,
                "total": 8754,
                "used": 3791
            },
            "swap": {
                "cached": 0,
                "free": 0,
                "total": 0,
                "used": 0
            }
        },
        "ansible_memtotal_mb": 8754,
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false
}

 保存信息

[root@k8s-master ~]# ansible web -m setup -a 'filter=*mem*' --tree /tmp/facts
[WARNING]: Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.9.129 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 4620,
        "ansible_memory_mb": {
            "nocache": {
                "free": 5426,
                "used": 3328
            },
            "real": {
                "free": 4620,
                "total": 8754,
                "used": 4134
            },
            "swap": {
                "cached": 0,
                "free": 0,
                "total": 0,
                "used": 0
            }
        },
        "ansible_memtotal_mb": 8754,
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false
}
[root@k8s-master ~]# cd /tmp/facts/
[root@k8s-master facts]# ll
total 4
-rw-r--r--. 1 root root 623 Feb 21 16:11 192.168.9.129
[root@k8s-master facts]# cat 192.168.9.129 
{"ansible_facts": {"ansible_memfree_mb": 4620, "ansible_memory_mb": {"nocache": {"free": 5426, "used": 3328}, "real": {"free": 4620, "total": 8754, "used": 4134}, "swap": {"cached": 0, "free": 0, "total": 0, "used": 0}}, "ansible_memtotal_mb": 8754, "discovered_interpreter_python": "/usr/bin/python3"}, "changed": false, "warnings": ["Platform linux on host 192.168.9.129 is using the discovered Python interpreter at /usr/bin/python3, but future installation of another Python interpreter could change this. See https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information."]}[root@k8s-master facts]# 

你可能感兴趣的:(运维,自动化,ansible,云原生)