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
相关推荐
梅孔立11 天前
Ansible 100 台服务器一键管控实战 进阶版
服务器·git·ansible
henry10101014 天前
Ansible自动化运维全攻略(AI生成)
linux·运维·python·ansible·devops
only_Klein17 天前
Ansible变量详解
运维·自动化·ansible
only_Klein17 天前
Ansible Roles 详解
自动化·ansible·role
only_Klein17 天前
Ansible 条件判断与流程控制详解
自动化·ansible
axPpcfNN18 天前
可直接编译运行 c#解析dxf可读取圆直线弧多段线源码-无封装缩放拖拽 可读取坐标信息 支持多...
ansible
Maggie_ssss_supp19 天前
Linux-ansible自动化运维
运维·自动化·ansible
迎仔19 天前
10-算力中心运维三剑客:Ansible + Jenkins + K8s 高效实战
运维·kubernetes·ansible·jenkins
Cloud Traveler24 天前
Ansible+cpolar:NAS 远程自动化运维方案
ansible