You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible中能否用大括号批量安装同前缀apt软件包?

Ansible中apt模块不支持bash大括号展开的问题与解决办法

在Bash Shell中,以下两条apt命令执行效果完全等价:

apt install libreoffice-writer libreoffice-calc libreoffice-impress
apt install libreoffice-{writer,calc,impress}

第二种大括号展开语法能大幅减少重复输入,但将其直接迁移到Ansible 2.14.3的Playbook中时:

---

- hosts: employee
  become: true
  vars:
    supp_dist:
      - "Ubuntu"
      - "Debian"
    supp_dist_ver:
      - "24"
      - "12"

  tasks:
  - name: update client
    apt:
      update_cache: yes
    when: >
      ansible_distribution == "Ubuntu" and
      ansible_distribution_major_version in supp_dist_ver
  - name: install desktop for client
    apt:
      name:
        - xfce4
        - xfce4-goodies
        - libreoffice-gtk4
        - libreoffice-{writer,calc,impress,draw,formulas}
        - libreoffice-l10n-{de,eu,en-gb,uk}

会触发如下错误:

fatal: [test.vms.home.com]: FAILED! => {"changed": false, "msg": "No package matching 'libreoffice-{writer,calc,impress' is available"}

原因说明

Ansible的apt模块不解析Bash的大括号展开语法,它会把带大括号的字符串当作完整的包名去查找,自然找不到对应软件包。

解决办法

1. 手动展开包列表

最直接的方式是把大括号展开的内容手动拆分成列表项:

- name: install desktop for client
  apt:
    name:
      - xfce4
      - xfce4-goodies
      - libreoffice-gtk4
      - libreoffice-writer
      - libreoffice-calc
      - libreoffice-impress
      - libreoffice-draw
      - libreoffice-formulas
      - libreoffice-l10n-de
      - libreoffice-l10n-eu
      - libreoffice-l10n-en-gb
      - libreoffice-l10n-uk

2. 利用Ansible变量生成展开后的列表

通过变量拼接生成完整包名列表,减少重复输入:

---

- hosts: employee
  become: true
  vars:
    supp_dist:
      - "Ubuntu"
      - "Debian"
    supp_dist_ver:
      - "24"
      - "12"
    libreoffice_components:
      - writer
      - calc
      - impress
      - draw
      - formulas
    libreoffice_l10n:
      - de
      - eu
      - en-gb
      - uk
    # 生成完整包名列表
    libreoffice_packages: "{{ ['libreoffice-gtk4'] + libreoffice_components | map('regex_replace', '^', 'libreoffice-') | list + libreoffice_l10n | map('regex_replace', '^', 'libreoffice-l10n-') | list }}"

  tasks:
  - name: update client
    apt:
      update_cache: yes
    when: >
      ansible_distribution == "Ubuntu" and
      ansible_distribution_major_version in supp_dist_ver
  - name: install desktop for client
    apt:
      name:
        - xfce4
        - xfce4-goodies
        - "{{ libreoffice_packages }}"

3. 使用shell模块执行apt命令(不推荐)

如果一定要用Bash的大括号展开,可以通过shell模块调用系统的apt命令,但这种方式会绕过Ansibleapt模块的幂等性检查(重复执行会重复尝试安装),仅在特殊场景下使用:

- name: install desktop for client via shell
  shell: apt install -y xfce4 xfce4-goodies libreoffice-gtk4 libreoffice-{writer,calc,impress,draw,formulas} libreoffice-l10n-{de,eu,en-gb,uk}
  become: true

内容的提问来源于stack exchange,提问作者rbaleksandar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 20:42:36