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

AWX工作流中如何获取源Windows主机名命名目标JSON文件

AWX工作流中正确获取源Windows主机名的解决方法

问题根源

你设置set_stats时将per_host设为no,这会把统计数据标记为全局变量。如果作业1在多台主机上执行,所有主机的current_hostname值会被合并拼接,导致作业2拿到的是多个主机名的组合。

解决方案

方案1:限制作业1仅在源Windows主机上执行

确保作业1只针对目标源Windows主机运行(通过主机组、执行限制实现),然后直接存储该主机的名称:

- name: 读取JSON并存储统计数据
  hosts: windows_source_hosts  # 指定仅包含源Windows主机的组
  tasks:
    - name: 读取JSON文件内容
      win_shell: Get-Content C:\target\file.json | ConvertFrom-Json
      register: json_content

    - name: 存储JSON内容到test_stat
      set_stats:
        data:
          test_stat: "{{ json_content.stdout }}"
        per_host: no

    - name: 存储源主机名到source_hostname
      set_stats:
        data:
          source_hostname: "{{ ansible_hostname }}"  # 用ansible_hostname取主机名,或inventory_hostname取清单中定义的名称
        per_host: no

作业2中直接调用source_hostname作为文件名即可:

- name: 生成命名正确的JSON文件
  copy:
    content: "{{ test_stat }}"
    dest: "/path/to/{{ source_hostname }}.json"

方案2:保留主机级统计数据,作业2中筛选提取

如果作业1必须在多台主机执行,将per_host设为yes存储每个主机的统计数据,再在作业2中指定提取源主机的名称:
作业1的Playbook片段:

- name: 存储主机名(按主机独立存储)
  set_stats:
    data:
      current_hostname: "{{ ansible_hostname }}"
    per_host: yes

作业2中提取目标源主机的名称:

- name: 获取源Windows主机名
  set_fact:
    source_hostname: "{{ hostvars[target_source_host].current_hostname }}"
  vars:
    target_source_host: "{{ groups['windows_source_hosts'][0] }}"  # 取源主机组中指定的主机,按需调整

- name: 生成JSON文件
  copy:
    content: "{{ test_stat }}"
    dest: "/path/to/{{ source_hostname }}.json"

方案3:将主机名与JSON内容绑定存储

直接把主机名和JSON内容打包成字典存储,避免变量混淆:
作业1的Playbook片段:

- name: 存储带主机名的JSON数据
  set_stats:
    data:
      test_data:
        hostname: "{{ ansible_hostname }}"
        content: "{{ json_content.stdout }}"
    per_host: no

作业2中直接调用字典中的字段:

- name: 生成命名正确的JSON文件
  copy:
    content: "{{ test_data.content }}"
    dest: "/path/to/{{ test_data.hostname }}.json"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:40:29