企业级自动化运维神器Ansible

一、介绍

1.自动化运维工具对比

1.Puppet:基于 Ruby 开发,采用 C/S 架构,扩展性强,远程命令执行相对较弱
2.SaltStack:基于 Python 开发,采用 C/S 架构,相对 puppet 更轻量级,配置语法使用 YAML,需要配置客户端以及服务器端。每台被控制节点需要安装agent
3.Ansible:基于 Python开发,分布式,无需客户端,轻量级,配置语法使用YAML 及 Jinja2模板语言,更强的远程命令执行操作

2.ansible简介

ansible是自动化运维工具,基于Python开发,分布式,无需客户端,轻量级,实现了批量系统配置、批量程序部署、批量运行命令等功能。ansible是基于模块工作的,本身没有批量部署的能力。真正具有批量部署的是ansible所运行的模块,ansible只是提供一种框架。

Ansible特性
    1) no agents:不需要在被管控主机上安装任何客户端,更新时,只需在操作机上进行一次更新即可(不用安装客户端。分布式的)
    2) no server:无服务器端,使用时直接运行命令即可
    3) modules in any languages:基于模块工作,可使用任意语言开发模块
    4) yaml,not code:使用yaml语言定制剧本playbook
    5) ssh by default:基于SSH工作

 connection plugins:连接插件,负责和被监控端的通信,默认使用SSH连接(免密或密码)(如何连接)
 host inventory:主机清单,是一个配置文件里面定义监控的主机(如何找到被控制节点)
 modules : 模块,核心模块、command模块、自定义模块等
 plugins : modules功能的补充,包括连接插件,邮件插件等
 playbook:编排,定义 Ansible 多任务配置文件,非必需

ansible默认一次控制5台

二、ansible安装

1、 准备环境

----关闭防护墙和selinux

环境:
主机:4台  一个控制节点 3个被控制节点
解析:本地互相解析(所有机器)
# vim /etc/hosts
192.168.1.10 ansible-web1
192.168.1.11   ansible-web2
192.168.1.12  ansible-web3
192.168.1.9   ansible-server  (控制节点服务器端)
配置ssh公钥认证:控制节点需要发送ssh公钥给所有非被控制节点
[root@ansible-server ~]# ssh-keygen
[root@ansible-server ~]# ssh-copy-id -i 192.168.1.10  #所有机器

2、安装

安装:控制节点
 1. 配置EPEL网络yum源
 [root@ansible-server ~]# yum install -y epel*
 2. 安装ansible
 [root@ansible-server ~]# yum install -y ansible
 3.查看版本
 [root@ansiable-server ~]# ansible --version
 4.看帮助
 [root@ansible-server ~]# ansible --help

3、ansible基础配置

(1)配置inventory主机清单

官方文档: http://docs.ansible.com/ansible/intro_inventory.html#>

inventory文件通常用于定义要管理主机的认证信息,例如ssh登录用户名、密码以及key相关信息。

查看配置文件:
[root@ansible-server ~]# rpm -qc ansible
/etc/ansible/ansible.cfg
/etc/ansible/hosts
-qc:---query查询配置文件configuration
1.主配置文件:
/etc/ansible/ansible.cfg  #主要设置一些ansible初始化的信息,比如日志存放路径、模块、插件等配置信息
2.主机清单文件:
默认位置/etc/ansible/hosts(建议使用ip,避免DNS解析)
 (2)主机配置
语法:
1.添加主机或者主机组:
[root@ansible-server ~]# vim /etc/ansible/hosts  #在最后追加被管理端的机器
ansible-web1                      #单独指定主机,可以使用主机名称或IP地址
2.添加主机组:
[webservers]        #使用[]标签指定主机组 ----标签自定义
192.168.10.11        #如果未解析添加ip
ansible-web2      #解析添加主机名
3.组可以包含其他组:
[webservers1]     #组一
ansible-web1
[webservers2]     #组二
ansible-web2
[weball:children]      #caildren-照写 #weball包括两个子组
webservers1        #组一
webservers2        #组二
4.为一个组指定变量,组内每个主机都可以使用该变量:
[weball:vars]         #设置变量,vars--照写
ansible_ssh_port=22     
ansible_ssh_user=root   
ansible_ssh_private_key_file=/root/.ssh/id_rsa  (默认不写,自定义目录的hosts文件时可以使用)
#ansible_ssh_pass=1      #也可以定义密码,如果没有互传秘钥可以使用密码。

Ansible Inventory 常见的内置参数

查看组内主机列表:
语法:ansible  组名  --list-hosts
[root@ansible-server ~]# ansible  weball --list-hosts
  hosts (2):
    ansible-web1
    ansible-web2
====================================
扩展:自定义主机列表使用密码登录:(了解)
[root@ansible-server ~]# vim /opt/hostlist
[all:vars]
ansible_ssh_port=22
ansible_ssh_user=root
#ansible_ssh_private_key_file=/root/.ssh/id_rsa
a1nsible_ssh_pass=1
​
[all]
ansible-web1
ansible-web2
使用:
[root@ansible-server ~]# ansible -i /opt/hostlist all -m ping -o
-i:指定清单文件
注意:这里的ping并不是真正意义上的ping而是探测远程主机ssh是否可以连接!判断ssh端口是否存活

4、语法

ansible  <pattern>   -m <module_name>   -a <arguments>

pattern--主机清单里定义的主机组名,主机名,IP,别名等,all表示所有的主机,支持通配符,正则
-m module_name: 指定要使用的模块,默认为command
-a arguments: 传递给模块的参数,即具体的shell命令
-o  横着显示(单行显示)
 ping命令
检查ansible节点的连通性:探测被控制节点的22端口是否存活
1.指定单台机器:
ansible ansible-web1 -m ping -o
2.同时指定多台机器:
ansible ansible-web1,ansible-web2 -m ping -o
3.指定组名:
ansible  webservers1 -m ping -o
 shell命令 

shell 模块支持使用管道、重定向、通配符等 shell 特性,适合执行复杂的命令和命令串。command 模块不会使用 shell 进程来解释命令,适合执行简单的命令,同时也更高效和安全。

当不使用-m shell时即为command模块

ansible webservers1 -m shell -a 'uptime'
不加 -m  默认是 command 模块
ansible webservers1 -a 'uptime'
给节点增加用户
ansible webservers1 -m shell -a 'useradd tom'   #添加用户
ansible webservers1  -a 'grep tom /etc/passwd'  #查看是否添加成功
重定向输出到本地文件中:
ansible webservers1 -a 'df -Th' > /opt/a.txt
面试: 在ansible中shell 和 command 模块. 这两个模块在很多情况下都能完成同样的工作,那么这两个模块之间的区别是什么? 
  • shell模块:支持shell特性,如管道和重定向,适合执行复杂的shell命令。
  • command模块:仅执行命令,不支持shell特性,性能更高且更安全。

5、Ad-Hoc

