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 常用模块详解:lineinfile、replace、get_url实战
linux·python·ansible
我爱学习好爱好爱17 小时前
Ansible 环境搭建
linux·运维·ansible
淼淼爱喝水18 小时前
openEuler 系统下 Ansible 一键安装教程(保姆级)
运维·ansible·openeuler
我爱学习好爱好爱1 天前
Ansible 常用模块详解:hostname、selinux 、file实战
前端·chrome·ansible
我爱学习好爱好爱1 天前
Ansible 常用模块详解:yum、service/systemd、copy实战
linux·服务器·ansible
淼淼爱喝水2 天前
Ansible 配置与环境搭建超全教程(自动化运维基础)
运维·自动化·ansible
我爱学习好爱好爱3 天前
Ansible 入门:ad-hoc 临时命令与常用模块
linux·服务器·ansible
Yana.nice4 天前
Ansible 常用模块
网络·python·ansible
feng68_4 天前
Ansible还原数据库节点
linux·运维·数据库·ansible
SPC的存折4 天前
1、Ansible之Ansible安装与入门
linux·数据库·ansible