25.ansible的hostname模块

hostname模块

参数 类型 必填 默认值 说明
name 字符串 --- 要设置的主机名 • 必须符合 DNS 命名规范: - 仅允许小写字母、数字、连字符 - - 不能以 - 开头或结尾 - 长度建议 ≤ 63 字符
permanent 布尔值 yes - yes(默认):永久修改(写入 /etc/hostname 等配置文件) - no:仅临时修改(当前会话生效,重启后恢复)
use 字符串 自动检测 指定底层工具: • hostnamectl(systemd 系统) • sysctl(旧系统) • 通常无需手动指定

示例:配置主机名

yaml 复制代码
- name: 设置永久主机名
  ansible.builtin.hostname:
    name: web-server-01
    # 默认永久修改,可省略
    permanent: yes
yaml 复制代码
- name: 临时修改主机名(重启失效)
  hostname:
    name: temp-test
    # 非永久修改
    permanent: no
yaml 复制代码
- name: 仅当主机名不匹配时才修改
  hostname:
    name: "{{ target_hostname }}"
  # - ansible_hostname 是 Ansible 自动采集的 fact 变量,表示目标主机当前的短主机名(不含域名)
  # - target_hostname 是用户定义的期望主机名(通常来自变量或 inventory)
  # - 此条件避免不必要的主机名修改,提升幂等性和执行效率  
  when: ansible_hostname != target_hostname
  # 提权
  become: yes
相关推荐
热爱Liunx的丘丘人3 小时前
Ansible-doc及常用模块
linux·运维·服务器·ansible
亚空间仓鼠3 天前
Ansible之Playbook(一):简单应用
ansible
亚空间仓鼠3 天前
Ansible之Playbook(六):实例部署实战
linux·网络·ansible
小梦爱安全3 天前
ansible基础配置和ansible模块
运维·自动化·ansible
亚空间仓鼠5 天前
Ansible之Playbook(三):变量应用
java·前端·ansible
亚空间仓鼠5 天前
Ansible之Playbook(二):模块大全
ansible
亚空间仓鼠5 天前
Ansible之Playbook(四):循环与判断
java·服务器·ansible
Harvy_没救了6 天前
Ansible 学习指南
linux·运维·服务器·ansible
TechWJ6 天前
Ansible 跨千台机器批量部署,Node Exporter 监控实现 Prometheus 统一采集
ansible·prometheus
淼淼爱喝水6 天前
Ansible 批量运维实战:openEuler 环境一键安装 httpd 服务
运维·ansible