You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写Ansible Playbook:以指定格式输出resolv.conf中的DNS服务器与主机名

实现「hostname;dns1;dns2;dnsN」格式输出的Ansible Playbook

以下是调整后的Playbook,可直接输出你需要的格式:

- hosts: localhost
  gather_facts: yes

  tasks:
    - name: 检查/etc/resolv.conf是否存在
      stat:
        path: /etc/resolv.conf
      register: resolv_conf

    - name: 输出指定格式的DNS信息
      debug:
        msg: "{{ ansible_hostname }};{{ dns_servers | join(';') }}"
      vars:
        dns_servers: "{{ lookup('file', '/etc/resolv.conf') | regex_findall('\\s*nameserver\\s*(\\S+)') }}"
      when: resolv_conf.stat.exists

关键调整说明:

  • 开启gather_facts: yes,直接通过内置变量ansible_hostname获取本地主机名,无需额外执行命令。
  • 正则表达式改用\s*nameserver\s*(\S+),精确提取DNS服务器地址(\S+确保只取空格后的非空白字符,避免多余格式干扰)。
  • 用join(';')将DNS列表拼接成连续的分号分隔字符串,再与主机名组合成目标格式。
  • 保留了原Playbook中检查文件存在的逻辑,避免文件缺失时触发错误。

如果不想启用gather_facts,可改用以下版本通过命令获取主机名:

- hosts: localhost
  gather_facts: no

  tasks:
    - name: 检查/etc/resolv.conf是否存在
      stat:
        path: /etc/resolv.conf
      register: resolv_conf

    - name: 获取本地主机名
      command: hostname
      register: hostname_output
      when: resolv_conf.stat.exists

    - name: 输出指定格式的DNS信息
      debug:
        msg: "{{ hostname_output.stdout }};{{ dns_servers | join(';') }}"
      vars:
        dns_servers: "{{ lookup('file', '/etc/resolv.conf') | regex_findall('\\s*nameserver\\s*(\\S+)') }}"
      when: resolv_conf.stat.exists

内容的提问来源于stack exchange,提问作者masterzst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 19:45:41