使用ansible.builtin.uri调用Databricks API遇Base64编码错误求助
问题:Ansible uri模块调用Databricks DBFS API时出现Base64编码错误
问题背景
原Ansible任务通过shell模块调用curl上传文件到Databricks DBFS,运行正常:
--- - name: Databricks dbfs upload shell: "curl -H 'Authorization: Bearer {{ token }}' \ -F filedata=config-file/application.conf \ -F path=/destpath/on/dbfs/application.conf \ https://<instance_name>.azuredatabricks.net/api/2.0/dbfs/put"
改用ansible.builtin.uri模块后,出现400错误:
{ ... "json": { "error_code": "MALFORMED_REQUEST", "message": "Could not parse request object: Unexpected end of base64-encoded String: base64 variant 'MIME-NO-LINEFEEDS' expects padding (one or more '=' characters) at the end. This Base64Variant might have been incorrectly configured\n at [Source: (ByteArrayInputStream); line: 1, column: 36]\n at [Source: java.io.ByteArrayInputStream@35649c34; line: 1, column: 36]" }, "msg": "Status code was 400 and not [200]: HTTP Error 400: Bad Request" ... }
当前的uri任务代码:
--- - name: Databricks dbfs upload ansible.builtin.uri: url: https://<instance_name>.azuredatabricks.net/api/2.0/dbfs/put method: POST return_content: true headers: Authorization: "Bearer {{ token }}" body_format: json body: contents: config-file/application.conf path: /destpath/on/dbfs/application.conf
已尝试重命名文件、更换Ansible版本、读取外部JSON文件,均未解决。
问题根源
- API参数格式误解:Databricks DBFS Put API的
contents字段(JSON格式请求时)要求传入文件内容的Base64编码字符串,而非本地文件路径。直接传入文件路径会被API当作Base64字符串解析,因格式不合法导致编码错误。 - 请求格式不匹配:原curl命令用
-F参数提交的是multipart/form-data格式表单,API会自动处理文件内容;新任务用body_format: json切换为JSON格式请求,参数规则完全不同。
解决方案
提供两种可行方案,任选其一即可:
方案1:模拟原curl的multipart/form-data上传
保持和原curl一致的请求格式,用form-multipart作为body格式,直接传入文件内容:
--- - name: Databricks dbfs upload (form-data格式) ansible.builtin.uri: url: https://<instance_name>.azuredatabricks.net/api/2.0/dbfs/put method: POST return_content: true headers: Authorization: "Bearer {{ token }}" body_format: form-multipart body: filedata: "{{ lookup('ansible.builtin.file', 'config-file/application.conf') }}" path: /destpath/on/dbfs/application.conf
说明:lookup('ansible.builtin.file')会读取本地文件内容,作为表单字段filedata的值上传,和原curl行为完全一致。
方案2:使用JSON格式并正确Base64编码文件内容
如果坚持用JSON格式请求,需将文件内容读取后进行Base64编码,再传给contents字段:
--- - name: Databricks dbfs upload (JSON格式+Base64编码) ansible.builtin.uri: url: https://<instance_name>.azuredatabricks.net/api/2.0/dbfs/put method: POST return_content: true headers: Authorization: "Bearer {{ token }}" body_format: json body: contents: "{{ lookup('ansible.builtin.file', 'config-file/application.conf') | b64encode }}" path: /destpath/on/dbfs/application.conf
说明:b64encode过滤器会将读取到的文件内容转换为符合要求的Base64字符串,满足API对contents字段的格式要求。
内容的提问来源于stack exchange,提问作者groromain92
相关产品推荐
相关产品推荐

