ansible作业

ansible作业

0.ansible了解
roles:多个角色的集合目录, 可以将多个的role,分别放至roles目录下的独立子目录中,如下示例
roles/
 mysql/
 nginx/
 tomcat/
 redis/
 
 
 
 默认roles存放路径
 /root/.ansible/roles
/usr/share/ansible/roles
/etc/ansible/roles


roles目录结构:
playbook1.yml
playbook2.yml
roles/
 project1/
   tasks/
   files/
   vars/       
   templates/
   handlers/
   default/    
   meta/       
 project2/
   tasks/
   files/
   vars/       
   templates/
   handlers/
   default/    
   meta/
   
   
   
   Roles各目录作用:
roles/project/ :项目名称,有以下子目录
files/ :存放由copy或script模块等调用的文件
templates/:template模块查找所需要模板文件的目录
tasks/:定义task,role的基本元素,至少应该包含一个名为main.yml的文件;其它的文件需要在
此文件中通过include进行包含
handlers/:至少应该包含一个名为main.yml的文件;此目录下的其它的文件需要在此文件中通过
include进行包含
vars/:定义变量,至少应该包含一个名为main.yml的文件;此目录下的其它的变量文件需要在此
文件中通过include进行包含,也可以通过项目目录中的group_vars/all定义变量,从而实现角色通用
代码和项目数据的分离
meta/:定义当前角色的特殊设定及其依赖关系,至少应该包含一个名为main.yml的文件,其它文
件需在此文件中通过include进行包含
default/:设定默认变量时使用此目录中的main.yml文件,比vars的优先级低




#安装ansible
yum install epel-release ansible libselinux-python -y

前提你配置好了阿里云的epel源可以直接安装
yum install ansible -y 

[root@ansible-1 ~]# ansible --version
ansible 2.9.27
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Nov 14 2023, 16:14:06) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
  
  
  
  #主机清单文件(主机分组)
  vim /etc/ansible/hosts 

[web]
10.0.1.185
10.0.1.186
10.0.1.187

[nfs]
10.0.1.188

[backup]
10.0.1.189

[zabbix]
10.0.1.184
1.整理ansible 常用命令
###--ansible----常用命令50条

ansible --version: 查看 Ansible 版本信息。
ansible all -m ping: 检查所有主机的连通性。
ansible-playbook playbook.yml: 运行指定的 Ansible Playbook 文件。
ansible-doc module_name: 查看指定模块的帮助文档。
ansible-config view: 查看当前 Ansible 配置信息。
ansible-inventory --list: 列出当前主机清单中定义的所有主机和组。
ansible-vault create file.yml: 创建一个加密的 Ansible Vault 文件。
ansible-galaxy init role_name: 初始化一个新的 Ansible 角色。
ansible-lint playbook.yml: 检查 Ansible Playbook 文件的语法错误和最佳实践。
ansible-vault encrypt file.yml: 加密一个现有的 YAML 文件。
ansible-vault decrypt file.yml: 解密一个加密的 YAML 文件。
ansible-pull -U repository_url playbook.yml: 在目标主机上执行 Ansible Playbook 并从代码仓库拉取最新的副本。
ansible-doc -l: 列出所有可用的 Ansible 模块。
ansible-galaxy install role_name: 安装一个 Ansible 角色。
ansible-vault edit file.yml: 编辑一个已加密的 YAML 文件。
ansible-playbook playbook.yml --tags=tag_name: 只运行指定标签的任务。
ansible all -a "command": 在所有主机上运行指定的命令。
ansible all -m shell -a "command": 在所有主机上运行指定的 Shell 命令。
ansible all -m file -a "path=/path/to/file state=absent": 删除指定路径下的文件。
ansible all -m copy -a "src=file.txt dest=/path/to/dest": 将本地文件复制到远程主机。
ansible all -m yum -a "name=package state=present": 在所有主机上安装指定的 Yum 包。
ansible all -m service -a "name=service state=started": 启动指定的服务。
ansible all -m user -a "name=username state=present": 创建一个新用户。
ansible all -m command -a "echo 'hello'": 在所有主机上运行指定的命令。
ansible all -b -m apt -a "name=package state=present": 使用管理员权限在所有主机上安装指定的 Apt 包。
ansible all -i hosts_file -m ping: 使用自定义的主机清单文件,检查所有主机的连通性。
ansible-playbook playbook.yml --limit=hostname: 限制只在指定的主机上运行 Playbook。
ansible-playbook playbook.yml --check: 以模拟模式运行 Playbook,不会实际修改系统状态。
ansible-playbook playbook.yml --diff: 在执行任务时显示更改的详细信息。
ansible-vault rekey file.yml: 更改 Ansible Vault 文件的加密密码。
ansible-galaxy search search_term: 搜索 Ansible Galaxy 上可用的角色。
ansible all -m setup: 收集所有主机的系统信息。
ansible all -m debug -a "var=ansible_hostname": 打印指定变量的值。
ansible-doc -s module_name: 显示指定模块的示例用法。
ansible-galaxy init --offline role_name: 在离线模式下初始化一个新的 Ansible 角色。
ansible all --list-hosts: 列出所有主机清单中定义的主机。
ansible-vault encrypt_string 'password' --name 'var_name': 加密一个字符串并将其存储为 Ansible 变量。
ansible all -m lineinfile -a "dest=file line='text' state=present": 在文件中插入一行文本。
ansible all -m service -a "name=service state=restarted": 重新启动指定的服务。
ansible all -m package -a "name=package state=latest": 在所有主机上更新指定的软件包。
ansible all -m synchronize -a "src=/path/to/src dest=/path/to/dest": 将本地目录同步到远程主机。
ansible all -m lineinfile -a "dest=file regexp='regex' line='replacement'": 替换文件中匹配正则表达式的行。
ansible-galaxy remove role_name: 删除指定的 Ansible 角色。
ansible all -m apt_repository -a "repo='repo_url' state=present": 添加一个 Apt 仓库。
ansible all -m shell -a "echo $VAR": 打印远程主机上的环境变量的值。
ansible all -m cron -a "name='cron_job' minute='*/5' job='command'": 创建一个定时任务。
ansible-playbook playbook.yml --syntax-check: 检查 Playbook 文件的语法错误。
ansible all -m setup -a "filter=ansible_distribution*": 过滤收集的系统信息。
ansible all --become -m copy -a "src=file.txt dest=/path/to/dest":以管理员权限将本地文件复制到远程主机。
ansible all -m file -a "path=/path/to/file owner=user group=group": 修改文件的所有者和所属组。
2.批量执行一个命令 比如批量查看磁盘
#步骤