ad hoc其实就是执行简单的命令——一条命令。对于复杂的命令则为 playbook。
帮助文档:列出ansible支持的模块:
-l:获取列表
-s module_name:获取指定模块的使用信息
看所有模块(A10,华为,docker,EC2,aws等等广大厂商设备)
[root@ansible-server ~]# ansible-doc -l
查看模块使用信息,了解其功能:
[root@ansible-server ~]# ansible-doc -s yum

三、常用模块

常用模块帮助文档参考

https://docs.ansible.com/ansible/2.9/modules/modules_by_category.html
https://docs.ansible.com/ansible/2.9/modules/list_of_all_modules.html
https://docs.ansible.com/ansible/latest/modules/list_of_all_modules.html
https://docs.ansible.com/ansible/latest/modules/modules_by_category.html

1.copy远程复制备份

模块参数详解:  
src=:指定源文件路径(控制节点)
dest=:目标地址(拷贝到哪里)(被控制节点)
owner:指定属主
group:指定属组
mode:指定权限,可以以数字指定比如0644
backup:在覆盖之前将原文件备份,备份文件包含时间信息。有两个选项:yes|no
vim a.txt  #创建一个测试文件
123123
ansible weball -m copy -a 'src=/root/a.txt dest=/opt owner=root group=root mode=644' -o
vim a.txt  #追加如下内容
123123
234234
ansible weball -m copy -a 'src=/root/a.txt dest=/opt/ owner=root group=root mode=644 backup=yes' -o
登录被控制机器其中一台查看
[root@ansible-web1 ~]# cat /opt/a.txt.15301.2019-09-01\@00\:35\:18~

2.user用户管理 

​添加用户:
ansible ansible-web1 -m user -a "name=qianfeng"
"name=   "  #如:指定的用户名,要安装的软件
​删除用户:
ansible ansible-web1 -m user -a "name=qianfeng state=absent" -o
absent #删除用户,但是不会删除家目录
remove 参数在 state=absent 时使用,等价于 userdel --remove 布尔类型,默认值为 false。
ansible ansible-web1 -m user -a "name=qianfeng state=absent remove=yes" 
        #连同用户的家目录和邮件一起删除(/home/和/var/spool/mail/)
添加用户并设置密码
password: 参数用于指定用户密码,但是这个密码不能是明文密码,而是一个对明文密码加密后的字符串,相当于 /etc/shadow 文件中的密码字段,是一个对明文密码进行哈希后的字符串,可以使用命令生成明文密码对应的加密字符串。​
可以使用py命令生成哈希密码
pass=`python -c 'import crypt,getpass;pw="12345678";print(crypt.crypt(pw))'`
ansible ansible-web1 -m user -a "name=tom password=$pass"
登陆验证
生成ssh密钥
generate_ssh_key: 参数用于指定是否生成ssh密钥对,布尔类型,默认为false。当设置为yes时,为用户生成 ssh 密钥对,默认在 ~/.ssh 目录中生成名为 id_rsa私钥 和 id_rsa.pub公钥,如果同名密钥已经存在,则不做任何操作。
ansible ansible-web1 -m user -a "name=tom  generate_ssh_key=yes"

3.yum软件包管理 

安装apache
ansible webservers1 -m yum -a "name=httpd state=latest" -o
state=     #状态是什么,干什么
state=directory    用于目录的编辑
state=absent        用于删除文件
state=latest       表示最新的
state=removed      表示卸载
卸载软件:
ansible webservers1 -m yum -a "name=httpd state=removed" -o

4.service服务管理模块

name:服务的名称。
state:服务的状态,可选值包括started、stopped、restarted、reloaded、enabled和disabled。
enabled:指定服务是否在系统启动时自动启动,可选值为yes或no。
pattern:用于指定匹配服务进程的正则表达式,用于重新启动或重新加载服务时使用。
sleep:指定在执行重启或重新加载操作之前的等待时间。
ansible webservers1 -m service -a "name=httpd state=started" #启动
ansible webservers1 -m service -a "name=httpd state=stopped" #停止
ansible webservers1 -m service -a "name=httpd state=restarted" #重启
ansible webservers1 -m service -a "name=httpd state=started enabled=yes" #开机启动
ansible webservers1 -m service -a "name=httpd state=started enabled=no"  #开机关闭

5.file文件模块

模块参数详解:  
owner:修改属主
group:修改属组
mode:修改权限
path=:要修改文件的路径
recurse:递归的设置文件的属性,只对目录有效,默认no
        yes:表示使用递归设置
state:
absent:确保文件不存在,即删除文件。
directory:确保目录存在(不存在则创建。存在则不修改)
file:确保文件存在,如果不存在则创建空文件。
hard:确保硬链接存在。
link:确保符号链接存在。
touch:确保文件存在,如果不存在则创建空文件,并更新文件的修改时间。
present:确保文件或目录存在。
#创建一个文件
ansible webservers1 -m file -a 'path=/tmp/88.txt mode=777 state=touch'
#创建一个目录
ansible webservers1 -m file -a 'path=/tmp/99 mode=777 state=directory' 
#创建文件
- name: Ensure testfile exists
  file:
    path: /tmp/testfile
    state: touch
#创建目录
- name: Ensure testdir exists
  file:
    path: /tmp/testdir
    state: directory
    owner: myuser
    group: mygroup
    mode: '0755'
#删除文件或目录
- name: Remove testfile if it exists
  file:
    path: /tmp/testfile
    state: absent
- name: Remove testdir if it exists
  file:
    path: /tmp/testdir
    state: absent
更改文件权限和所有者
- name: Change file ownership and permissions
  file:
    path: /tmp/testfile
    owner: newowner
    group: newgroup
    mode: '0644'
创建符号链接
- name: Create a symbolic link
  file:
    src: /tmp/original
    dest: /tmp/link
    state: link
递归更改目录权限
- name: Recursively change directory permissions
  file:
    path: /tmp/testdir
    state: directory
    mode: '0755'
    recurse: yes

6.脚本 script 模块 

指定本地的脚本文件,到远程主机运行一次
注意:和 shell 模块的不同,shell 模块是要求客户端上有这个脚本才能执行;
script 是要求 ansible 服务端有这个脚本就可以了,执行的时候是不会拷贝这个脚本到客户端的。
[root@ansible-server ~]# cat test.sh 
#!/usr/bin/bash
touch test{1..50}
[root@ansible-server ~]# chmod o+x test.sh
参数:
chdir:在远端执行脚本前先切换一个目录
[root@ansible-server ~]# ansible webservers1 -m script -a "chdir=/mnt /root/test.sh"
编写测试脚本:
[root@ansible-server ~]# cat awk.sh 
#!/bin/bash
cat /etc/passwd | awk -F: '{print $1,$2}'
[root@ansible-server ~]# chmod o+x awk.sh
参数:
creates:如果其后跟的文件存在,则不执行脚本;
removes:如果其后跟的文件存在,则执行脚本;
[root@ansible-server ~]# ansible webservers1 -m script -a "/root/awk.sh removes=/etc/passwd"
​

7.setup 收集信息模块

参数

