Ansible无需解压tar.gz包获取其中Nexus版本目录名称的方法
解决方案
有两种常用的实现方式,都可以直接从你下载的原始tar.gz压缩包中读取顶层目录名称,完全不受/srv目录下历史版本的影响:
方法1:使用community.general.archive模块(推荐,原生Ansible方式)
前提是已安装community.general集合,未安装可执行ansible-galaxy collection install community.general完成安装。
任务示例如下:
# 替换path为你实际下载的Nexus压缩包路径,也可以直接用你下载任务中存路径的变量 - name: 读取Nexus压缩包内的顶层目录名称 community.general.archive: path: /opt/download/nexus-latest.tar.gz list: yes register: nexus_archive_content - name: 提取本次安装对应的Nexus版本目录名 ansible.builtin.set_fact: # 过滤出nexus开头的顶层目录,自动去除路径末尾的/ nexus_target_dir: "{{ nexus_archive_content.files | map(attribute='path') | select('match', '^nexus-[^/]+/$') | first | regex_replace('/$', '') }}" - name: 创建Nexus符号链接 ansible.builtin.file: src: "/srv/{{ nexus_target_dir }}" dest: /srv/nexus state: link
方法2:使用tar命令行工具(兼容性更好,无需额外安装集合)
如果环境不方便安装第三方Ansible集合,可以直接调用系统tar命令读取压缩包内容:
# 替换命令中的压缩包路径为你实际的文件路径 - name: 读取Nexus压缩包内的顶层目录名称 ansible.builtin.shell: "tar tf /opt/download/nexus-latest.tar.gz | grep -E '^nexus-[^/]+/$' | head -n 1 | sed 's/\\/$//'" register: nexus_target_dir changed_when: false # 标记任务不会修改目标主机状态,保证幂等性 - name: 创建Nexus符号链接 ansible.builtin.file: src: "/srv/{{ nexus_target_dir.stdout }}" dest: /srv/nexus state: link
内容的提问来源于stack exchange,提问作者30thh
相关产品推荐
相关产品推荐