0.安装ansible

1.打通秘钥


2.配置清单文件


3.创建剧本目录和角色拆分目录



4.单命令执行(查看磁盘)

ansible all -m shell -a "df -h"



5.剧本实现(查看磁盘)

---
- name: Gather Disk Usage and Save to Log
  hosts: all  # 或指定特定的主机组
  gather_facts: no
  tasks:
    - name: Execute df -h on remote hosts
      command: df -h
      register: disk_usage

    - name: Save output to local file
      copy:
        content: "{{ disk_usage.stdout }}"
        dest: /etc/ansible/df.log
        mode: '0644'
      delegate_to: localhost
      
      








具体效果:
[root@ansible-1 roles]# ansible all -m shell -a "df -h"
10.0.1.186 | CHANGED | rc=0 >>
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        475M     0  475M   0% /dev
tmpfs           487M     0  487M   0% /dev/shm
tmpfs           487M  7.6M  479M   2% /run
tmpfs           487M     0  487M   0% /sys/fs/cgroup
/dev/sda2        94G  2.1G   91G   3% /
/dev/sda3        47G   33M   47G   1% /data
/dev/sda1      1014M  153M  862M  16% /boot
10.0.1.187 | CHANGED | rc=0 >>
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        475M     0  475M   0% /dev
tmpfs           487M     0  487M   0% /dev/shm
tmpfs           487M  7.6M  479M   2% /run
tmpfs           487M     0  487M   0% /sys/fs/cgroup
/dev/sda2        94G  2.1G   91G   3% /
/dev/sda3        47G   33M   47G   1% /data
/dev/sda1      1014M  153M  862M  16% /boot
10.0.1.189 | CHANGED | rc=0 >>
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        475M     0  475M   0% /dev
tmpfs           487M     0  487M   0% /dev/shm
tmpfs           487M  7.6M  479M   2% /run
tmpfs           487M     0  487M   0% /sys/fs/cgroup
/dev/sda2        94G  2.1G   92G   3% /
/dev/sda3        47G   33M   47G   1% /data
/dev/sda1      1014M  153M  862M  16% /boot
10.0.1.188 | CHANGED | rc=0 >>
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        475M     0  475M   0% /dev
tmpfs           487M     0  487M   0% /dev/shm
tmpfs           487M  7.6M  479M   2% /run
tmpfs           487M     0  487M   0% /sys/fs/cgroup
/dev/sda2        94G  2.3G   91G   3% /
/dev/sda3        47G   33M   47G   1% /data
/dev/sda1      1014M  153M  862M  16% /boot
10.0.1.185 | CHANGED | rc=0 >>
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        475M     0  475M   0% /dev
tmpfs           487M     0  487M   0% /dev/shm
tmpfs           487M  7.6M  479M   2% /run
tmpfs           487M     0  487M   0% /sys/fs/cgroup
/dev/sda2        94G  2.1G   91G   3% /
/dev/sda3        47G   33M   47G   1% /data
/dev/sda1      1014M  153M  862M  16% /boot
3.批量安装一个tomcat
tomcat网址:https://archive.apache.org/dist/tomcat/tomcat-7/


----------------------------------------------------------------------------------------
                             剧本一键安装方式(playbook)
----------------------------------------------------------------------------------------


