我正在为一个实验室项目编写一本剧本,该项目使用 EC2 实例来托管网站。我目前使用 ubuntu 作为操作系统。所以默认情况下安装并启用apache2时,默认的index.html文件存储在/var/www/html/目录中。
我编写了一个任务,在从 gitrepo 提取网站源代码之前删除 index.html 文件。一切正常,但问题是,如果我再次运行此剧本,删除 index.html 文件将运行并导致我的网站瘫痪。到目前为止,我的解决方案是在我的剧本上第一次运行后评论/删除删除index.html 任务。现在还好。作为一名学生,我想学习更好的方法来解决这个问题。我尝试使用“run_once”,但我似乎无法让它实际只运行一次,再也不会运行。
非常感谢任何建议或提示。谢谢!
库存档案:
all:
hosts:
webserver:
ansible_host:
ansible_user:
ansible_ssh_private_key_file:
webserver02:
ansible_host:
ansible_user:
ansible_ssh_private_key_file:
webserver03:
ansible_host:
ansible_user:
ansible_ssh_private_key_file:
children:
webservers:
hosts:
webserver:
webserver02:
webserver03:
Playbook.yaml:
- name: Install webserver packages
hosts: webservers
become: yes
#vars:
tasks:
- name: Install apache2
ansible.builtin.apt:
name: "{{item}}"
state: latest
update_cache: yes
loop:
- apache2
- git
- zip
- unzip
- name: Start apache2 service
ansible.builtin.service:
name: apache2
state: started
enabled: yes
** ###Delete this tasks after running the playbook once###
- name: Remove default index.html
ansible.builtin.file:
path: /var/www/html/index.html
state: absent**
- name: Clone the source code
ansible.builtin.git:
repo: "{{gitrepo}}" ###git source code###
dest: "{{index_html}}" ###/var/www/html###
single_branch: yes
version: gottoweb
notify: #the handler will only get executed if there is a change in the git task
- restart apache2 service
handlers: #this handler only restarts apache2 when there is a change in the git task
- name: restart apache2 service
ansible.builtin.service:
name: apache2
state: restarted
enabled: yes
在相关任务上尝试了不同的方法,例如“run_once”和“delegate_to”
默认情况下,安装并启用
时,默认的apache2
文件存储在index.html
目录中。在从 Git 存储库中提取网站源代码之前,我编写了一个任务来删除/var/www/html/
文件。一切正常,但问题是,如果我再次运行此剧本,删除index.html
文件将运行并导致我的网站瘫痪。index.html
我知道您喜欢使 Ansible 剧本具有幂等性,并且只“删除”默认的
index.html
但不删除您自己的项目文件。
这可以通过类似的任务轻松实现
- name: Backup once in preparation for overwrite
copy:
remote_src: true
src: /var/www/html/index.html
dest: /var/www/html/index.html.default
force: false
仅当任务之前未成功运行时,才会创建默认
index.html
的副本 (force: false
)。您不仅可以从 Git 存储库中提取网站的源代码,其中包含项目 index.html
文件。它将用您的版本覆盖左侧默认的 index.html
文件。
进一步简化,可能根本不需要备份、移动或删除默认配置,只需删除该任务并让
git
任务覆盖文件即可。