ansible_all_ipv4_addresses	所有目标主机的 IPv4 地址列表。
ansible_all_ipv6_addresses	所有目标主机的 IPv6 地址列表。
ansible_date_time	系统时间。
ansible_kernel	内核版本。
ansible_default_ipv4	默认网关的 IPv4 地址。
ansible_default_ipv6	默认网关的 IPv6 地址。
ansible_distribution	Linux 系统发行版本,例如 CentOS、Ubuntu、等。
ansible_nodename	主机名。
ansible_pkg_mgr	包管理器,例如 yum、apt、dpkg 等。
ansible_python_version	Python 版本。
ansible_processor_cores	CPU核数。
ansible_processor_count	逻辑 CPU 核心数,包括超线程。
ansible_cpu_info	CPU 信息字典,包含 CPU 频率、架构等信息。
ansible_mem_total	总内存容量。
ansible_mem_free	可用内存容量。
ansible_mem_used	已使用内存容量。

示例

ansible webservers1 -m setup  #收集所有信息
ansible webservers1 -m setup -a 'filter=ansible_all_ipv4_addresses' 
#只查询ipv4的地址 filter:过滤

1. 收集所有Facts信息
- name: 收集所有Facts信息
  hosts: all
  tasks:
    - name: 收集所有Facts信息
      setup:
2. 收集特定Facts信息
- name: 收集特定Facts信息
  hosts: all
  tasks:
    - name: 收集硬件信息
      setup:
        gather_subset: hardware
    - name: 收集网络信息
      setup:
        gather_subset: network
    - name: 收集Fact信息
      setup:
        gather_subset: fact
    - name: 收集配置信息
      setup:
        gather_subset: config
    - name: 不收集任何Facts信息
      setup:
        gather_subset: none
3. Facts信息收集的参数
- name: 设置Facts信息收集的参数
  hosts: all
  tasks:
    - name: 设置Facts信息收集的超时时间为 120 秒
      setup:
        gather_timeout: 120
    - name: 将Facts信息存储在 /tmp/facts.d 目录中
      setup:
        fact_path: /tmp/facts.d
    - name: 覆盖 host_uuid Facts信息
      setup:
        gather_overrides:
          ansible_facts:
            host_uuid: "my-uuid"
    - name: 收集子目录中的Facts信息
      setup:
        gather_subdirs: yes
    - name: 指定Facts信息收集的配置文件
      setup:
        gather_profile: default
    - name: 收集CLI Facts信息
      setup:
        gather_cli_facts: yes

8. archive模块 

功能:打包与压缩

常用参数
path       打包目录名称
dest       声称打包目标目录文件名称
format     打包格式
owner      指定文件所属人
mode       指定文件权限
ansible 10.10.10.134 -m archive -a 'path=/var/log  dest=/tmp/log.tar.gz  format=gz'
##其他格式
ansible 10.10.10.134 -m archive -a 'path=/var/log  dest=/tmp/log.zip  format=zip'
ansible 10.10.10.134 -m archive -a 'path=/var/log  dest=/tmp/log.tar  format=tar'
ansible 10.10.10.134 -m archive -a 'path=/var/log  dest=/tmp/log.tar.bz2  format=bz2'
ansible webservers1 -m archive -a "path=/etc dest=/mnt/`date +%F`-etc.tar.gz format=gz"
# 以时间命名打包后的文件

9. unarchive解压模块

可以解压tar.gz包也可以解压zip包(注意:如果是zip包需要在控制机器安装unzip)
参数解释:
copy:
默认yes,当copy=yes时ansible主机复制到远程主机上的,设置为copy=no时在远程主机上寻找src源文件
src:
源路径,可以是ansible主机上的路径或远程主机上的路径,如果是远程主机上的路径,则需设置copy=no
dest:远程主机上的目标路径
解压缩文件到指定目录
ansible all -m unarchive -a "src=/root/arc.tar.gz dest=/root/" --become
解压复制到目标目录,单行格式输出
ansible webservers -m unarchive -a 'src=/root/jdktar.gz dest=/opt/ copy=yes' -o
强制覆盖现有文件
ansible all -m unarchive -a "src=/root/a.tar.gz dest=/root/ extra_opts=--overwrite" 
1. 从控制机复制并解压文件到远程主机
- name: Extract file to remote machine
  unarchive:
    src: /path/to/archive.tar.gz
    dest: /path/to/destination
2. 直接在目标主机上解压文件
- name: Extract file that is already on remote machine
      unarchive:
        src: /path/to/file.tar.gz
        dest: /path/to/destination/
        remote_src: yes
3. 解压缩 ZIP 文件
- name: Extract zip file to remote machine
      unarchive:
        src: /path/to/file.zip
        dest: /path/to/destination/
         mode: '0755'
4. 下载并解压远程 URL 文件
- name: Download and extract file from URL
      unarchive:
        src: http://example.com/file.tar.gz
        dest: /path/to/destination/
5. 使用 creates 参数防止重复解压 
- name: Unarchive only if specific file does not exist
      unarchive:
        src: /path/to/file.tar.gz
        dest: /path/to/destination/
        creates: /path/to/destination/extracted_file

10.cron模块作用:计划任务

常用参数
minute     分钟
hour       小时
day        天
month      月
weekday    周
name       任务名称
job        任务脚本或命令
disabled   yes 禁用计划任务/no 启动计划任务
state=absent 删除计划任务
ansible webservers -m cron -a 'job="rm -rf /mnt/*" name="deletefile" minute="53" hour="20" day="7" month="5"'
删除计划任务:
ansible webservers -m cron -a "name='deletefile' state=absent"
创建每日凌晨 2 点运行备份脚本的任务
- name: Add daily backup cron job
      cron:
        name: "daily backup"
        minute: "0"
        hour: "2"
        job: "/usr/local/bin/backup.sh"
删除定时任务
- name: Remove daily backup cron job
      cron:
        name: "daily backup"
        state: absent
创建每周一早上 3 点清理临时文件的任务
cron:
        name: "weekly temp files cleanup"
        minute: "0"
        hour: "3"
        weekday: "1"  # 0 is Sunday, 1 is Monday, etc.
        job: "/usr/bin/find /tmp -type f -atime +7 -delete"
每小时运行日志轮转
- name: Add hourly log rotation cron job
      cron:
        name: "hourly log rotation"
        minute: "0"
        job: "/usr/sbin/logrotate"

​11.get_url模块

从http、https或ftp服务器中下载文件

参数:
url:指定要下载的文件路径
dest:指定下载的文件存放路径
backup:如果为 yes,在目标文件存在且内容发生更改时,将创建备份。类型:布尔值,默认值:no
force:如果为 yes,则总是下载文件,即使文件已存在。类型:布尔值,默认值:no
url_password:用于 URL 访问的密码(用于处理 URL 中包含的密码)。类型:字符串
url_username:用于 URL 访问的用户名(用于处理 URL 中包含的用户名)。类型:字符串

ansible webservers -m get_url -a "url=https://download.redis.io/releases/redis-7.0.10.tar.gz dest=/mnt backup=no force=yes"
ansible webservers -m get_url -a "url=https://repo.zabbix.com/zabbix/5.0/rhel/7/x86_64/zabbix-release-5.0-1.el7.noarch.rpm dest=/root force=yes"

