1:如何一次性驗證所有主機能否被 Ansible 訪問??
答:使用臨時命令:ansible all -m ansible.builtin.ping
或驗證 sudo 是否正常:ansible all -m ansible.builtin.ping --become -K
2:如何用 Ansible 統一配置 YUM/DNF 倉庫并導入 GPG key??
答:
- 寫倉庫文件:
yaml
- name: 配置 EPEL
? ansible.builtin.yum_repository:
??? name: epel
??? description: EPEL
??? baseurl: https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
??? gpgcheck: 1
??? gpgkey: https://download.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-{{ ansible_distribution_major_version }}
- 導入公鑰:
yaml
- name: 導入 EPEL GPG key
? ansible.builtin.rpm_key:
??? key: https://download.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-{{ ansible_distribution_major_version }}
??? state: present
- 裝包:
yaml
- name: 安裝 htop
? ansible.builtin.dnf:
??? name: htop
??? state: present
3:如何在 100 臺服務器上批量創建運維用戶并下發 SSH 公鑰??
答:用 user + authorized_key 模塊:
yaml
- name: 創建 ops 用戶
? ansible.builtin.user:
??? name: ops
??? groups: wheel
??? shell: /bin/bash
??? generate_ssh_key: yes
- name: 下發公鑰到 ops 用戶
? ansible.posix.authorized_key:
??? user: ops
??? key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"
4:如何確保只有 wheel 組可免密 sudo??
答:用 lineinfile 修改 sudoers:
yaml
- name: 配置 sudoers
? ansible.builtin.lineinfile:
??? path: /etc/sudoers
??? regexp: '^%wheel'
??? line: '%wheel ALL=(ALL) NOPASSWD:ALL'
??? validate: 'visudo -cf %s'
5:如何每天晚上 2 點跑備份腳本??
答:cron 模塊:
yaml
- name: 添加備份計劃任務
? ansible.builtin.cron:
??? name: nightly-backup
??? minute: "0"
??? hour: "2"
??? job: /usr/local/bin/backup.sh
??? user: root
6:如何用系統角色一鍵創建 20 GB 的邏輯卷并掛載到 /data??
答:調用 redhat.rhel_system_roles.storage:
yaml
- hosts: db_servers
? vars:
??? storage_pools:
????? - name: vg_data
??????? disks: [sdb]
??????? volumes:
????????? - name: lv_data
??????????? size: 20g
??????????? mount_point: /data
??????????? fs_type: xfs
? roles:
??? - redhat.rhel_system_roles.storage
7:如何給一批主機同時配置固定 IP、網關和 DNS??
答:使用redhat.rhel_system_roles.network:
yaml
- hosts: web_servers
? vars:
??? network_connections:
????? - name: ens192
??????? type: ethernet
??????? autoconnect: yes
??????? ip:
????????? address:
??????????? - 192.168.10.50/24
????????? gateway: 192.168.10.1
????????? dns:
??????????? - 8.8.8.8
??????????? - 8.8.4.4
??????? state: up
? roles:
??? - redhat.rhel_system_roles.network
8:如何立即重啟機器并等待其重新上線??
答:reboot 模塊:
yaml
- name: 重啟并等待
? ansible.builtin.reboot:
??? reboot_timeout: 600