linux - ansible 从另一个任务输出设置事实

标签 linux python ansible

我在一些 ansible 模块上遇到了麻烦。我编写了自定义模块及其输出,如下所示:

ok: [localhost] => {
    "msg": {
        "ansible_facts": {
            "device_id": "/dev/sdd"
        },
        "changed": true,
        "failed": false
    }
}

我的自定义模块:

#!bin/env python
from ansible.module_utils.basic import *
import json
import array
import re

def find_uuid():
  with open("/etc/ansible/roles/addDisk/library/debug/disk_fact.json") as disk_fact_file, open("/etc/ansible/roles/addDisk/library/debug/device_links.json") as device_links_file:
    disk_fact_data = json.load(disk_fact_file)
    device_links_data = json.load(device_links_file)
    device = []
    for p in disk_fact_data['guest_disk_facts']:
      if disk_fact_data['guest_disk_facts'][p]['controller_key'] == 1000 :
        if disk_fact_data['guest_disk_facts'][p]['unit_number'] == 3:
           uuid = disk_fact_data['guest_disk_facts'][p]['backing_uuid'].split('-')[4]
           for key, value in device_links_data['ansible_facts']['ansible_device_links']['ids'].items():
              for d in device_links_data['ansible_facts']['ansible_device_links']['ids'][key]:
                  if uuid in d:
                     if key not in device:
                        device.append(key)
  if len(device) == 1:
     json_data={
         "device_id": "/dev/" + device[0]
     }
     return True, json_data
  else:
    return False

check, jsonData = find_uuid()

def main():
  module = AnsibleModule(argument_spec={})

  if check:
     module.exit_json(changed=True, ansible_facts=jsonData)
  else:
     module.fail_json(msg="error find device")
main()

我想在其他任务上使用 device_id 变量。我认为使用 module.exit_json 方法进行处理,但我该怎么做?

最佳答案

I want to use device_id variable on the other tasks

您正在寻找的是register:,以便使该值保留到运行该任务的主机的“主机事实”中。然后,您可以采用“推”模型,在其中您将这一事实设置在您感兴趣的所有其他主机上,或者您可以采用“拉”模型,其中感兴趣的主机可以在需要时伸出援手以获取值.

让我们看看这两种情况,进行比较。

首先,捕获该值,为了便于讨论,我将使用名为“alpha”的主机:

- hosts: alpha
  tasks:
  - name: find the uuid task
    # or whatever you have called your custom task
    find_uuid:
    register: the_uuid_result

现在,输出可在主机“alpha”上使用 {{ vars["the_uuid_result"]["device_id"] }} ,这将是 /dev/sdd 在上面的示例中。也可以将其缩写为 {{ the_uuid_result.device_id }}

在“推送”模型中,您现在可以迭代所有主机,或者仅迭代特定组中的主机,这些主机也应该接收 device_id 事实;对于此示例,我们将目标定位为名为“need_device_id”的现有主机组:

- hosts: alpha  # just as before, but for context ...
  tasks:
  - find_uuid:
    register: the_uuid_result

  # now propagate out the value
  - name: declare device_id fact on other hosts
    set_fact:
       device_id: '{{ the_uuid_result.device_id }}'
    delegate_to: '{{ item }}'
    with_items: '{{ groups["need_device_id"] }}'

最后,相比之下,如果主机“beta”需要查找主机“alpha”发现的 device_id,则可以伸手拉出这一事实:

- hosts: alpha
  # as before
- hosts: beta
  tasks:
  - name: set the device_id fact on myself from alpha
    set_fact:
      device_id: '{{ hostvars["alpha"]["the_uuid_result"]["device_id"] }}'

您还可以在“alpha”上运行相同的 set_fact: device_id: 业务,以防止名为 the_uuid_result 的“本地”变量从 alpha 的 playbook 中泄漏。由你决定。

关于linux - ansible 从另一个任务输出设置事实,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57680365/

相关文章:

c - 如果我使用 mmap 而不是 malloc 分配内存会怎样?

python - 即使收到警告,我也应该使用 _setit 吗? (tkinter)

python - pymysql - 谷歌云 - 操作错误 : (2003, "Can' t 连接到 MySQL 服务器

ansible - 如何重试可能失败的 Ansible 任务?

java - Buffer Reader 俄语字符编码字符集

javascript - 带有 Ratchet 的 PHP WebSockets - 示例不起作用

xml - Ansible 编辑 XML 文件中同名的多个属性

vagrant - packer + ansible,如何指定库存文件

linux - 恢复 checkout 后所做的更改

python - Python视频降低fps