可靠的。从 "tar.gz" 存档中获取目录名称而不解压缩

Ansible. Get a directory name out of "tar.gz" archive without decompressing

我正在使用 Ansible 安装 Nexus。 Ansible 任务下载打包为“tar.gz”存档的最新版本并将其解压到目标目录中。存档包含两个目录。例如:

/srv
  |- /nexus-3.34.0-01
  |- /sonatype-work

然后 Ansible 需要创建一个符号 link。像这样:

/srv
  |- /nexus-3.34.0-01
  |- /sonatype-work
  |- ~nexus -> /srv/nexus-3.34.0-01

Ansible 不知道 nexus 目录的名称。这不是问题,如果我们只有其中之一:

- name : Find the name of the nexus directory
  ansible.builtin.find:
    paths: /srv
    patterns: 'nexus-*'
    file_type: directory
  register: nexus_dir

- name: Create a symbolic link for Nexus
  ansible.builtin.file:
    src: "{{ nexus_dir.files[0].path }}"
    dest: /srv/nexus
    state: link   

问题是:目录 srv 已经包含以前的 nexus 安装。我如何查看原始存档以找到当前 nexus 目录的名称?

这是我找到的解决方案:

- name : Find the name of the nexus directory
  shell: tar --gzip --list  --file={{ filename_nexus }} | grep -o -E -m 1 ^nexus-[^/]+
  register: nexus_dir

- name: Print found nexus installation
  ansible.builtin.debug:
    msg: "Following nexus installation found: {{ nexus_dir.stdout }}"

其中 grep -o -E -m 1 returns 提供的正则表达式的第一个匹配项。