【问题标题】:saving variables from playbook run to ansible host local file将剧本运行中的变量保存到 ansible 主机本地文件
【发布时间】:2020-08-16 16:20:47
【问题描述】:

我正在尝试从 ansible playbook 运行中构建库存文件。 我试图通过同时运行service libvirtd statusvirsh list --all 来列出所有kvm 主机和在其上运行的来宾,并将值存储在ansible 主机上的文件中。 我尝试了几种不同的剧本结构,但都没有成功写入文件(使用local_action 仅从一台主机编写了ansible_hostname)。 请有人指导我做错了什么? 这就是我正在运行的:

- name: Determine KVM hosts
  hosts: all
  become: yes
  #gather_facts: false

  tasks:
    - name: Check if libvirtd service exists
      shell: "service libvirtd status"
      register: libvirtd_status
      failed_when: not(libvirtd_status.rc == 0)
      ignore_errors: true

    - name: List KVM guests
      shell: "virsh list --all"
      register: list_vms
      when: libvirtd_status.rc == 0
      ignore_errors: true

    - name: Write hostname to file
      lineinfile:
        path: /tmp/libvirtd_hosts
        line: "{{ ansible_hostname }} kvm guests: "
        create: true
    #local_action: copy content="{{ item.value }}" dest="/tmp/libvirtd_hosts"
      with_items:
          - variable: ansible_hostname
            value: "{{ ansible_hostname }}"
          - variable: list_vms
            value: "{{ list_vms }}"
      when: libvirtd_status.rc == 0 or list_vms.rc == 0

【问题讨论】:

    标签: ansible centos7 centos6 debian-based


    【解决方案1】:

    能够拼凑出大部分正常工作的东西:

    - name: Check if libvirtd service exists
          shell: "service libvirtd status"
          register: libvirtd_status
          failed_when: libvirtd_status.rc not in [0, 1]
    
        - name: List KVM guests
          #shell: "virsh list --all"
          virt:
            command: list_vms
          register: all_vms
          when: libvirtd_status.rc == 0
    
    ---
    - name: List all KVM hosts
      hosts: production, admin_hosts, kvm_hosts
      become: yes
    
      tasks:
        - name: create file
          file:
              dest: /tmp/libvirtd_hosts
              state: touch
          delegate_to: localhost
    
        - name: Copy VMs list
          include_tasks: run_libvirtd_commands.yaml
    
        - name: saving cumulative result
          lineinfile:
             line: '{{ ansible_hostname }} has {{ all_vms }}'
             dest: /tmp/libvirtd_hosts
             insertafter: EOF
          delegate_to: localhost
          when: groups["list_vms"] is defined and (groups["list_vms"] | length > 0)
    

    现在,如果我能清理输出以过滤掉误报(没有 libvirtd 状态的机器,并且有一个空/没有虚拟机列表,因为上面的方法并没有真正起作用。

    但至少所有KVM主机都有输出!

    【讨论】:

      猜你喜欢
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多