环境:虚拟机
ansible:10.0.1.184
web1:10.0.1.185
web2:10.0.1.186
web3:10.0.1.187


0.上传jdk和Tomcat压缩包到/usr/local目录下



1.#在ansible机器上执行
[root@ansible-1 playbook]# cat tomcatyj.yml 
---
- hosts: web
  become: yes  # 使用sudo权限执行任务
  tasks:
    # 配置JDK
    - name: Copy JDK archive
      copy:
        src: /usr/src/jdk-11.0.14_linux-x64_bin.tar.gz
        dest: /usr/src/
    
    - name: Unarchive JDK
      unarchive:
        src: /usr/src/jdk-11.0.14_linux-x64_bin.tar.gz
        dest: /usr/local/
        remote_src: yes
        creates: /usr/local/jdk-11.0.14
    
    - name: Set Java Home in profile
      lineinfile:
        path: /etc/profile
        line: 'JAVA_HOME=/usr/local/jdk-11.0.14'
        state: present
        create: yes
    
    - name: Add Java bin to PATH in profile
      lineinfile:
        path: /etc/profile
        line: 'export PATH=$JAVA_HOME/bin:$PATH'
        state: present
    
    # 配置Tomcat
    - name: Copy Tomcat archive
      copy:
        src: /usr/src/apache-tomcat-9.0.59.tar.gz
        dest: /usr/src/
    
    - name: Unarchive Tomcat
      unarchive:
        src: /usr/src/apache-tomcat-9.0.59.tar.gz
        dest: /usr/local/
        remote_src: yes
        creates: /usr/local/apache-tomcat-9.0.59
    
    - name: Rename Tomcat directory
      command: mv /usr/local/apache-tomcat-9.0.59 /usr/local/tomcat
      args:
        creates: /usr/local/tomcat  # 确保只在必要时执行
    
    # 注意:通常不需要手动复制startup.sh,因为解压后已包含
    # 如果确有特殊需求,可使用copy模块替换shell
    
    # 通知Handler启动Tomcat
    - name: Notify handler to start Tomcat
      debug:
        msg: "Tomcat installation completed, triggering start."
      notify: Start Tomcat

  handlers:
    - name: Start Tomcat
      command: /usr/local/tomcat/bin/startup.sh
      async: 180  # 异步执行,超时时间180秒
      poll: 0     # 不轮询结果,让其后台运行


  
  2.#写入启动脚本(ansible上执行)
  [root@java-server src]# startup.sh 
#!/bin/sh
source /etc/profile




3.#批量执行环境变量和启动tomcat(ansible执行)
[root@ansible-1 playbook]# ansible web -m shell -a "source /etc/profile;bash /usr/local/tomcat/bin/startup.sh "





4.#执行效果
[root@ansible-1 playbook]# ansible web -m shell -a "source /etc/profile;bash /usr/local/tomcat/bin/startup.sh "
10.0.1.186 | CHANGED | rc=0 >>
Using CATALINA_BASE:   /usr/local/tomcat
Using CATALINA_HOME:   /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:        /usr/local/jdk-11.0.14
Using CLASSPATH:       /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Tomcat started.
10.0.1.185 | CHANGED | rc=0 >>
Using CATALINA_BASE:   /usr/local/tomcat
Using CATALINA_HOME:   /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:        /usr/local/jdk-11.0.14
Using CLASSPATH:       /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Tomcat started.
10.0.1.187 | CHANGED | rc=0 >>
Using CATALINA_BASE:   /usr/local/tomcat
Using CATALINA_HOME:   /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:        /usr/local/jdk-11.0.14
Using CLASSPATH:       /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Tomcat started.
10.0.1.184 | CHANGED | rc=0 >>
Using CATALINA_BASE:   /usr/local/tomcat
Using CATALINA_HOME:   /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:        /usr/local/jdk-11.0.14
Using CLASSPATH:       /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Tomcat started.
































---------------------------------------------------------------------------------------

                                      角色安装
----------------------------------------------------------------------------------------

### 步骤1: 准备角色目录结构

首先,在Ansible控制节点上为Tomcat角色创建必要的目录结构:


mkdir -pv /etc/ansible/roles/tomcat/{tasks,handlers,files,templates,vars}


### 步骤2: 编写角色文件

# tasks/main.yml
yaml
- include_tasks: install.yml
- include_tasks: configure.yml
- include_tasks: service.yml


# tasks/install.yml
yaml
- name: Download Tomcat tarball
  get_url:
    url: "https://archive.apache.org/dist/tomcat/tomcat-9/v9.0.65/bin/apache-tomcat-9.0.65.tar.gz"
    dest: /opt/tomcat.tar.gz
    mode: '0644'
  register: tomcat_download

- name: Extract Tomcat
  unarchive:
    src: "{{ tomcat_download.dest }}"
    dest: /opt/
    remote_src: yes
    creates: /opt/apache-tomcat-9.0.65
    extra_opts: [--strip-components=1]
  when: tomcat_download.changed

