如何通过 Ansible “hostnamectl set-icon-name”?

问题描述 投票:0回答:1

Red Hat 有一个名为

hostnamectl set-icon-name
的命令。使用 Ansible 配置是否正确?

常用命令

ansible.builtin.shell: "hostnamectl set-icon-name {{ inventory_hostname }}"

当然是可能的,但是每次通过时,Ansible 都会认为它正在更改此参数,这不好。

ansible hostname ansible-facts almalinux
1个回答
0
投票

红帽有一个名为

hostnamectl
...

的命令

没错。它通常用于更改主机名。另请参阅

hostnamectl
— 控制系统主机名

请注意

Static hostname
与 RHEL 中的
Icon name
Pretty hostname
有何不同?
以及
hostname != icon-name

icon-name [NAME]

如果没有给出参数,则打印系统的图标名称。如果提供了可选参数

NAME
,则该命令会将图标名称更改为
NAME
。某些图形应用程序使用图标名称来可视化该主机。图标名称应遵循图标命名规范

因此,对于服务器,

Icon name
可能应该设置为
computer
computer-vm
(如果尚未设置)。

~/test$ hostnamectl
   Static hostname: test.example.com
         Icon name: computer-vm
           Chassis: vm
        Machine ID: 1234567890abcdefghijkl1234567890
           Boot ID: 1234567890abcdefghijkl1234567890
    Virtualization: microsoft
  Operating System: RHEL
       CPE OS Name: cpe:/o:redhat:enterprise_linux:7.9:GA:server
            Kernel: Linux 3.10.0-1160.105.1.el7.x86_64
      Architecture: x86-64

由于 Ansible

hostname
模块 – 管理主机名 仅用于设置主机名

设置系统的主机名。支持大多数操作系统/发行版,包括使用

systemd

剩下一个

command
模块 – 在目标上执行命令定义“已更改”,因为
hostname
退出状态
将只是

成功时,返回 0,否则返回非零失败代码。

并为了获得幂等性。这也是因为 Ansible 事实 不收集

Icon name
并且如果没有实施额外的 自定义事实

使用 Ansible 配置是否正确?常用命令

ansible.builtin.shell: "hostnamectl set-icon-name {{ inventory_hostname }}
当然是可能的,但是每次通过时,Ansible 都会认为它正在更改此参数,这不好。

最后,一个最小的示例手册

---
- hosts: localhost
  become: true
  gather_facts: false

  vars:

    ICON_NAME: computer-vm

  tasks:

  - name: Gather Fact via 'hostnamectl' without leading white-space
    shell: hostnamectl | sed "s/^[ \t]*//"
    register: HOSTNAMECTL
    # Since it is reporting task which should run in any case, set
    check_mode: false
    changed_when: false

  - name: Show Fact to get familiar with the data structure
    debug:
      msg: "{{ (HOSTNAMECTL.stdout | from_yaml) }}"

  - name: Set 'Icon name' via 'hostnamectl' idempotent
    command: hostnamectl set-icon-name {{ ICON_NAME }}
    when: ( HOSTNAMECTL.stdout | from_yaml)['Icon name'] != ICON_NAME

将产生

的输出
TASK [Gather Fact via 'hostnamectl' without leading white-spaces] **********************
ok: [localhost]

TASK [Show Fact to get familiar with the data structure] *******************************
ok: [localhost] =>
  msg:
    Architecture: x86-64
    Boot ID: 1234567890abcdefghijkl1234567890
    CPE OS Name: cpe:/o:redhat:enterprise_linux:7.9:GA:server
    Chassis: vm
    Icon name: computer-vm
    Kernel: Linux 3.10.0-1160.105.1.el7.x86_64
    Machine ID: 1234567890abcdefghijkl1234567890
    Operating System: RHEL
    Static hostname: test.example.com
    Virtualization: microsoft

PLAY RECAP *****************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=1
© www.soinside.com 2019 - 2024. All rights reserved.