Ansible 核心运维场景落地:YUM 仓库、SSH 公钥、固定 IP 配置技巧

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

相关推荐
孙克旭_1 天前
kind部署K8S集群并将“修仙业务“部署到kind集群
linux·运维·云原生·kubernetes·kind
IT成长日记1 天前
【LVS入门宝典】探秘LVS透明性:客户端如何“看不见”后端服务器的魔法
运维·服务器·负载均衡·lvs·透明性
IT成长日记1 天前
【LVS入门宝典】LVS DR模式深度解析:直接路由(DR)的高性能秘诀,MAC地址欺骗与ARP隔离
linux·运维·负载均衡·lvs·arp
HappyGame021 天前
Linux多进程编程(上)
linux
小红帽6151 天前
Web服务器(Nginx和Apache)
服务器·前端·nginx
wanhengidc1 天前
新手玩家如何使用云手机
运维·服务器·网络·游戏·智能手机
半梦半醒*1 天前
在Linux中部署tomcat
java·linux·运维·服务器·centos·tomcat
半梦半醒*1 天前
haproxy负载均衡
linux·运维·服务器·centos·负载均衡
黑马金牌编程1 天前
总结一下MySQL数据库服务器性能优化的几个维度
服务器·数据库·mysql·性能优化
间彧1 天前
Windows server局域网内配置NTP时间同步
服务器