在mongo的适用剧本中rs.add()有问题

时间:2019-08-06 15:44:50

标签: mongodb ansible

我正在剧本中使用以下任务来初始化集群并将辅助添加到主要:

- name: Initialize replica set
  run_once: true
  delegate_to: host1
  shell: >
       mongo --eval 'printjson(rs.initiate())'

- name: Format secondaries
  run_once: true
  local_action:
     module: debug
     msg: '"{{ item }}:27017"'
  with_items: ['host2', 'host3']
  register: secondaries

- name: Add secondaries
  run_once: true
  delegate_to: host1
  shell: >
        /usr/bin/mongo --eval 'printjson(rs.add({{ item.msg }}))'
  with_items: secondaries.results



我遇到以下错误:

TASK [mongodb-setup : Add secondaries] *******************************
fatal: [host1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'msg'\n\nThe error appears to have been in '/var/lib/awx/projects/_dev/roles/mongodb-setup/tasks/users.yml': line 15, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Add secondaries\n  ^ here\n"}

感谢您的答复,我对代码进行了如下修改


-  name: Add secondaries
   run_once: true
   delegate_to: host-1
   shell: >
        /usr/bin/mongo --eval 'printjson(rs.add({{ item }}:27017))'
   with_items:
    - host2
    - host3

但是低于错误

failed: [host-2 -> host-1] (item=host-2) => {"changed": true, "cmd": "/usr/bin/mongo --eval 'printjson(rs.add(host-2:27017))'", "delta": "0:00:00.173077", "end": "2019-08-06 13:29:09.422560", "item": "host-2", "msg": "non-zero return code", "rc": 252, "start": "2019-08-06 13:29:09.249483", "stderr": "", "stderr_lines": [], "stdout": "MongoDB shell version: 3.2.22\nconnecting to: test\n2019-08-06T13:29:09.419-0500 E QUERY [thread1] SyntaxError: missing ) after argument list @(shell eval):1:37", "stdout_lines": ["MongoDB shell version: 3.2.22", "connecting to: test", "2019-08-06T13:29:09.419-0500 E QUERY [thread1] SyntaxError: missing ) after argument list @(shell eval):1:37"]}

1 个答案:

答案 0 :(得分:1)

您发布的不是rs.add(),而是循环的数据。在上一个任务中,项目列表是一个字符串。

# Wrong #
with_items: secondaries.results

您想通过以前的注册结果传递实际列表:

with_items: "{{ secondaries.results }}"

话虽这么说,注册调试任务的结果还是很奇怪的。您应该使用set_fact在var中注册所需的内容,或者最好直接在任务中循环其他主机列表。它也看起来像rs.add funcion is exepecting a string,因此您应该在评估中引用该参数。像这样:

- name: Add secondaries
  shell: >
    /usr/bin/mongo --eval 'printjson(rs.add("{{ item }}:27017"))'
  with_items:
    - host2
    - host3

在这种情况下,使用委派的方式对我来说似乎很陌生,但是如果没有完整的剧本示例来说明您想做什么,很难给出任何有效的线索(必要时可以提出一个新的问题)。