1、生成HTML文件
- name: Generate HTML files on each client and collect them
hosts: all
become: yes
tasks:
- name: Generate HTML file with last command output
shell: |
echo "
<html>
<head>
<meta charset=\"UTF-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
<title>Last Command Output</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
pre { white-space: pre-wrap; word-wrap: break-word; }
</style>
</head>
<body>
<h1>Last Command Output</h1>
<pre>$(last)</pre>
</body>
</html>" > /tmp/{{ inventory_hostname }}.html
changed_when: false
2、文件存在性检查与收集
- name: Check if the HTML file exists
stat:
path: /tmp/{{ inventory_hostname }}.html
register: file_stat
- name: Fail if HTML file does not exist
fail:
msg: "/tmp/{{ inventory_hostname }}.html file does not exist."
when: not file_stat.stat.exists
- name: Fetch HTML files from clients to Ansible server
fetch:
src: /tmp/{{ inventory_hostname }}.html
dest: /tmp/collected_files/
flat: yes
3、移动文件至Web目录
name: Move HTML files to /var/www/html on Ansible control node
hosts: localhost
become: yes
tasks:
name: Ensure destination directory exists
file:
path: /var/www/html
state: directory
name: Move HTML files to /var/www/html
shell: |
if [ -d /tmp/collected_files ]; then
mv /tmp/collected_files/*.html /var/www/html/
else
echo "No files to move"
fi
args:
warn: false
register: mv_result
ignore_errors: yes
name: Check if files were moved successfully
debug:
msg: "Files moved successfully."
when: mv_result.rc == 0
name: Fail if there was an error moving files
fail:
msg: "Failed to move files from /tmp/collected_files/ to /var/www/html/"
when: mv_result.rc != 0
如果喜欢这篇文章,请点下方在看,
后续推荐更多类似文章