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