- name: Set owner and permissions
  file:
    path: /opt/apache-tomcat-9.0.65
    owner: tomcat
    group: tomcat
    mode: '0755'


# tasks/configure.yml
yaml
- name: Copy server.xml configuration
  template:
    src: server.xml.j2
    dest: /opt/apache-tomcat-9.0.65/conf/server.xml
  notify: restart_tomcat

- name: Copy startup script
  template:
    src: tomcat.init.j2
    dest: /etc/init.d/tomcat
    mode: '0755'


# tasks/service.yml
yaml
- name: Ensure Tomcat is running and enabled at boot
  service:
    name: tomcat
    state: started
    enabled: yes


# handlers/main.yml
yaml
- name: Restart Tomcat Service
  service:
    name: tomcat
    state: restarted


# templates/server.xml.j2
xml
<!-- 这里放置你的server.xml配置模板 -->
<Server port="8005" shutdown="SHUTDOWN">
  <Service name="Catalina">
    <!-- Define the Tomcat AJP connector on port 8009 -->
    <!-- ... -->
  </Service>
</Server>


# templates/tomcat.init.j2

#!/bin/
# 这里是你的初始化脚本模板,用于启动、停止、重启Tomcat服务


# vars/main.yml
yaml
tomcat_user: tomcat
tomcat_group: tomcat
tomcat_version: 9.0.65


### 步骤3: 创建Playbook

创建一个Playbook文件,如tomcat_deploy.yml,来调用Tomcat角色:

yaml
- name: Deploy Apache Tomcat
  hosts: tomcat_servers  # 确保这个组名与你的inventory文件中定义的一致,指向目标主机
  become: yes
  roles:
    - tomcat


### 步骤4: 执行Playbook

在确保你的Ansible Inventory已正确配置并包含了目标主机后,执行Playbook:


ansible-playbook -i inventory.ini tomcat_deploy.yml














### 注意事项
- 确保你的目标主机上已安装Java运行环境,因为Tomcat运行依赖Java。
- 上述示例下载的是Tomcat 9.0.65版本,根据需要可以修改URL下载其他版本。
- 请根据实际情况调整inventory.ini中的主机分组和主机信息。
- server.xml.j2 和 tomcat.init.j2 文件内容需根据实际需求定制。
4.批量安装一个nginx
nginx网址:https://nginx.org/en/download.html




# 步骤1: 准备角色目录结构

在Ansible控制节点上创建nginx角色的目录结构:


mkdir -pv /etc/ansible/roles/nginx/{tasks,handlers,templates,files,vars}


# 步骤2: 编写角色文件

#创建main(连接这个目录下的其他yml文件)
   vim /etc/ansible/roles/nginx/tasks/main.yml

- include_tasks: install.yml
- include_tasks: config.yml
- include_tasks: index.yml
- include_tasks: service.yml

#创建install
  vim /etc/ansible/roles/nginx/tasks/install.yml

- name: Install Nginx
  yum:
    name: nginx
    state: present

#创建config
  vim /etc/ansible/roles/nginx/tasks/config.yml

- name: Configure Nginx
  template:
    src: "{{ ansible_distribution_major_version }}.conf.j2"
    dest: /etc/nginx/nginx.conf
  notify: restart_nginx


#创建index
   vim /etc/ansible/roles/nginx/tasks/index.yml

- name: Copy index.html to Document Root
  copy:
    src: files/index.html
    dest: /usr/share/nginx/html/index.html

#创建service(启动文件)
  vim /etc/ansible/roles/nginx/tasks/service.yml

- name: Manage Nginx Service
  service:
    name: nginx
    state: started
    enabled: yes


#创建handlers下的main文件
  vim /etc/ansible/roles/nginx/handlers/main.yml

- name: Restart Nginx Service
  service:
    name: nginx
    state: restarted

#创建模版配置文件(这里是nginx默认配置文件路径的地方)
 vim /etc/ansible/roles/nginx/templates/7.conf.j2

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2;
#        listen       [::]:443 ssl http2;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}



#如果是其他系统,也可以创建其他系统的配置文件(各系统的不同,可能会有些变化)
 vim /etc/ansible/roles/nginx/templates/8.conf.j2

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2;
#        listen       [::]:443 ssl http2;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}






#创建vars下的变量
vim /etc/ansible/roles/nginx/vars/main.yml

user: nginx

#创建file下的网页文件(看自己需求了)
vim  /etc/ansible/roles/nginx/files/index.html
echo 老六666 > index.html




# 步骤3: 创建Playbook

在Ansible控制节点的适当位置创建Playbook文件,例如nginx_deploy.yml:


- name: Deploy Nginx to CentOS 7 Hosts
  hosts: webservers  # 确保这个组名与你的inventory文件中定义的一致,指向CentOS 7的主机
  become: yes
  roles:
    - nginx


# 步骤4: 执行Playbook

确保您的Ansible Inventory文件已正确设置,并包含了目标CentOS 7主机。然后,执行Playbook:


ansible-playbook -i inventory.ini nginx_deploy.yml