12.yum_repository

可以帮助我们在远程主机上创建yum仓库

name:相当于.repo文件定义中括号的[仓库ID]
baseurl:设置yum仓库源的路径
description:相当于.repo文件中的yum源的名字(name字段)
file:相当于.repo文件的名称,不使用时默认以name加.repo命令
enabled=yes|no:是否启用yum源
gpgcheck=yes|no:是否开启验证软件包
gpgcakey:前提是gpgcheck=yes,相当于.repo文件中gpgkey,验证gpg公钥
state=present|absent:默认present,absent表示删除
创建yum仓库
ansible webserver -m yum_repository -a "name='Centos Base' file=base description=test baseurl=file:///mnt/centos enabled=yes gpgcheck=no"
配置阿里epel源
ansible webserver  -m yum_repository -a "name=aliepel baseurl=https://mirrors.aliyun.com/epel/7/x86_64/ enabled=yes gpgcheck=yes gpgcakey=https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-7 state=present file=AlicloudEpel description=alepel"
删除yum源
ansible webserver -m yum_repository -a "file=base name='Centos Base' state=absent"

13.lineinfile

lineinfile 模块用于修改或插入文件中的行。它可以用来更新配置文件中的特定行,或者向文件末尾添加一行,如果该行不存在的话。

主要参数
path: 文件路径。
line: 要插入或替换的具体行内容。
state: 行的状态,可以是 present 或 absent。
regexp: 用于匹配要替换行的正则表达式。
insertafter: 如果指定,会在匹配到的行之后插入 line;如果未指定,则直接替换匹配的行。
create: 如果文件不存在,是否创建文件,默认为 no。
backup: 是否在修改前创建文件的备份,默认为 no。

14.debug

在Ansible中用于调试任务,它可以显示变量的值或任务执行的详细信息,⼀般配合register⼀起使⽤.

  • 在执行playbook或运行ad-hoc命令时验证变量是否按预期设置。
  • 输出变量的值以进行调试。
  • 显示有关正在运行的任务的信息。
参数:
msg:相当于是echo命令,如果是变量需要加上{{}}配置着register一起用
register: 用于获取任务执行结果以及任务执行过程中产生的输出和值。
还可以将任务的执行结果存储到一个变量中,在playbook后续的任务中使用这个变量。
var:指定要打印的变量名可以直接写变量名不用加{{}},与msg参数互斥,二者只能有一个。
ansible webservers -m debug -a "msg=hello,beijing"  # 打印字符串
ansible webservers -m debug -a "var=a" -e "a=1234567"  #打印变量
vim debug.yml
- hosts: webs
  user: root  
  tasks:
   - name:create file
     file: path=/mnt/debug.txt state=touch
     register: create_file
   - name: print create file
     debug:
      msg={{ create_file }}
  

四、ansible-playbook 剧本

playbook是ansible用于配置,部署,和管理被控节点的剧本。通过playbook的详细描述,执行其中的tasks,可以让远端主机达到预期的状态。playbook是由一个或多个”play”组成的列表。 当对一台机器做环境初始化的时候往往需要不止做一件事情,这时使用playbook会更加适合。通过playbook你可以一次在多台机器执行多个指令。通过这种预先设计的配置保持了机器的配置统一,并很简单的执行日常任务。

工作原理:

ansible通过不同的模块实现相应的管理,管理的方式通过定义的清单文件(hosts)所管理的主机包括认证的方式连接的端口等。所有的功能都是通过调用不同的模块(modules)来完成不同的功能的。不管是执行单条命令还是play-book都是基于清单文件。执行的方式可以是对本地执行也可以通过ssh的方式对远程主机进行操作,常见的是通过ssh的方式,对远程主机进行操作。

playbook格式:playbook由YMAL语言编写。YMAL格式是类似于JSON的文件格式,便于人理解和阅读,同时便于书写。

一个剧本里面可以有多个play,每个play只能有一个tasks,每个tasks可以有多个name

核心元素:

  1. Playbooks: Playbooks是用来编排和执行一系列任务的YAML文件。它包括了一系列的plays,每个play都包含了一组任务。
  2. Variables: 变量是一种用于存储数据的容器,可以在playbooks中定义和使用。变量可以传递给tasks和templates来使用,可以用来存储主机信息、配置参数等。
  3. Tasks: 任务是由模块定义的操作的列表,通过调用模块来完成特定的任务。每个任务都有一个名称和一组参数,可以在playbook中指定要在哪些主机上执行这些任务。
  4. Templates: 模板是使用模板语法编写的文本文件,可以根据变量的值生成最终的文件。模板可以用来生成配置文件、脚本等动态内容。
  5. Handlers: 处理器是一种特殊的任务,通常在特定的事件满足时触发执行。比如在配置文件发生变化后重启服务。
  6. Roles: 角色是一种可重用的组织结构,可以将相关的tasks、templates和变量打包在一起,用来实现特定的功能。角色可以在多个playbook中重复使用,提高了代码的可复用性。

 playbook的基础组件:

  • name: 定义playbook或者task的名称(描述信息),每一个play都可以完成一个任务。
  • hosts: playbook中的每一个play的目的都是为了让某个或某些以某个指定用户的身份执行任务。hosts用于指定要执行指定任务的主机。
  • user: remote_user则用于指定远程主机上的执行任务的用户,也可以使用user(基本上是root)。
  • tasks: 任务列表play的主体部分是task list. task list中的各任务按次序逐个在hosts中指定的所有主机上执行,即在所有主机上完成第一个任务后再开始第二个。
  • vars: 定义变量(如果不使用内部变量需要提前定义)。
  • vars_files: 调用定义变量文件。
  • notify: 任务执行结果如果是发生更改了的则触发定义在handler的任务执行。
  • handlers: 用于当前关注的资源发生变化时采取一定指定的操作。

Playbook配置文件详解

---
#yaml文件以---开头,以表明这是一个yaml文件,可省略(但是如果两个YAML配置叠加的话,要以此为分割)
- name: first play
#定义一个play的名称,可省略
  gather_facts: false
#设置不进行facts信息收集,这可以加快执行速度,可省略
  hosts: webservers
#指定要执行任务的被管理主机组,如多个主机组用冒号分隔
  remote_user: root
#指定被管理主机上执行任务的用户
  tasks:
#定义任务列表,任务列表中的各任务按次序逐个在hosts中指定的主机上执行
   - name: test connection
#自定义任务名称
     ping:
#使用 module: [options] 格式来定义一个任务
   - name: disable selinux
     command: '/sbin/setenforce 0'
#command模块和shell模块无需使用key=value格式
     ignore_errors: True
#如执行命令的返回值不为0,就会报错,tasks停止,可使用ignore_errors忽略失败的任务
   - name: disable firewalld
     service: name=firewalld state=stopped
#使用 module: options 格式来定义任务,option使用key=value格式
   - name: install httpd
     yum: name=httpd state=latest
   - name: install configuration file for httpd
     copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf
