【问题标题】:Running jq command in ansible tasks在 ansible 任务中运行 jq 命令
【发布时间】:2021-12-31 06:56:50
【问题描述】:

我想让一个文件由两个文件的组合组成循环,我正在使用 ansible 重复执行 jq 命令。这是我在剧本中的任务:

- name: COMBINE JSON FILES
  shell: jq -s '{bgp_verif:.[0], vni_verif:.[1]}' {{ item.name }}-bgp.json {{ item.name }}-vni.json > {{ item.name }}-result.json
  with_file:
    - "/containers/http_server/data/verif_json/{{ item.name }}-bgp.json"
    - "/containers/http_server/data/verif_json/{{ item.name }}-vni.json"
  loop: "{{ get_devices.json.results }}"
  when: "item.device_type.manufacturer.slug == 'cumulus-linux'"

运行剧本后,我收到此错误

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'dict' object has no attribute 'startswith'
fatal: [localhost]: FAILED! => {"msg": "Unexpected failure during module execution.", "stdout": ""}

我在我的任务中遗漏了什么吗?如果您能告诉我如何解决此错误,我将不胜感激,谢谢。

【问题讨论】:

  • 您提到的错误与您粘贴的代码没有直接关系,是吗?据称不存在的“开始”在哪里?尝试添加一些上下文。另外,请注意 Ansible 提供过滤器,例如 from_jsonto_jsonfrom_yamlto_yaml、... 不知道您的上下文:我不确定 jq 是否相关。集成的插件和过滤器往往表现良好。
  • 除了出现与任务无关的错误之外,您还向我们展示了一个完全无效的任务,因为您同时指定了loopwith_file
  • 您看到的错误表明 Ansible 使用的 Python 版本与您或您的工具所期望的不同。尝试仔细检查正在运行的 Python 解释器(Python 2 与 3)。

标签: json ansible jq


【解决方案1】:

为了更好地理解错误消息The error was: AttributeError: 'dict' object has no attribute 'startswith',您可以查看此示例运行

---
- hosts: localhost
  become: no
  gather_facts: no

  tasks:

  - name: Loop with items
    shell:
      cmd: "echo {{ item }}"
      warn: false
    register: result
    changed_when: false
    failed_when: false
    with_file:
      - "{{ item }}"
    loop:
      - 1
      - 2
      - 3

导致错误The error was: AttributeError: 'int' object has no attribute 'startswith'

由于存在类型不匹配,只需通过以下方式更正它们

loop:
  - "1"
  - "2"
  - "3"

仍然不会导致正确运行。 with_items也一样

  - name: Loop with items
    shell:
      cmd: "echo {{ item }}"
      warn: false
    register: result
    changed_when: false
    failed_when: false
    with_items:
      - "4"
      - "5"
    loop:
      - "1"
      - "2"
      - "3"

根据您的问题产生不是您本意的结果。

TASK [Loop with items] ****
ok: [localhost] => (item=1)
ok: [localhost] => (item=2)
ok: [localhost] => (item=3)

人们可以认为这是一种无声的失败。

关于您的问题

我在我的任务中遗漏了什么? ...如何解决此错误

您可能需要更改任务逻辑中的某些内容。如果以下方法之一满足您的需求,您可以看看。

Stackoverflow 上有更多示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多