一.示例1
需求:通过YAML编写一个简单的剧本,完成web的部署,配置,启动的全过程。
1.第一步
准备工作
####准备工作
ansible all -m yum -a 'name=httpd state=removed' -o #清理旧环境
yum install -y httpd #准备配置文件
在httpd服务中修改端口
mkdir apache
cd apache
cp /etc/httpd/conf/httpd.conf .
grep '^Listen' httpd.con
2.第二步
编写剧本
###编写剧本
- hosts: host1 ####指定了目标主机组,即要在其中执行任务的主机。
tasks: ###一个任务列表,其中包含一系列要在目标主机上执行的任务
- name: install apache packages ##任务的名称,用于执行时标识这个任务,也可以自定义
yum: name=httpd state=present
- name: copy apache conf
copy: src=./httpd.conf dest=/etc/httpd/conf/httpd.conf
- name: ensure apache is running
service: name=httpd state=started enabled=yes
####详细解释
hosts: host2 指定了目标主机组,即要在其中执行任务的主机。你需要在 Ansible 的 inventory 文件中定义这个主机组。
tasks 是一个任务列表,其中包含一系列要在目标主机上执行的任务。
name: install apache packages 是任务的名称,用于标识这个任务。
yum: name=httpd state=present 是使用 yum 模块执行的任务。yum 模块用于在目标主机上安装软件包。在这里,它指定要安装的软件包名称为 "httpd",并将状态设置为 "present",表示要确保该软件包已安装。
name: copy apache conf 是下一个任务的名称。
copy: src=./httpd.conf dest=/etc/httpd/conf/httpd.conf 是使用 copy 模块执行的任务。copy 模块用于将文件从控制节点复制到目标主机。在这里,它指定要复制的文件路径为 "./httpd.conf",目标路径为 "/etc/httpd/conf/httpd.conf",即将控制节点上的 "./httpd.conf" 文件复制到目标主机的 "/etc/httpd/conf/" 目录下。
name: ensure apache is running 是最后一个任务的名称。
service: name=httpd state=started enabled=yes 是使用 service 模块执行的任务。service 模块用于管理系统服务。在这里,它指定要管理的服务名称为 "httpd",将服务状态设置为 "started",表示要确保服务正在运行,并将服务设置为 "enabled",表示在系统启动时自动启用该服务。
这个 playbook 的目标是在目标主机上安装 Apache 软件包、复制 Apache 配置文件,并确保 Apache 服务正在运行并在系统启动时自动启用。
3.第三步
测试剧本
ansible-playbook apache.yaml --syntax-check ###检验语法
ansible-playbook apache.yaml --list-tasks ###列出任务
ansible-playbook apache.yaml ####执行
如果配置文件发生变化。会怎么样????????????????
ansible-playbook apache.yaml 再次执行,命令成功,但配置未生效,所以要增加处理程序。设置触发器
######配置文件不生效,需要添加触发器
- hosts: host1 。
tasks:
- name: install apache packages
yum: name=httpd state=present
- name: copy apache conf
copy: src=./httpd.conf dest=/etc/httpd/conf/httpd.conf
notify: restart apache service
- name: ensure apache is running
service: name=httpd state=started enabled=yes
handlers:
- name: restart apache service
service: name=httpd state=restarted
#############详细解释
#notify: restart apache service:这个任务在完成复制 Apache 配置文件的操作后,将触发名为 restart apache service 的处理程序。
#handlers::这个部分定义了处理程序,用于在任务中的 notify 语句被触发时执行特定的操作。
service: name=httpd state=restarted:这个处理程序使用 service 模块来重启 httpd 服务。它会在复制 Apache 配置文件的任务完成后被触发。
触发器的操作
工作原理:
notify: restart apache service
会触发名为restart apache service
的处理程序。因此,handlers
部分中的 -name: restart apache service
必须与notify
语句中的名称一致。如果它们不一致,处理程序将无法正确触发。确保在notify
语句和处理程序中使用相同的名称可以确保处理程序在适当的时候被触发,以执行所需的操作。
为什么要添加触发器???
notify: restart apache service
语句会触发名为restart apache service(handle)
的处理程序。这个处理程序使用service
模块来重启 Apache 服务。这样,每当复制 Apache 配置文件的任务完成时,处理程序会被触发,确保 Apache 服务重新启动以使配置更改生效。