#这里需要一个事先准备好的/opt/httpd.conf文件
     notify: "restart httpd"
#如以上操作后为changed的状态时,会通过notify指定的名称触发对应名称的handlers操作
   - name: start httpd service
     service: enabled=true name=httpd state=started
  handlers:
#handlers中定义的就是任务,此处handlers中的任务使用的是service模块
   - name: restart httpd
#notify和handlers中任务的名称必须一致
     service: name=httpd state=restarted
#Ansible在执行完某个任务之后并不会立即去执行对应的handler,而是在当前play中所有普通任务都执行完后再去执行handler,这样的好处是可以多次触发notify,但最后只执行一次对应的handler,从而避免多次重启。

基础命令

ansible-playbook test.yml                  #运行playbook
ansible-playbook test1.yml --syntax-check	#检查yaml文件的语法是否正确
ansible-playbook test1.yml --list-task	    #检查tasks任务
ansible-playbook test1.yml --list-hosts	#检查生效的主机
ansible-playbook test1.yml --start-at-task='install httpd'	
#指定从某个task开始运行

控制台输出的颜色编码具有特定的意义,用于帮助用户快速理解执行的状态。

  • 绿色:代表成功。当一个任务在目标主机上成功运行且没有遇到任何错误时,控制台输出将会显示为绿色。例如,当一个配置文件被正确更新或一个服务被启动而没有任何问题时,你会看到绿色输出。
  • 黄色:代表改变。如果一个任务导致了目标主机上的状态变化(例如安装了一个新的软件包或更新了一个配置文件),控制台输出将会显示为黄色。这意味着虽然任务执行成功,但对系统产生了实际的影响。
  • 红色:代表失败或错误。如果一个任务未能完成,或者执行过程中出现了错误,控制台输出将会显示为红色。这通常意味着你需要调查具体的原因,并可能需要采取一些补救措施。

tasks任务

一个典型的tasks部分包含多个任务,每个任务包含一个或多个模块。模块是Ansible的基本执行单元,用于执行特定的操作,如文件管理、软件安装、服务管理等。

vim /etc/ansible/test.yml  #创建文件必须以.yml结尾
---
 - hosts: webservers1
   user: root
   tasks:
   - name: create file
     file: state=touch mode=777 path=/tpm/playbook.txt
   - name:create dir
     file: path=/mnt/dir12 state=directory
===========================================
参数解释:
    Ansible playbook 文件通常使用 .yml 或 .yaml 扩展名。
    ---: YAML 文档的开始标记。在 Ansible 中,每个 playbook 都是从这里开始的。
    hosts: 参数指定了对哪些主机进行操作;
    user: 参数指定了使用什么用户登录远程主机操作;
    tasks: 指定任务.下面列出的任务将在指定的主机上执行。
    name:  对任务的描述,在执行过程中会打印出来。
    file:  使用 Ansible 的 file 模块来管理文件。
    state: touch: 表明要创建或更新文件,如果文件已存在则不会修改其内容,但会更新文件的时间戳。
    path: 指定要创建的文件的路径为 

检测语法:
[root@ansible-server ansible]# ansible-playbook --syntax-check test.yml 
playbook: test.yml
运行Playbook:
[root@ansible-server ansible]# ansible-playbook test.yml #加剧本名称

handlers/notify处理器、触发器

handlers(处理器)是一种特殊类型的任务,它们通常用于在特定条件下触发操作。Handlers通常与notify(通知)关键字一起使用,用于在任务执行过程中发出通知,并在所有相关任务完成后执行。

在一个playbook中,可以定义一个或多个handlers。每个handler都有一个唯一的名称和一个或多个操作。当某个任务的notify关键字指定某个handler时,在该任务执行完后,即当Ansible在监控到该任务 changed=1时,相关的handlers将被触发并执行操作。

handlers:由特定条件触发的Tasks
handlers:处理器
notify:触发器
语法:
tasks:
- name: TASK_NAME
  module: arguments         #1.上面任务执行成功,然后
  notify: HANDLER_NAME      #2.通知他
handlers:
- name: HANDLER_NAME        #3.一一对应,这里的描述与notify定义的必须一样
  module: arguments         #4.执行这个命令
vim handlers.yml
- hosts: webservers1
  user: root
  tasks:
  - name: test copy
    copy: src=/root/a.txt dest=/mnt
    notify: test handlers
  handlers:
  - name: test handlers
    shell: echo "abcd" >> /mnt/a.txt
​
检测语法:
/etc/ansible/ansible-playbook --syntax-check handlers.yml 
运行
/etc/ansible/ansible-playbook handlers.yml
说明:只有 copy 模块真正执行后,才会去调用下面的 handlers 相关的操作,追加内容。所以这种比较适合配置文件发生更改后,需要重启服务的操作。

迭代

循环:迭代,需要重复执行的任务;
对迭代项的引用,固定变量名为”item”,使用with_item属性给定要迭代的元素; 
 元素:1.列表 ,2.字符串 3.字典
item关键字定义迭代元素 
基于字符串列表元素
vim list.yml
- hosts: websrvs
  remote_user: root
  tasks:
  - name: install packages
    yum: name={{ item }} state=latest         #相当于for循环里面的i 
    with_items:                               #取值 。但是不支持通配符
     - httpd
     - httpd-tools
     - php
     - php-mysql
     - php-mbstring
     - php-gd 
检测语法:
/etc/ansible/ansible-playbook --syntax-check list.yml 
执行:
/etc/ansible/ansible-playbook  list.yml

使用loop关键字定义迭代参数
批量创建用户
[root@ansible-server ansible]# vim list2.yml
- hosts: test
  tasks:
    - name: Create Groups
      group:
        name: "{{ item }}"
      loop:
          - group1
          - group2
          - group3
    - name: Create Users
      user:
        name: "{{ item.user }}"
        group: "{{ item.group }}"
        uid: "{{ item.uid }}"
      loop:
        - { user: jack,group: group1, uid: 2001 }
        - { user: tom,group: group2, uid: 2002 }
        - { user: alice,group: group3, uid: 2003 }
        
[root@ansible-server ansible]# ansible-playbook list2.yml

批量安装
vim install.yml
- hosts: 192.168.157.129
  users: root
  task: 
   - name: install epel
     yum: name=epel-release state=latest

   - name: install packages
     yum: name={{ item }} state=latest
     loop: 
      - httpd
      - mysql
      - nginx
      - redis
批量卸载
vim remove.yml
- hosts: 192.168.157.129
  users: root
  task: 
   - name: remove packages
     yum: name={{ item }} state=removed
     loop: 
      - httpd
      - mysql
      - nginx
      - redis

自定义vars_files变量

使用 vars_files 加载变量;变量调用语法: {{ var_name }}

作用
  • 提高可读性:变量让 playbook 更易于理解和维护。
  • 减少错误:避免因复制粘贴路径而导致的潜在错误。
  • 易于维护:一处更新,全局生效。
  • 重用性:可以在多个任务或 playbook 中复用变量。
  • 灵活性:可以根据需要轻松调整配置选项。
