ansible自定义模板部署apache服务

使用Ansible来部署Apache服务是一个很好的选择,因为它可以自动化部署过程,确保所有的服务器上都有相同的配置。以下是一个简单的步骤指南,展示如何使用Ansible来部署Apache服务:

1 创建角色目录

首先,在 /etc/ansible/roles 下创建 apache 目录:

mkdir -p /etc/ansible/roles/apache 

2 创建角色内的目录结构

apache 角色目录下,你需要创建几个子目录:tasks, templates, files, handlers, vars, meta, 和 defaults(尽管不是所有的都是必要的,但通常 taskstemplates 是必须的)。

cd /etc/ansible/roles/apache mkdir tasks templates 

3 编写 tasks/main.yml

tasks/main.yml 中,你将定义安装和配置 Apache 的步骤。

--- - name: Install httpd   yum:     name: httpd     state: present  - name: Start httpd service   service:     name: httpd     state: started     enabled: yes  - name: Stop firewalld   service:     name: firewalld     state: stopped     enabled: no  - name: Create /site directory   file:     path: /var/www/html/site     state: directory     mode: '0755'  - name: Template index.html   template:     src: index.html.j2     dest: /var/www/html/site/index.html     mode: '0644' 

4 编写 templates/index.html.j2

templates/index.html.j2 中,你将使用 Jinja2 模板语法来插入主机名和 IP 地址。

Welcome to {{ ansible_fqdn }} On {{ ansible_default_ipv4.address }} 

要使用你在 /etc/ansible/roles 目录下创建的 apache 角色,你需要编写一个 Ansible playbook。以下是如何编写并使用该角色的步骤:

5 创建 playbook

/etc/ansible/ 目录下(或者任何你希望存放 playbook 的地方),创建一个新的 playbook 文件,例如 apache.yml

cd /etc/ansible/ touch apache.yml 

然后使用你喜欢的文本编辑器(如 nano, vim, emacs 等)打开 apache.yml 并输入以下内容:

--- - name: Deploy Apache   hosts: your_target_group  # 替换为你的目标主机组名,例如 'webservers'   become: yes  # 使用 sudo 或其他方法提升权限(如果需要)   roles:     - apache  # 调用你创建的 apache 角色 

请注意,your_target_group 需要替换为你的 Ansible 主机清单中定义的一个主机组名。

6 运行 playbook

使用 ansible-playbook 命令运行 playbook:

ansible-playbook apache.yml 

如果你定义了密码提升(即 become: yes),Ansible 可能会提示你输入 sudo 密码(除非你在 ansible.cfg 中配置了 become_method: sudobecome_pass)。
ansible自定义模板部署apache服务

7 验证结果

一旦 playbook 运行完成,你可以登录到目标机器上检查 Apache 是否已正确安装、启动,并且 /site/index.html 文件是否已正确创建。

你可以使用以下命令来检查 Apache 的状态:

sudo systemctl status httpd 

ansible自定义模板部署apache服务

并使用 curlwget 来检查 /site/index.html 文件的内容:

curl http://localhost/site/index.html 

ansible自定义模板部署apache服务

或者

wget -qO- http://localhost/site/index.html 

注意:如果你是在本地测试,并且 Apache 监听在默认的 80 端口上,那么 http://localhost 应该是正确的。但如果你是在远程机器上运行,你需要将 localhost 替换为远程机器的实际 IP 地址或域名。

8 验证后卸载apache

编写Ansible playbook,该playbook包含必要的步骤来在目标主机上卸载Apache。

-- - hosts: tests // 指定此playbook将在哪些主机上运行   tasks:     - name: stop httpd server // 停止httpd服务       service: name=httpd state=stopped       notify:         - remove httpd   handlers:     - name: remove httpd       yum: name=httpd state=removed 

运行此playbook,您可以使用以下命令(假设playbook文件名为remove_httpd.yml):

ansible-playbook remove_httpd.yml 

ansible自定义模板部署apache服务

发表评论

评论已关闭。

相关文章