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
相关推荐
江华森15 小时前
Ansible 自动化运维:从入门到实战
运维·自动化·ansible
JackSparrow4142 天前
使用Ansible批量管理+更新产品环境服务器配置
运维·服务器·ci/cd·kubernetes·自动化·ansible·sre
Cat_Rocky5 天前
Linux-ansible之Playbook简单应用
linux·网络·ansible
淼淼爱喝水6 天前
Ansible 入门实战:四种变量优先级比较实验
ansible·变量
淼淼爱喝水6 天前
ansible实战:「磁盘空间 ≥ 2G 时自动创建文件」
前端·ansible·自动创建
红茶要加冰7 天前
四、ansible的templates
linux·运维·服务器·ansible
红茶要加冰7 天前
五、ansible的流程控制
linux·运维·服务器·ansible
Cat_Rocky7 天前
Linux学习-ansible自动化
linux·学习·ansible
大白菜和MySQL8 天前
ansible使用简记
ansible
灰色人生qwer8 天前
入门 Ansible
ansible·ansible tower