创建变量目录:
[root@ansible-server ~]# mkdir /etc/ansible/vars
[root@ansible-server ~]# cd /etc/ansible/vars/
[root@ansible-server vars]# vim file.yml     #创建变量文件。
src_path: /root/test/a.txt
dest_path: /opt/test/

创建一个测试文件
[root@ansible-server vars]# mkdir /root/test
[root@ansible-server vars]# vim /root/test/a.txt  #编辑测试文件
123
创建play-book引用变量文件:
[root@ansible-server vars]# cd /etc/ansible/
[root@ansible-server ansible]# vim vars.yml
- hosts: ansible-web1
  user: root
  vars_files:
   - /etc/ansible/vars/file.yml
  tasks:
   - name: create directory
     file: path={{ dest_path }} mode=755 state=directory
   - name: copy file
     copy: src={{ src_path }} dest={{ dest_path }}

检测语法:
[root@ansible-server vars]# cd ..
[root@ansible-server ansible]# ansible-playbook --syntax-check vars.yml
playbook: vars.yml
执行:
[root@ansible-server ansible]# ansible-playbook  vars.yml

登录查看:

group模块

Ansible 提供了 group 模块来管理 Linux 系统上的用户组。这个模块可以用来添加、修改或删除用户组。group模块参数详解
name: 必须参数,用于指定组名称。
state: 可选参数,默认值为 present,也可以设置为 absent 以删除组。
gid: 可选参数,用于指定组的 GID(Group ID)。如果不指定,则会分配一个随机的 GID。
system: 可选参数,如果设置为 yes,则该组被视为系统组。
vim play.yml
- hosts: webserver1    #play1
  user: root
  tasks:
  - name: create a group
    group: name=mygrp system=yes
  - name: create a user
    user: name=tom group=mygrp system=yes
​
- hosts: webserver2    #play2
  user: root
  tasks:
  - name: install apache
    yum: name=httpd state=latest
  - name: start httpd service
    service: name=httpd state=started

执行
[root@ansible ansible]# ansible-playbook play.yml
2.使用变量并不显示搜集主机相关信息
gather_facts参数:指定了在任务部分执行前,是否先执行setup模块获取主机相关信息,默认值为true,改成false之后在执行过程中不会搜集主机相关信息。
[root@ansible ansible]# vim create_user.yml
- hosts: ansible-web1
  user: root
  gather_facts: false  #是否执行setup模块,搜集对方机器的信息
  vars:                #自定义变量
  - user: "jack"       #user是自定义变量名称,“jack”是变量值
  - src_path: "/root/a.txt"    #同上
  - dest_path: "/mnt/"
  tasks:
  - name: create user
    user: name={{ user }}
  - name: copy file
    copy: src={{ src_path }} dest={{ dest_path }}
[root@ansible ansible]# vim /root/a.txt  #创建测试文件
123

执行:
[root@ansible ansible]# ansible-playbook create_user.yml

debug调试 

debug进行调试
vim debug.yml 
- hosts: webserver
  user: root
  tasks:
   - name: create file
     file: path=/mnt/debug.txt state=touch
     register: create_file  #可以将上面执行的结果通过register保存为一个变量里面。
   - name: 输出创建过程
     debug: msg={{ create_file }}  #打印保存的变量的值
     
ansible-playbook debug.yml  #运行剧本

vim debug_var.yml  打印变量剧本
- hosts: webserver
  user: root
  vars:
   user1: jack
  tasks:
   - name: 打印变量
     debug: var=user1
     
ansible-playbook debug_var.yml

条件判断w hen

4.条件判断when:根据特定的条件来决定是否执行某个task。当条件为真时,任务将会执行;
当条件为假时,任务将被跳过。
when关键字的使用非常简单,只需在单个任务的后面添加when条件判断语句即可。在when语句中,
变量不需要使用{{ }}。

比较运算符                       含义
  >                            大于
  >=                           大于等于
  <	                           小于
  <=	                       小于等于
  ==                           等于
  !=                           不等于

判断远程主机的主机名是否为localhost,如果是创建文件
通过setup模块获取远程主机的信息
[root@ansible-server ~]# vim test_when.yml
- hosts: webserver
  user: root
  tasks:
   - name: create file
     file: path=/mnt/test1.txt state=touch  #在执行上面的任务
     register: create_file
     when: ansible_hostname == "localhost"  #先条件成立

   - name: add 123 to file
     shell: echo 123123 >> /mnt/test1.txt

   - name: 打印过程
     debug: msg={{ create_file }}
[root@ansible-server ~]# ansible-playbook test_when.yml

判断操作系统为centos安装nginx
ignore_errors: true  #设置为true,如果命令1报错,也不影响其他命令执行
[root@ansible-server ~]# vim when_install.yml
- hosts: webserver
  user: root
  tasks:
   - name: install package
     ignore_errors: true
     yum: name={{ 1 }} state=latest   #记得替换变量item
     loop:
      - nginx
      - redis
     when: ansible_distribution == "CentOS"

   - name: install epel
     yum: name=epel-release state=latest

   - name: create file
     file: path=/root/ansible.txt state=touch
     
[root@ansible-server ~]# ansible-playbook when_install.yml

判断文件是否为空,如果是空那就添加内容
[root@ansible-server ~]# vim test_file.yml
- hosts: webserver
  user: root
  tasks:
   - name: create file
     file: path=/opt/file.txt state=touch

   - name: Check if file is empty
     shell: cat /opt/file.txt
     register: check_file

   - name: print vars
     debug: msg={{ check_file }}

   - name: insert hello
     shell: echo "hello" >> /opt/file.txt
     when: check_file.stdout == ""  #字符串引号引起来
     
[root@ansible-server ~]# ansible-playbook test_file.yml
注意:
TASK [print vars] **************************************************************
ok: [192.168.229.158] => {
    "msg": {
        "changed": true, 
        "cmd": "cat /opt/file.txt", 
        "delta": "0:00:00.004283", 
        "end": "2023-07-30 01:28:32.812782", 
        "failed": false, 
        "rc": 0,   #对于server可以作为判断依据,运行返回值为0,不运行返回值为非0
        "start": "2023-07-30 01:28:32.808499", 
        "stderr": "", 
        "stderr_lines": [], 
        "stdout": "hello",   #可以作为文件内容输出的判断依据
        "stdout_lines": [
            "hello"
        ]
    }
}

判断mysql服务是否启动,没有启动那就启动
[root@ansible-server ~]# vim test_server.yml
- hosts: webserver
  user: root
  tasks:
   - name: check mysql status
     ignore_errors: true
     shell: systemctl status mysqld
     register: check_mysql

   - name: print mysql server
     debug:
      var: check_mysql

   - name: start mysqld
     service: name=mysqld state=started
     when: check_mysql.rc != 0
     
[root@ansible-server ~]# ansible-playbook test_server.yml

五、Role角色

roles则是在ansible中,playbooks的目录组织结构。而模块化之后,成为roles的组织结构,易读,代码可重用,层次清晰。

实战目标:通过role远程部署nginx并配置

