网站集群批量管理-Ansible剧本与变量-二、剧本案例

时间:2025-04-10 07:55:55

1、案例01: 创建目录并分发文件

创建目录/server/files/etc/hosts文件并且发送过去/server/files

- hosts: all
  tasks:
    - name: 01 创建目录/server/files
      file: 
        path=/server/files 
        state=directory
    - name: 02 分发文件
      copy: 
        src=/etc/hosts 
        dest=/server/files

2、案例02:分发软件包,安装软件包,启动服务

zabbix-agent软件包(下载)—》 安装软件包—》配置(略)—》启动开机自启动

- hosts: all
  takes: 
    - name: 01 软件包下载
      get_url: 
        url: https://mirrors.aliyun.com/zabbix/zabbix/6.0/rhel/7/x86_64/zabbix-agent-6.0.13-release1.el7.x86_64.rpm
        dest: /tmp/
        validate_certs: no
    - name: 02 安装软件包
       yum:
        name:/tmp/zabbix-agent-6.0.13-release1.el7.x86_64.rpm
        state=insatlled
    - name: 03 配置 
       debug:
        msg: "进行配置zabbix-agent"
    - name: 04 启动
       systemd:
        name: zabbix-agent
        enabled: yes
        state: started
ansible all -m shell -a 'ps -ef | grep zabbix'

不能使用-m command。在 Ansible 的命令模块中,你需要以单个字符串的形式指定要执行的命令,而不能使用管道符号 |

3、案例03:nfs服务

  • nfs服务端:在backup上部署nfs服务,共享/backup-nfs目录,all_squash,匿名用户:nfsnobody
  • nfs客户端:web挂载 /ans-upload目录挂载nfs服务端共亭的/backup-nfs(永久挂载)

写剧本必备-列出流程

服务端流程:

  • 部署nfs-utils,rpcbind
  • 修改配置文件
  • 创建共享目录并改所有者
  • 启动服务rpcbind,nfs(注意顺序)

客户端流程:

  • 安装nfs-utils2.
  • 挂载与永久挂载
- hosts: nfs
  tasks: 
    - name: 01 部署nfs-utils,rpcbind
      yum: 
        name: nfs-utils
        state: installed
    - name: 02 修改配置文件
      lineinfile:
        path: /etc/exports
        line: "/backup-nfs/ 10.0.0.0/24(rw)"
        create: true
    - name: 03 创建共享目录并且修改权限
      file: 
        path: /backup-nfs/
        state: directory
        owner: nfsnobody
        group: nfsnobody
    - name: 04-1 依次启动服务rpc
      systemd: 
        name: rpcbind
        enabled: yes
        state: started
    - name: 04-2 依次启动服务nfs
      systemd: 
        name: nfs
        enabled: yes
        state: started
- hosts: web
  tasks: 
  - name: 01 部署nfs-utils,rpcbind
    yum: 
      name: nfs-utils
      state: installed
  - name: 02 永久挂载
    mount:
      src: 10.0.0.31:/backup-nfs/
      path: /data/
      fstype: nfs
      state: mounted