在ansible中执行curl命令

Execute curl command in ansible

我正在尝试在 ansible 剧本中传递这个 curl 命令:

shell: 'curl -k -u {{ AMBARI_USER }}:{{ AMBARI_PASSWORD }} -H 'X-Requested-By: ambari' -X POST -d '[{"Event": {"specs": [{"principal_type": "users", "sync_type": "all"}, {"principal_type": "groups", "sync_type": "all"}]}}]' https://{{AMBARI_SERVER_HOST}}:8083/api/v1/ldap_sync_events

这是我的 ansible 剧本:

- hosts: adm
  tasks:
    - name: sync ldap
      shell: "curl -k -u {{ AMBARI_USER }}:{{ AMBARI_PASSWORD }} -H 'X-Requested-By: ambari' -X POST -d '[{"Event": {"specs": [{"principal_type": "users", "sync_type": "all"}, {"principal_type": "groups", "sync_type": "all"}]}}]' https://{{AMBARI_SERVER_HOST}}:8083/api/v1/ldap_sync_events"

问题是这个命令有多个双通道和简单通道,所以它不起作用,无论如何要将它传递到这里,或者我应该为它创建一个 shell 脚本? 谢谢

您使用普通 shell 命令而不是 uri 模块有什么原因吗?一般的最佳实践是更喜欢 Ansible 模块。它们已经适合 Ansible(例如变更检测、错误处理),可以节省您的工作,并且在需要时可能会关心安全性。

例如,在您的情况下,它避免了与多个嵌套引号的斗争,因为它抽象了参数而不是进行大量调用。原始 shell 命令仅应在特殊情况下使用,即当 Ansible 模块不适用于该用例时。

像这样的东西应该适合使用 uri 模块的基本请求:

- name: Make an API call
  uri:
    method: POST
    url: "https://{{ AMBARI_SERVER_HOST }}:8083/api/v1/ldap_sync_events"
    url_username: "{{ AMBARI_USER }}"
    url_password: "{{ AMBARI_PASSWORD }}"
    body_format: json
    headers:
      'X-Requested-By': 'ambari'

有几种方法可以传递 JSON 正文:

  • As 字符串,这在这里是可能的,因为您不需要 curl 调用所需的额外引号。 可以使用这样的东西:

    body: '[{"Event": ...'
    
  • 像数组这样的 Ansible 数据结构。 Ansible 会自动将其转换为 JSON,只要将 body_format 设置为相应的类型,如我上面的示例

  • 来自文件。如果 JSON 更大,我更喜欢这个,因为您可以直接将对象粘贴到那里并具有适当的格式,而不会弄乱 Ansible 部分。只需像这样使用 lookup

    body: "{{ lookup('file','api-body.json') }}"
    

只需将所需的 body 属性 添加到 uri。例如,如果你想要一个 json 文件,像这样:

- name: Make an API call
  uri:
    method: POST
    url: "https://{{ AMBARI_SERVER_HOST }}:8083/api/v1/ldap_sync_events"
    url_username: "{{ AMBARI_USER }}"
    url_password: "{{ AMBARI_PASSWORD }}"
    body: "{{ lookup('file','api-body.json') }}"
    body_format: json
    headers:
      'X-Requested-By': 'ambari'
    # If you're interested in the response
    return_content: yes
  register: api_result