两台机器配置本地解析
[root@ansible-server ~]# vim /etc/hosts
192.168.1.9    ansible-server
192.168.1.13   ansible-web4
[root@ansible-web4 ~]# vim /etc/hosts
192.168.1.9    ansible-server
192.168.1.13   ansible-web4
添加主机组
[root@ansible-server ansible]# pwd
/etc/ansible
[root@ansible-server ansible]# vim hosts
[webservers4]
ansible-web4
配置免密登录:
[root@ansible-server ~]# ssh-copy-id -i 192.168.1.13

1.目录结构:

目录顺序:
role_name/     ---角色名称=目录
    files/:存储一些可以用copy调用的静态文件。
    tasks/: 存储任务的目录,此目录中至少应该有一个名为main.yml的文件,用于定义各task;其它的文件需要由main.yml进行“包含”调用es; 
    handlers/:此目录中至少应该有一个名为main.yml的文件,用于定义各handler;其它的文件需要由(与notify:名字相同,方便notify通知执行下一条命令)通过main.yml进行“包含”调用; 
    vars/:此目录中至少应该有一个名为main.yml的文件,用于定义各variable;其它的文件需要由main.yml进行“包含”调用; 
    templates/:存储由template模块调用的模板文本; (也可以调用变量)
    site.yml:定义哪个主机应用哪个角色
1.准备目录结构
~]# cd /etc/ansible/roles/  #role为自带目录,如果不存在可以创建
roles]# mkdir nginx/{files,handlers,tasks,templates,vars} -p
2.创建文件:
roles]# touch site.yml nginx/{handlers,tasks,vars}/main.yml
[root@localhost roles]# yum install -y tree
roles]# ls
nginx  site.yml
roles]# tree .
.
├── nginx
│   ├── files
│   ├── handlers
│   │   └── main.yml
│   ├── tasks
│   │   └── main.yml
│   ├── templates
│   └── vars
│       └── main.yml
└── site.yml

6 directories, 4 files
1.创建nginx的测试文件
roles]# echo 1234 > nginx/files/index.html
2.安装nginx并配置模板
yum install -y nginx && cp /etc/nginx/nginx.conf nginx/templates/nginx.conf.j2

templates模板: 用的是jinja2的语法

3.编写任务
[root@ansible-server roles]# vim nginx/tasks/main.yml
---
- name: install packege
  yum: name={{ item }} state=latest 
  loop:
   - epel-release
   - nginx
   - net-tools
- name: copy nginx.conf template
  template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
- name: copy index.html
  copy: src=index.html dest=/usr/share/nginx/html/index.html
  notify: start nginx

4.准备配置文件
[root@ansible-server roles]# vim nginx/templates/nginx.conf.j2
修改成如下内容。自定义变量

5.编写变量
[root@ansible-server roles]# vim nginx/vars/main.yml  #添加如下内容
worker_connections: 2
6.编写handlers
[root@ansible-server roles]# vim nginx/handlers/main.yml #编写如下内容
---
- name: start nginx  #和notify的名字必须一样
  service: name=nginx state=started
7.编写剧本
[root@ansible-server roles]# vim site.yml
---
- hosts: webservers4
  user: root
  roles:
   - nginx

检测语法
[root@ansible-server roles]# ansible-playbook site.yml --syntax-check
playbook: site.yml
执行剧本:
[root@ansible-server roles]# ansible-playbook site.yml

查看:

[root@ansible-web4 ~]# netstat -lntp 
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      3102/nginx: master  
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      926/sshd            
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1007/master         
tcp6       0      0 :::80                   :::*                    LISTEN      3102/nginx: master  
tcp6       0      0 :::22                   :::*                    LISTEN      926/sshd            
tcp6       0      0 ::1:25                  :::*                    LISTEN      1007/master         
[root@ansible-web4 ~]# cat /etc/nginx/nginx.conf | grep pro
#worker_processes auto;
worker_processes 2;

访问:

项目实战:通过ansible上线

项目一:部署jenkins.war

项目描述:
1.准备两台机器,一台作为nginx代理。一台为tomcat服务器。
2.tomcat服务器部署tomcat服务,并将webapps目录下面的内容提前删掉。
3.将jenkins.war包与jdk、tomcat上传到nginx服务器。通过ansible将包拷贝过去。部署并启动tomcat
4.配置nginx反向代理tomcat,实现访问jenkins。
操作如下:
一、tomcat服务器
2.添加tomcat启动脚本中添加环境变量
[root@ansible-web2 ~]# vim /usr/local/tomcat/bin/startup.sh  #需要添加如下内容
source /etc/profile
#为了确保 Tomcat 能够正确地识别 Java 环境变量(如 JAVA_HOME 和 PATH),你需要在 Tomcat 的启动脚本中引入系统的环境变量。
====================================
二、nginx服务器:
1.安装nginx与ansible。
2.ansible配置
3.定义变量:
[root@ansible ansible]# mkdir vars
[root@ansible ansible]# vim vars/file.yml
src_path: /root/jenkins.war
src_jdk_path: /root/jdk-8u191-linux-x64.tar.gz
src_tomcat_path: /root/apache-tomcat-8.5.51.tar.gz
dest_path: /usr/local/tomcat/webapps/
dest_jdk_path: /usr/local/
dest_tomcat_path: /usr/local/
​4.配置playbook
[root@ansible ansible]# vim jenkins.yml
- hosts: ansible-web1
  user: root
  vars_files:
  - /etc/ansible/vars/file.yml
  tasks:

  - name: unarchive jdk package
    unarchive: src={{ src_jdk_path }} dest={{ dest_jdk_path }} ##可以用解压模块代替复制并解压
  - name: rename to java
    shell: mv /usr/local/jdk1.8.0_191 /usr/local/java
  - name: configure JDK envirement1
    shell: echo "JAVA_HOME=/usr/local/java" >> /etc/profile
  - name: configure JDK envirement2
    shell: echo 'PATH=$JAVA_HOME/bin:$PATH' >> /etc/profile