[root@ansible-1 templates]# ansible-playbook /etc/ansible/playbook/nginx_deploy.yml 

PLAY [Deploy Nginx to CentOS 7 Hosts] ***************************************************

TASK [Gathering Facts] ******************************************************************
ok: [10.0.1.187]
ok: [10.0.1.186]
ok: [10.0.1.184]
ok: [10.0.1.185]

TASK [nginx : include_tasks] ************************************************************
included: /etc/ansible/roles/nginx/tasks/install.yml for 10.0.1.185, 10.0.1.186, 10.0.1.187, 10.0.1.184

TASK [nginx : Install Nginx] ************************************************************
ok: [10.0.1.185]
ok: [10.0.1.187]
ok: [10.0.1.186]
ok: [10.0.1.184]

TASK [nginx : include_tasks] ************************************************************
included: /etc/ansible/roles/nginx/tasks/config.yml for 10.0.1.185, 10.0.1.186, 10.0.1.187, 10.0.1.184

TASK [nginx : Configure Nginx] **********************************************************
ok: [10.0.1.187]
ok: [10.0.1.186]
ok: [10.0.1.185]
ok: [10.0.1.184]

TASK [nginx : include_tasks] ************************************************************
included: /etc/ansible/roles/nginx/tasks/index.yml for 10.0.1.185, 10.0.1.186, 10.0.1.187, 10.0.1.184

TASK [nginx : Copy index.html to Document Root] *****************************************
ok: [10.0.1.186]
ok: [10.0.1.185]
ok: [10.0.1.187]
ok: [10.0.1.184]

TASK [nginx : include_tasks] ************************************************************
included: /etc/ansible/roles/nginx/tasks/service.yml for 10.0.1.185, 10.0.1.186, 10.0.1.187, 10.0.1.184

TASK [nginx : Manage Nginx Service] *****************************************************
ok: [10.0.1.187]
ok: [10.0.1.186]
ok: [10.0.1.185]
ok: [10.0.1.184]

PLAY RECAP ******************************************************************************
10.0.1.184                 : ok=9    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
10.0.1.185                 : ok=9    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
10.0.1.186                 : ok=9    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
10.0.1.187                 : ok=9    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   








#可能遇到的问题
1.变量名名称错误
2.yaml文件的格式缩进问题
3.引用的yml文件没有创建
4.目录错误
5.防火墙未放行
6.nginx的自定义配置文件(我这里是自定义的配置文件有问题,我换成默认的配置文件,故障解决,nginx这里可以后期调,ansible支持幂等性的)




# 注意事项
- 确保您的Ansible环境已经正确配置,并且能够连接到目标主机。
- 根据实际情况调整inventory.ini中的主机分组和主机信息。
- 本流程中,我们假设所有目标主机都是CentOS 7,如果需要同时支持CentOS 8,您可能需要在Playbook中加入条件判断,或调整配置策略来适应不同版本的系统。
5.就是借助 ansible 批量安装 zabbix-agent 客户端实现自动注册 完成批量监控服务器
#步骤


环境:
zabbix服务端:10.0.1.189
zabbix客户端1:10.0.1.185
zabbix客户端2:10.0.1.186
zabbix客户端3:10.0.1.187


1.安装ansible软件
yum install epel-release ansible libselinux-python -y

#前提你配置好了阿里云的epel源可以直接安装
yum install ansible -y 
ansible --version



 
 


2.配置免密

方式1:手动免密
ssh-keygen
 ssh-copy-id root@10.0.1.185:
 ssh 10.0.1.185 ip a
 
 方式2:剧本批量免密
 ssh-keygen
 
vim /etc/ansible/playbook/ssh.yml 

---
- name: Configure SSH key
  hosts: all
  become: yes
  vars:
    public_key_file: "/root/.ssh/id_rsa.pub"  # 将此替换为您的公钥文件路径

  tasks:
    - name: Install OpenSSH server
      package:
        name: openssh-server
        state: present

    - name: Ensure SSH service is running
      service:
        name: sshd
        state: started
        enabled: yes

    - name: Allow SSH connections through firewall
      firewalld:
        service: ssh
        permanent: yes
        state: enabled

    - name: Temporarily disable SELinux
      selinux:
        state: disabled

    - name: Add SSH public key to authorized_keys
      authorized_key:
        user: "{{ ansible_user_id }}"
        state: present
        key: "{{ lookup('file', public_key_file) }}"



3.编写清单文件
vim /etc/ansible/hosts 

[web]
10.0.1.185
10.0.1.186
10.0.1.187

[nfs]
10.0.1.188

[backup]
10.0.1.189





4.更新证书/时间/mysql插件
sudo yum update
sudo yum install ca-certificates

ansible-galaxy collection install community.mysql

ansible-galaxy collection install community.mysql --ignore-certs



5.在ansible剧本目录下创建zabbix服务端剧本
vim /etc/ansible/playbook/zabbix_server.yml

