- hosts: tmp1
tasks:
- name: Find all test* files in /root/test
ansible.builtin.find:
paths: /root/test
patterns: 'test*'
recurse: no
register: found_files
- name: Debug found_files
ansible.builtin.debug:
var: found_files
- name: Set the priority order of test* files
ansible.builtin.set_fact:
files_by_priority: >
{{
[
found_files.files
| selectattr('path', 'search', 'test-1')
| list
| first
| default({}),
found_files.files
| selectattr('path', 'search', 'test')
| list
| first
| default({}),
found_files.files
| selectattr('path', 'search', 'test-2')
| list
| first
| default({})
]
| selectattr('path', 'defined')
}}
- name: Debug files_by_priority
ansible.builtin.debug:
var: files_by_priority
- name: Determine the latest test* file to execute
ansible.builtin.set_fact:
latest_file: "{{ (files_by_priority | first).path | default('') }}"
- name: Debug latest_file
ansible.builtin.debug:
msg: "Latest file to execute: {{ latest_file }}"
- name: Fail if no test* file is found
ansible.builtin.fail:
msg: "No test* file found in /root/test"
when: latest_file == ''
- name: Ensure the latest test* file is executable
ansible.builtin.file:
path: "{{ latest_file }}"
mode: '0755'
become: yes
- name: Check the first line of the script
ansible.builtin.command:
cmd: head -n 1 "{{ latest_file }}"
register: script_header
become: yes
- name: Debug the shebang line
ansible.builtin.debug:
msg: "Shebang line: {{ script_header.stdout }}"
- name: View the content of the script
ansible.builtin.command:
cmd: cat "{{ latest_file }}"
register: script_content
become: yes
- name: Debug the content of the script
ansible.builtin.debug:
msg: "{{ script_content.stdout }}"
- name: Execute the latest test* file
ansible.builtin.command:
cmd: "{{ latest_file }}"
become: yes
register: start_output
- name: Print the output of the test* file execution
ansible.builtin.debug:
msg: "{{ start_output.stdout }}"
when: start_output.stdout is defined
- name: Execute c.sh script
ansible.builtin.shell:
cmd: cd /root/test2 && ./c.sh
become: yes
#第一个执行的文件有先后排序,执行第一个的需求
#执行命令:ansible-playbook -i hosts mount.yaml