当 Ansible 中所有主机的 Gather_facts 设置为“no”时,如何在 Ansible 中收集本地主机事实?

stm*_*001 6 ansible

我的剧本使用路由器作为执行任务的主机。我已禁用主机的事实,但我需要ansible_date_time从运行剧本的本地主机进行访问。本地主机是 Ubuntu 虚拟机。

这就是我的剧本的样子:

---
- hosts: lab
  gather_facts: no

  tasks:   
    - name: Run block tasks
      delegate_to: 127.0.0.1
      block:
        - name: Get cert serial number using OpenSSL
          shell: |
            openssl s_client -connect {{ inventory_hostname }}:50051 2>/dev/null  | sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p' |openssl x509 -noout -serial  | cut -d'=' -f2 | sed -e 's/\(.*\)/\L\1/'
          register: serialNum
      
        - name: Print Serial Numbers
          debug:
            msg: "{{ serialNum.stdout_lines }}"

    - name: Ansible fact - ansible_date_time
      # gather_facts: yes
      delegate_to: 127.0.0.1
      debug:
        var: ansible_date_time.date

Run Code Online (Sandbox Code Playgroud)

gather_facts: yes由于出现错误,我无法放入最后一个任务。

如果我gather_facts: yes在游戏级别启用,那么我会得到路由器的事实,这不是我想要的。

按上面的方式运行剧本会给出以下消息:

TASK [Ansible fact - ansible_date_time] ***************************************************************************************************************************************************
ok: [router1.mgt.net] => {
    "ansible_date_time.date": "VARIABLE IS NOT DEFINED!"
}
Run Code Online (Sandbox Code Playgroud)

这可以用 Ansible 来做吗?

Zei*_*tor 3

我不能 100% 确定我了解您的用例,但这是我的看法。

\n

在进一步讨论之前,先做一些说明。

\n
    \n
  • 委派给 127.0.0.1 在全球范围内都是一种不好的做法,因为它可能使用 ssh 而不是local连接插件,并强制您在清单中定义主机而不是使用隐式localhost
  • \n
  • 我们需要从本地主机收集事实以获取其ansible_date_time信息。我们将在一个单独的 play 中执行此操作,并在下一个 play 中将该值分配为 play var,以便于使用。有许多其他方法可以解决这个问题,但最重要的是使用hostvars魔术变量从特定主机获取事实。
  • \n
  • 如果您发现从本地主机收集全套事实过于耗费资源,您可以将我的建议与 @\xce\xb2.\xce\xb5\xce\xb7\xce\xbf\xce\xb9\xcf\ 的建议混合起来x84.\xce\xb2\xce\xb5
  • \n
\n

这是我修复你的剧本的方法(未完全测试)

\n
---\n- name: Gather facts from localhost for later use\n  hosts: localhost\n  # If facts gathering is disabled in ansible.cfg you will\n  # have to turn it on explicitly (i.e. `gather_facts: true`)\n  \n\n- name: Do the actual work on lab routers\n  hosts: lab\n  gather_facts: no\n\n  vars:\n    # Get current date from localhost in a play var\n    current_date: "{{ hostvars[\'localhost\'].ansible_date_time.date }}"\n\n  tasks:   \n    - name: Get cert serial number using OpenSSL\n      shell: |\n        openssl s_client -connect {{ inventory_hostname }}:50051 2>/dev/null  | sed -n -e \'/BEGIN\\ CERTIFICATE/,/END\\ CERTIFICATE/ p\' |openssl x509 -noout -serial  | cut -d\'=\' -f2 | sed -e \'s/\\(.*\\)/\\L\\1/\'\n      register: serialNum\n      delegate_to: localhost\n      \n    - name: Print Serial Numbers\n      debug:\n        msg: "{{ serialNum.stdout_lines }}"\n\n    - name: Show date from localhost gathered at very beginning\n      debug:\n        var: current_date\n
Run Code Online (Sandbox Code Playgroud)\n