--- 
- hosts: backup
  remote_user: root 
  gather_facts: yes  
  tasks:
  - name: wget zabbix_repo
    get_url: 
      url: "https://repo.zabbix.com/zabbix/5.0/rhel/7/x86_64/zabbix-release-5.0-1.el7.noarch.rpm"
      dest: "/tmp/zabbix-release-5.0-1.el7.noarch.rpm"
      validate_certs: no
  - name: yum install zabbix-release-5.0
    yum: 
      name: "/tmp/zabbix-release-5.0-1.el7.noarch.rpm"
      state: present
  - name: clean 
    shell: yum clean all;yum makecache fast
  - name: install zabbix-agent zabbix-get zabbix-sender zabbix-server-mysql  epel-release
    yum: 
      name: "{{ item }}"
      state: present
    with_items:
      #- epel-release
      - zabbix-agent 
      - zabbix-get
      - zabbix-sender
      - zabbix-server-mysql
      - bind-utils
  - name: touch mariadb.repo
    file: 
      path: "/etc/yum.repos.d/mariadb.repo"
      state: touch
      mode: 0644
  - name: insert mariadbrepo 
    lineinfile:
      path: "/etc/yum.repos.d/mariadb.repo"
      insertafter: EOF
      line: "[mariadb]"
  - name: insert baseurl gpgkey gpgcheck
    lineinfile:
      path: "/etc/yum.repos.d/mariadb.repo"
      insertafter: '[mariadb]'
      line: |
        name = MariaDB 
        baseurl = https://mirrors.ustc.edu.cn/mariadb/yum/10.4/centos7-amd64 
        gpgkey=https://mirrors.ustc.edu.cn/mariadb/yum/RPM-GPG-KEY-MariaDB 
        gpgcheck=0
  - name: install mariadb
    yum:
     name: "MariaDB-server,MariaDB-client,MySQL-python"
     state: present 
  - name: touch /etc/my.cnf.d/server.cnf
    file:
      path: "/etc/my.cnf.d/server.cnf"
      state: "touch"
  - name: "insert mariadbdata"
    lineinfile:
      path: "/etc/my.cnf.d/server.cnf"
      insertafter: EOF
      line: "[mysqld]"
  - name: "mariadbdata"
    lineinfile:
      path: "/etc/my.cnf.d/server.cnf"
      insertafter: '[mysqld]'
      line: |
       skip_name_resolve = ON
       innodb_file_per_table = ON
       innodb_buffer_pool_size = 256M
       max_connections = 2000
       log-bin = master-log
  - name: "service start mariadb"
    service:
     name: mariadb
     state: started
  - name: "Login to MySQL and create a database" 
    mysql_db:
     name: zabbix
     encoding: utf8
     collation: utf8_bin
     login_user: root
     login_host: localhost
     state: present
  - name: "grant all zabbix and set password keer"
    mysql_user:
     name: zabbix
     password: "keer"
     priv: "zabbix.*:ALL"
     host: "%"
     login_host: localhost
     state: present
  - name: "exec flush privileges"
    community.mysql.mysql_query:
     query: "flush privileges;"
  - name: "zcat data"
    vars: 
     sqldata: "/usr/share/doc/zabbix-server-mysql-*/create.sql.gz"
    shell:
     zcat {{ sqldata }} | mysql -uzabbix -pkeer -h 127.0.0.1 zabbix 
  - name: "backup /etc/zabbix/zabbix_server.conf"
    vars:
     zabbix_server: "/etc/zabbix/zabbix_server.conf"
     zabbix_server_bak: "/etc/zabbix/zabbix_server.conf_bak"
    copy:
     src: "{{ zabbix_server }}"
     dest: "{{ zabbix_server_bak }}"
     backup: "yes"
  - name: "change ListenPort"
    vars:
     file: /etc/zabbix/zabbix_server.conf
     db_passwd: keer
     db_port: 3306
    shell: |
     sed -ri 's/# ListenPort=10051/ListenPort=10051/' {{ file }};
     #sed -ri 's/# SourceIP=/SourceIP="{{ ansible_default_ipv4 }}"/' {{ file }};
     #sed -ri 's/# DBHost=/DBHost="{{ ansible_default_ipv4 }}"/' {{ file }};
     sed -i "s/# SourceIP=/SourceIP=$(dig +short myip.opendns.com @resolver1.opendns.com)/" {{ file }};
     sed -i "s/# DBHost=/DBHost=$(dig +short myip.opendns.com @resolver1.opendns.com)/"   {{ file }};
     sed -ri 's/# DBPassword=/DBPassword={{ db_passwd }}/' {{ file }};
     sed -ri 's/# DBPort=/DBPort={{ db_port }}/' {{ file }}
  - name: systemctl start zabbix-server
    systemd:
     name: zabbix-server
     state: started
  #- name: replace enabled=1
  #   lineinfile:
  #   path: /etc/yum.repos.d/zabbix.repo  
  #   regexp: '^enabled='
  #   line: 'enabled=1'
  #   section: '[zabbix-frontend]'
  - name: change zabbix.repo 
    shell:
      sed -ri '11s/enabled=0/enabled=1/'  /etc/yum.repos.d/zabbix.repo
  - name: install centos-release-scl-rh centos-release-scl zabbix-web-mysql-scl zabbix-nginx-conf-scl
    package:
      name: "{{ item }}"
      state: present
    with_items:
     - centos-release-scl
     - zabbix-web-mysql-scl
     - zabbix-nginx-conf-scl
  - name: detele nginx model
    vars: 
      zabbix: /etc/opt/rh/rh-nginx116/nginx/nginx.conf
    shell:
      sed -i '38,80d'  {{ zabbix }}
  - name: change date and set
    vars:
      datetime: "/etc/opt/rh/rh-php72/php-fpm.d/zabbix.conf"
    shell: |
      sed -ri 's/listen.acl_users = apache/listen.acl_users = apache,nginx/' {{ datetime }}
      sed -ri 's/; php_value\[date.timezone\] = Europe\/Riga/php_value[date.timezone] = Asia\/Shanghai/' {{ datetime }}
  - name: systemctl restart zabbix-server zabbix-agent rh-nginx116-nginx rh-php72-php-fpm
    systemd: 
     name: zabbix-server
     state: restarted
     enabled: yes
  - name: restart zabbix-agent
    systemd:
     name: zabbix-agent
     state: restarted
     enabled: yes 
  - name: restart rh-nginx116-nginx
    systemd:
     name: rh-nginx116-nginx
     state: restarted
     enabled: yes
  - name: restart rh-php72-php-fpm
    systemd:
     name: rh-php72-php-fpm
     state: restarted
     enabled: yes