​
  - name: copy tomcat
    copy: src={{ src_tomcat_path }} dest={{ dest_tomcat_path }}
  - name: unzip tomcat
    shell: tar -xvzf /usr/src/apache-tomcat-8.5.51.tar.gz -C /usr/local
  - name: rename to tomcat
    shell: mv /usr/local/apache-tomcat-8.5.51 /usr/local/tomcat
  
  - name: add /etc/profile
    shell: sed -i "2i source /etc/profile" /usr/local/tomcat/bin/startup.sh
  - name: add /etc/profile to shutdown.sh
    lineinfile: path=/usr/local/tomcat/bin/shutdown.sh insertafter='/bin/sh' line='source /etc/profile'

  - name: delete webs
    shell:  rm -rf /usr/local/tomcat/webapps/* --no-preserve-root
  - name: copy jenkins
    copy: src={{ src_path }}  dest={{ dest_path }}
    notify: start jenkins
  handlers:
  - name: start jenkins
    shell: nohup /usr/local/tomcat/bin/startup.sh &
[root@ansible ansible]# ansible-playbook jenkins.yml
5.配置nginx反向代理
[root@ansible ansible]# vim /etc/nginx/conf.d/jenkins.conf
server {
    listen       80;
    server_name  localhost;
​
    charset koi8-r;
    access_log  /var/log/nginx/host.access.log  main;
​
    location /jenkins {
        proxy_pass http://192.168.1.12:8080;
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
​
}
6.启动nginx
7.检查nginx与tomcat是否启动成功!
8.访问nginx服务器http://ip/jenkins。

项目二、部署jspgou.zip

[root@ansible ansible]# vim vars/file1.yml
src_path: /root/jspgouV6.1-ROOT.zip
src_jdk_path: /root/jdk-8u421-linux-x64.tar.gz
src_tomcat_path: /root/apache-tomcat-9.0.91.tar.gz
dest_path: /root/
dest_jdk_path: /usr/local/
dest_tomcat_path: /usr/local/

 编写playbook

[root@ansible ansible]# vim jspgou.yml
---
- hosts: 192.168.157.128
  gather_facts: false     # 注意添加忽略错误,避免因为unzip的报错导致无法进行
  ignore_errors: True
  user: root
  vars_files:
    - /etc/ansible/vars/file1.yml

  tasks:
    - name: Unarchive JDK package
      unarchive:
        src: "{{ src_jdk_path }}"
        dest: "{{ dest_jdk_path }}"
    
    - name: Rename JDK directory to java
      shell: mv /usr/local/jdk1.8.0_421 /usr/local/java
    
    - name: Configure JAVA_HOME environment variable
      shell: echo "JAVA_HOME=/usr/local/java" >> /etc/profile
    
    - name: Add PATH for JDK to environment
      shell: echo 'PATH=$JAVA_HOME/bin:$PATH' >> /etc/profile
    
    - name: Copy Tomcat package
      copy:
        src: "{{ src_tomcat_path }}"
        dest: "{{ dest_tomcat_path }}"
    
    - name: Unpack Tomcat archive
      shell: tar -xvzf /usr/local/apache-tomcat-9.0.91.tar.gz -C /usr/local
    
    - name: Rename Tomcat directory
      shell: mv /usr/local/apache-tomcat-9.0.91 /usr/local/tomcat
    
    - name: Add source /etc/profile to startup.sh
      lineinfile:
        path: /usr/local/tomcat/bin/startup.sh
        insertafter: '/bin/sh'
        line: 'source /etc/profile'
    
    - name: Add source /etc/profile to shutdown.sh
      lineinfile:
        path: /usr/local/tomcat/bin/shutdown.sh
        insertafter: '/bin/sh'
        line: 'source /etc/profile'
    
    - name: Delete web applications in Tomcat
      shell: /bin/rm -rf /usr/local/tomcat/webapps/* --no-preserve-root
    
    - name: Install unzip
      yum:
        name: unzip
        state: latest
    
    - name: copy jspgou
      copy: src=/root/jspgouV6.1-ROOT.zip dest=/root/

    - name: unzip jspgou package
      unarchive:
        src: /root/jspgouV6.1-ROOT.zip
        dest: /root/
        copy: no

    - name: Copy ROOT directory to Tomcat's webapps
      shell: /bin/cp -rf /root/ROOT/ /usr/local/tomcat/webapps/
    
    - name: Install MariaDB
      yum:
        name: mariadb-server
        state: latest
    
    - name: Start MariaDB service
      service:
        name: mariadb
        state: started
    
    - name: Create jspgou database with UTF-8 character set
      shell: mysqladmin create jspgou --default-character-set=utf8
    
    - name: Load SQL file into jspgou database
      shell: mysql -D jspgou < /root/DB/jspgou.sql
      notify:
        - start Tomcat

  handlers:
    - name: start Tomcat
      shell: nohup /usr/local/tomcat/bin/startup.sh &

[root@ansible ansible]# ansible-playbook jspgou.yml --syntax-check
[root@ansible ansible]# ansible-playbook jspgou.yml

面试

公司服务器怎么管理

使用跳转机管理

1.通过编写跳转机脚本          2.jumpserver产品JumpServer 文档

==服务器并托管==
1.了解DELL常见服务器的价格、型号、配置(CPU,内存、硬盘、支持的RAID功能)
1. Dell PowerEdge R740
价格范围:约 3,000−3,000−10,000 美元(取决于配置)
型号:R740
配置CPU:支持最多两个 Intel Xeon Scalable Processors (如 Silver 4110, Gold 6130)
内存:最高支持 24 个 DIMM 插槽,最大容量可达 3TB DDR4 内存
硬盘:支持最多 16 个 2.5 英寸硬盘或 SSD
RAID 功能:支持 RAID 0, 1, 5, 6, 10, 50, 60
扩展性:支持 PCIe 扩展插槽
2. Dell PowerEdge R750
价格范围:约 4,000−4,000−15,000 美元(取决于配置)
型号:R750
配置CPU:支持最多两个第 3 代 Intel Xeon Scalable Processors
内存:最高支持 32 个 DIMM 插槽,最大容量可达 4TB DDR4 内存
硬盘:支持最多 16 个 2.5 英寸硬盘或 SSD
RAID 功能:支持 RAID 0, 1, 5, 6, 10, 50, 60
扩展性:支持 PCIe Gen 4 扩展插槽
3. Dell PowerEdge R6515
价格范围:约 3,500−3,500−12,000 美元(取决于配置)
型号:R6515配置CPU:支持最多一个 AMD EPYC 7003 系列处理器
内存:最高支持 24 个 DIMM 插槽,最大容量可达 2TB DDR4 内存硬盘:支持最多 10 个 2.5 英寸硬盘或 SSDRAID 功能:支持 RAID 0, 1, 5, 6, 10, 50, 60扩展性:支持 PCIe Gen 4 扩展插槽
4. Dell PowerEdge R7525
价格范围:约 4,500−4,500−18,000 美元(取决于配置)
型号:R7525
配置CPU:支持最多两个 AMD EPYC 7003 系列处理器
内存:最高支持 32 个 DIMM 插槽,最大容量可达 4TB DDR4 内存
硬盘:支持最多 24 个 2.5 英寸硬盘或 SSD
RAID 功能:支持 RAID 0, 1, 5, 6, 10, 50, 60
扩展性:支持 PCIe Gen 4 扩展插槽
2.了解HP常见服务器的价格、型号、配置(CPU,内存、硬盘、支持的RAID功能)
3.了解常见的硬盘接口类型、速率、价格如:ATA, SATA, SCSI, SAS, FC4. 
4.了解国内主要是北京托管商的信息如:厂商名称、托管的价格、地理位置(光环新网/世纪互联)
==云主机==
1.了解阿里云价格、基本部署---ecs、rds(数据库)-slb
2.了解华为云价格、基本部署
3. 了解腾讯云价格、基本部署
==DNS 解析==
1. 了解国内主要的DNS ISP如万网、新网、DNSPOD、阿里DNS
==CDN 技术==

 1.了解国内主要的3家CDN ISP,对比其价格、性能、市场的占有率等。
cdn得功能,为什么要用cdn?

  • 21
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值