Ime*_*tor 4 shell curl ansible ambari
我正在尝试在ansible playbook中传递这个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
Run Code Online (Sandbox Code Playgroud)
这是我的 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"
Run Code Online (Sandbox Code Playgroud)
问题是这个命令有多个 double 和 simple cotes,所以它不起作用,有没有办法在这里传递它或者我应该为它创建一个 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'
Run Code Online (Sandbox Code Playgroud)
有多种方法可以传递 JSON 主体:
作为字符串,这在这里是可能的,因为您不需要调用所需的额外引号curl
。可以使用这样的东西:
body: '[{"Event": ...'
Run Code Online (Sandbox Code Playgroud)Ansible 数据结构,如数组。Ansible 会自动将其转换为 JSON,只要body_format
设置为相应的类型(如我上面的示例中的情况)
来自一个文件。如果 JSON 较大,我更喜欢这样做,因为您可以直接将对象粘贴到那里并具有正确的格式,而不会弄乱 Ansible 部分。lookup
只需像这样使用:
body: "{{ lookup('file','api-body.json') }}"
Run Code Online (Sandbox Code Playgroud)只需将所需的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
Run Code Online (Sandbox Code Playgroud)