6.zabbix 服务端配置文件修改(zabbix_agentd.conf / zabbix_server.conf)

#方式1:ansible单命令批量修改

修改zabbix服务端主机
# 修改DBHost为10.0.1.189
ansible backup -m lineinfile -a "path=/etc/zabbix/zabbix_server.conf regexp='^DBHost=.*' line='DBHost=10.0.1.189'" -b

# 修改SourceIP为10.0.1.189
ansible backup -m lineinfile -a "path=/etc/zabbix/zabbix_server.conf regexp='^SourceIP=.*' line='SourceIP=10.0.1.189'" -b

# 修改StatsAllowedIP为10.0.1.189
ansible backup -m lineinfile -a "path=/etc/zabbix/zabbix_server.conf regexp='^StatsAllowedIP=.*' line='StatsAllowedIP=10.0.1.189'" -b




# 修改SourceIP为10.0.1.189
ansible backup -m lineinfile -a "path=/etc/zabbix/zabbix_agentd.conf  regexp='^Source=.*' line='Server=10.0.1.189'" -b

# 修改ServerActive为10.0.1.189
ansible backup -m lineinfile -a "path=/etc/zabbix/zabbix_agentd.conf 
 regexp='^ServerActive=.*' line='ServerActive=10.0.1.189'" -b

ansible backup -m lineinfile -a "path=/etc/zabbix/zabbix_agentd.conf 
 regexp='^Hostname=.*' line='Hostname=Zabbix server'" -b


#重启
ansible backup -m shell -a "systemctl restart zabbix-agent.service;systemctl restart zabbix-server.service"





#方式2:你也可以用剧本修改,不过我这里还是觉得单命令快点,所以就不用剧本了

zabbix服务端剧本

---
- name: Update Zabbix Server Configuration
  hosts: backup
  become: yes

  tasks:
    - name: Change DBHost to 10.0.1.189
      ansible.builtin.lineinfile:
        path: /etc/zabbix/zabbix_server.conf
        regexp: '^DBHost=.*'
        line: 'DBHost=10.0.1.189'
        backup: yes

    - name: Set SourceIP to 10.0.1.189
      ansible.builtin.lineinfile:
        path: /etc/zabbix/zabbix_server.conf
        regexp: '^SourceIP=.*'
        line: 'SourceIP=10.0.1.189'
        backup: yes

    - name: Allow Stats from 10.0.1.189
      ansible.builtin.lineinfile:
        path: /etc/zabbix/zabbix_server.conf
        regexp: '^StatsAllowedIP=.*'
        line: 'StatsAllowedIP=10.0.1.189'
        backup: yes

    - name: Restart Zabbix Server
      ansible.builtin.systemd:
        name: zabbix-server.service
        state: restarted



#zabbix客户端剧本
---
- name: Update Zabbix Agent Configuration
  hosts: web
  become: yes

  tasks:
    - name: Set Server to 10.0.1.189
      ansible.builtin.lineinfile:
        path: /etc/zabbix/zabbix_agentd.conf
        regexp: '^Server=.*'
        line: 'Server=10.0.1.189'
        backup: yes

    - name: Set ServerActive to 10.0.1.189
      ansible.builtin.lineinfile:
        path: /etc/zabbix/zabbix_agentd.conf
        regexp: '^ServerActive=.*'
        line: 'ServerActive=10.0.1.189'
        backup: yes

    - name: Set Hostname to Zabbix server
      ansible.builtin.lineinfile:
        path: /etc/zabbix/zabbix_agentd.conf
        regexp: '^Hostname=.*'
        line: 'Hostname=Zabbix server'
        backup: yes

    - name: Restart Zabbix Agent
      ansible.builtin.systemd:
        name: zabbix-agent.service
        state: restarted



