通过anisble执行一个文件后再执行另一个文件

- 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值