--become 安裝系統套件-l/--limit 限縮目標主機inventory.ini,且確認每台機器都可以透過 SSH 連線。sudo 權限,因為安裝套件通常會需要較高權限。在 Ansible 世界裡,有兩種常見的操作方式:
今天用 ad-hoc 來做暖身,因為不需撰寫任何 Playbook,並且可以馬上看到結果,也能快速驗證模組參數是否正確。
ansible <pattern> -i inventory.ini \
-m <module_fqcn> -a "<key=value ...>" \
[-b|--become] [--ask-become-pass|-K] [-l <limit>] [-f <forks>]
all、web、db[1:3])。ansible.builtin.package、ansible.builtin.apt。key=value 參數。這邊可以使用跨作業系統通用的 package 模組 (Ansible 會自動挑對應的套件管理器):
ansible all -i inventory.ini -b -m ansible.builtin.package -a "name=htop,git,curl state=present"
說明:
-b 使用 sudo 權限,避免因為權限問題導致無法安裝。state=present 表示若未安裝則安裝,已安裝則不動,具有冪等性。若各位是 Ubuntu/Debian 使用者,可以直接使用 apt 模組:
ansible all -i inventory.ini -b -m ansible.builtin.apt -a "name=htop,git,curl state=present update_cache=yes"
若各位是 RHEL/CentOS/AlmaLinux/Rocky 使用者,可以直接使用 dnf 模組:
ansible all -i inventory.ini -b -m ansible.builtin.dnf -a "name=htop,git,curl state=present"
另外可以用 setup 模組查看每台機器的套件管理器:
ansible all -i inventory.ini -m ansible.builtin.setup -a 'filter=ansible_pkg_mgr'
💡 小提醒:某些發行版可能找不到
btop/htop,請確認套件名稱是否存在該發行版的軟體庫 (RHEL 系列可能需要 EPEL)。
用 ad-hoc 直接驗證是否能執行或找到指令:
ansible all -i inventory.ini -m ansible.builtin.command -a 'htop --version'
ansible all -i inventory.ini -m ansible.builtin.shell -a 'command -v htop'
all:ansible web -i inventory.ini -b -m ansible.builtin.package -a "name=htop state=present"
-l/--limit 在既有 pattern 上再限縮:ansible all -i inventory.ini -l web -b -m ansible.builtin.package -a "name=htop state=present"
-b (需要 sudo),若 sudo 要密碼,再加 -K。apt 模組加 update_cache=yes。-f 20 (請視環境調整)。又來到了今天的重頭戲了,大家來試試看以下的練習吧:
btop 到你的所有主機上 (記得 -b)。web 群組安裝 htop,並使用 -l web 或直接把 pattern 設為 web。command -v btop)。wget,git,curl),並把 -f 調大觀察速度差異。今天學會用 ad-hoc 指令安裝套件,明天來學學怎麼批次修改設定檔案