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
相关推荐
Cloud Traveler3 天前
Ansible+cpolar:NAS 远程自动化运维方案
ansible
陈桴浮海3 天前
【Linux&Ansible】学习笔记合集七
linux·学习·ansible
only_Klein5 天前
Ansible自动化部署Kubernetes
kubernetes·自动化·ansible
陈桴浮海5 天前
【Linux&Ansible】学习笔记合集五
linux·云原生·ansible
杨了个杨89826 天前
Ansible Playbook 的常用模板
java·服务器·ansible
陈桴浮海6 天前
【Linux&Ansible】学习笔记合集四
linux·学习·ansible
杨了个杨89827 天前
Ansible的常见用法
ansible
陈桴浮海7 天前
【Linux&Ansible】学习笔记合集三
linux·运维·云原生·ansible
Sheffield8 天前
command和shell模块到底区别在哪?
linux·云计算·ansible