#方式三:手动修改(到对应的机器上,去修改配置信息)

PidFile=/var/run/zabbix/zabbix_agentd.pid
LogFile=/var/log/zabbix/zabbix_agentd.log
LogFileSize=0
Server=10.0.1.189    #要改
ServerActive=10.0.1.189  #要改
Hostname=Zabbix server  #要改
Include=/etc/zabbix/zabbix_agentd.d/*.conf

tips:按照这种类型修改





7.zabbix服务端--web页面安装配置


数据库类型  mysql
数据库主机 10.0.1.189
数据库端口 0
数据库名称 zabbix
用户     zabbix
密码 keer


8.zabbix服务端页面登录
username:Admin
password:zabbix





9.批量安装zabbix客户端

vim /etc/ansible/playbook/zabbix_agent.yml 


---
- name: Deploy Zabbix Agent2 to Web Hosts
  hosts: web
  become: yes

  tasks:

    # Step 1: Install Zabbix Repository
    - name: Install Zabbix Release RPM
      yum:
        name: https://repo.zabbix.com/zabbix/5.0/rhel/7/x86_64/zabbix-release-5.0-1.el7.noarch.rpm
        state: present

    # Step 2: Replace Repo Source with Alibaba Cloud Mirror
    - name: Modify Zabbix Repo to use Alibaba Cloud Mirror
      replace:
        path: /etc/yum.repos.d/zabbix.repo
        regexp: '^baseurl=http://repo.zabbix.com'
        replace: 'baseurl=https://mirrors.aliyun.com/zabbix'

    # Step 3: Install Zabbix Agent2
    - name: Install Zabbix Agent2
      yum:
        name: zabbix-agent2
        state: present

    # Step 4: Manage Zabbix Agent2 Service
    - name: Restart Zabbix Agent2
      systemd:
        name: zabbix-agent2
        state: restarted
    - name: Check Status of Zabbix Agent2
      systemd:
        name: zabbix-agent2
        state: started
    - name: Enable Zabbix Agent2 at Boot
      systemd:
        name: zabbix-agent2
        enabled: yes

    # Step 5: Configure Zabbix Agent2 (Backup and Modify Config)
    - name: Backup Original Configuration
      command: cp /etc/zabbix/zabbix_agent2.conf /etc/zabbix/zabbix_agent2.conf.orig
      args:
        creates: /etc/zabbix/zabbix_agent2.conf.orig

    - name: Create new configuration with specific settings
      lineinfile:
        path: /etc/zabbix/zabbix_agent2.conf
        line: "{{ item }}"
        state: present
        create: yes
      loop:
        - "PidFile=/var/run/zabbix/zabbix_agent2.pid"
        - "LogFile=/var/log/zabbix/zabbix_agent2.log"
        - "LogFileSize=0"
        - "Server=10.0.1.189"    #填自己的zabbix服务端ip
        - "ServerActive=10.0.1.189"  #填自己的zabbix服务端ip
        - "Hostname=Zabbix server"   #填自己的zabbix服务端名称
        - "Include=/etc/zabbix/zabbix_agent2.d/*.conf"
        - "ControlSocket=/tmp/agent.sock"
      notify: Restart Zabbix Agent2 Service

  handlers:
    - name: Restart Zabbix Agent2 Service
      systemd:
        name: zabbix-agent2
        state: restarted




10.zabbix配置自动注册(全部zabbix客户端ip--指向zabbix服务端)


###下面这个步骤,之前做过了,你可以不做,如果不知道的话,可以在做一遍
# 修改SourceIP为10.0.1.189
ansible web -m lineinfile -a "path=/etc/zabbix/zabbix_agentd.conf  regexp='^SourceIP=.*' line='Server=10.0.1.189'" -b

# 修改ServerActive为10.0.1.189
ansible web -m lineinfile -a "path=/etc/zabbix/zabbix_agentd.conf 
 regexp='^StatsAllowedIP=.*' line='ServerActive=10.0.1.189'" -b


#重启
ansible web -m shell -a "systemctl restart zabbix-agent.service"






#实现自动发现和自动注册
效果图:	https://blog.csdn.net/qq_42911262/article/details/138225375?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22138225375%22%2C%22source%22%3A%22qq_42911262%22%7D
1.

在这里插入图片描述

2.

在这里插入图片描述

3.

在这里插入图片描述

4.

在这里插入图片描述

5.
在这里插入图片描述
6.

在这里插入图片描述

7.

在这里插入图片描述

8.

在这里插入图片描述

9.

在这里插入图片描述

10.

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值