I am trying to convert the following curl to ansible play:
curl -u user:password -v -X POST -d #restrictions.json -H
"Content-Type: application/vnd.atl.bitbucket.bulk+json"
http://BitBucketServer/rest/branch-permissions/2.0/projects/project/repos/my-repo/restrictions
Ansible play:
- name: Branch permission
uri:
url: http://172.28.200.66:7990/rest/branch-permissions/2.0/projects/V10/repos/my-repo/restrictions
method: POST
user: "{{username}}"
password: "{{password}}"
src: restrictions.json
force_basic_auth: yes
status_code: 400
body_format: json
It is failing with the following error:
"errors": [{
"context": null,
"exceptionName": "org.codehaus.jackson.map.JsonMappingException",
"message": "Can not deserialize instance of com.atlassian.stash.internal.repository.ref.restriction.rest.RestRestrictionRequest out of START_ARRAY token\n at [Source: com.atlassian.stash.internal.web.util.web.CountingServletInputStream#3ab1a43; line: 1, column: 1]"
}]
}, "msg": "HTTP Error 400: Bad Request",
I solved the issue by adding:
headers:
Content-Type: "application/vnd.atl.bitbucket.bulk+json"
Related
while I am trying to tell Ansible to use this curl
curl --location --request POST 'https://34.107.103.175:3009/rest/v1.0/auth' \
--header 'Content-Type: application/json' \
--data-raw '{
"username": "sysadmin",
"password": "8529834022607504819"
}'
This will return a -DD-AUTH-TOKEN in the header but I am failing to tell the ReST endpoint the json Body
{
"username": "sysadmin",
"password": "{{DD-Old_Password}}"
}
My ansible approach
vars:
DDVE_public_IP: 34.107.103.175
destination_port: 3009
Instance_id: 8529834022607504819
S3_bucket_name: bucket_for_ddve_6
tasks:
- name: login access token
uri:
validate_certs: false
url: https://{{ DDVE_public_IP }}:{{ destination_port }}/{{ resource_path }}
method: POST
headers:
Content-Type: application/json
body:
username: sysadmin
password: 8529834022607504819
body_format: json
return_content: true
register: rest_post
vars:
resource_path: rest/v1.0/auth
is failing with
TASK [login access token] *********************************************************************************************************************************
fatal: [localhost]: FAILED! => {"access_control_allow_credentials": "true", "access_control_expose_headers": "AUTHORIZATION, X-DD-AUTH-TOKEN, X-DD-JSON-RESPONSE-WITH-ROOT, X-DD-PEER-USERNAME", "cache_control": "no-cache", "changed": false, "content": "{\"details\": \"**** Value of \\\"password\\\" is empty.\", \"code\": 5437}", "content_length": "65", "content_type": "application/json", "elapsed": 0, "json": {"code": 5437, "details": "**** Value of \"password\" is empty."}, "msg": "Status code was 400 and not [200]: HTTP Error 400: Bad Request", "redirected": false, "server": "Data Domain OS", "status": 400, "url": "https://34.107.103.175:3009/rest/v1.0/auth", "x_dd_auth_token": "", "x_dd_uuid": "857cd83f41d01670:68e24c1d986399ff"}
PLAY RECAP ************************************************************************************************************************************************
localhost : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
Why does it show this?
I would guess the upstream service is failing due to a type error. YAML coerces [0-9]+ into a formal int scalar; so if your password is entirely digits but should be transmitted as a str, you'll need to explicitly quote it:
body:
username: sysadmin
password: '8529834022607504819'
if you would prefer to use the var, you'll need to similarly "cast" it because the var is also an int for the same YAML coercion reason:
body:
username: sysadmin
password: "{{ Instance_id | string }}"
(be aware that the " in that example is merely protecting the jinja2 mustaches, and doesn't have anything to do with the type of the inner variable)
I've a problem with URI module from ansible, maybe someone have an idea what the problem could be?
I try to communicate with I-Doit API (JSON-RPC) by using ansible uri module. My first attempt with curl works fine, whether I try to run curl manually or by using ansible.
# curl manual example
curl --location --request POST 'https://SERVER-FQDN/i-doit/src/jsonrpc.php' \
--header 'Content-Type: application/json' \
--header 'X-RPC-Auth-Session: SESSION-KEY' \
--header 'Cookie: PHPSESSID=SESSION-KEY' \
--data-raw '{
"version": "2.0",
"method": "idoit.version",
"params": {
"apikey": "API-KEY",
"language": "en"
},
"id": 1
}'
# example in ansible
---
- name: CURL REST / JSON-RPC API Call
shell: |
curl -s --noproxy "*" --location --request POST 'https://SERVER-FQDN/i-doit/src/jsonrpc.php' \
--header "Content-Type: application/json" \
--header "X-RPC-Auth-Session: {{ session_key }}" \
--header "Cookie: PHPSESSID= {{ session_key }}" \
--data-raw '{
"version": "2.0",
"method": "idoit.version",
"params": {
"apikey": "{{ api_key }}",
"language": "en"
},
"id": 1
}'
If I try to reproduce the call with the URI module like
- name: REST / JSON-RPC API Call check I-Doit Version
uri:
url: "https://SERVER-FQDN/i-doit/src/jsonrpc.php"
method: post
validate_certs: no
follow_redirects: all
use_proxy: no
timeout: 200
headers:
X-RPC-Auth-Session: "{{ SESSION-KEY }}"
Content-Type: "application/json"
body_format: json
return_content: yes
body: "{{ lookup('file','test.json') }}"
ignore_errors: yes
# test.json content
{
"version": "2.0",
"method": "idoit.version",
"params": {
"apikey": "API-KEY",
"language": "en"
},
"id": 1
}
the request failed with error code -1 and message: "Connection failure: connection was closed before a valid response was received: No status line received - the server has closed the connection"
Is there a difference in usage by URI modul with rest or json-rpc?
thanks for help or ideas
dantegabriel
I am making a request to publish a plugin to on vmware with the ansible uri module:
- name: Enable the App Launchpad plugin if it is set
uri:
url: "https://{{ URL }}/cloudapi/extensions/ui/{{ plugin_id }}/tenants/publish"
method: "POST"
status_code: 200
body_format: json
return_content: yes
body:
- name: "{{ org_name }}"
id: "{{ org_uuid }}"
headers:
Authorization: "{{ vdc_token }}"
However I am getting a fatal error:
fatal: [localhost]: FAILED! => {"changed": false, "content": "", "elapsed": 0,
"msg": "Status code was -1 and not [200]: An unknown error occurred: got more than 100 headers",
"redirected": false, "status": -1,
"url": ".../cloudapi/extensions/ui/urn:vcloud:uiPlugin:b92bf.../tenants/publish"}
When I make a request diretly without ansible it works but it does have over 100 headers...
I do not have control of the amount of headers returned, so what can I do form the ansible playbook side?
I am trying to automate the Remedy - Incident Management Ticket creation using Ansible. For this, I am trying to connect to the Remedy API, but I am getting the below error.
Code:
-
name: Testing GET Method
hosts: localhost
tasks:
- name: Create a Incident Ticket
uri:
url: https://testapi.xyz.com/t/app.misc/remedyLogin/1.0/login
method: POST
headers:
"Authorization": "Bearer xxxxx-xxxxxx-xxxxxxxxx-xxxxx"
"Content-Type": "application/x-www-form-urlencoded"
body: '{"username": "some_username", "password": "some_password"}'
validate_certs: False
force_basic_auth: yes
return_content: yes
status_code: 200
register: result
- debug: msg="{{ result.status }}"
To be more precise. My Remedy needs username and password along with Access Token, for that I have added Authorization in the headers section. I may be wrong adding authorization.
Error:
fatal: [localhost]: FAILED! => {
"access_control_allow_headers": "authorization,Access-Control-Allow-Origin,Content-Type,SOAPAction",
"access_control_allow_methods": "POST",
"access_control_allow_origin": "*",
"cache_control": "must-revalidate,no-cache,no-store",
"changed": false,
"connection": "close",
"content": "<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html;charset=ISO-8859-1\"/>\n<title>Error 500 </title>\n</head>\n<body>\n<h2>HTTP ERROR: 500</h2>\n<p>Problem accessing /api/jwt/login. Reason:\n<pre> Request failed.</pre></p>\n<hr />\n</body>\n</html>\n",
"content_security_policy": "frame-ancestors 'self'",
"content_type": "text/html;charset=iso-8859-1",
"date": "Tue, 14 Apr 2020 11:17:07 GMT",
"msg": "Status code was 500 and not [200]: HTTP Error 500: Request failed.",
"redirected": false,
"status": 500,
"transfer_encoding": "chunked",
"url": "https://testapi.xyz.com/t/app.misc/remedyLogin/1.0/login",
"x_frame_options": "SAMEORIGIN"
}
Please help me on this.
you need to add body_format parameter to uri module
Example:
- name: Create a Incident Ticket
uri:
url: https://testapi.xyz.com/t/app.misc/remedyLogin/1.0/login
method: POST
headers:
"Authorization": "Bearer xxxxx-xxxxxx-xxxxxxxxx-xxxxx"
"Content-Type": "application/x-www-form-urlencoded"
body: '{"username": "some_username", "password": "some_password"}'
body_format: form-urlencoded
validate_certs: False
force_basic_auth: yes
return_content: yes
status_code: 200
register: result
I have problem with ansible j2 template when i run this task
I use this task for create grafana datasource
- name: Get certifacete
slurp:
src: /var/lib/cloudera-scm-server/certmanager/CMCA/ca-db/newcerts/00.pem
register: cert
- name: test
uri:
url: https://127.0.0.1:3000/api/datasources
method: POST
validate_certs: no
force_basic_auth: yes
user: "{{ grafana_admin_user }}"
password: "{{ grafana_admin_password }}"
body: "{{ lookup('template', 'test_template.j2') }}"
body_format: json
headers:
Content-Type: "application/json"
template
{
"name": "Cloudera Manager",
"type": "foursquare-clouderamanager-datasource",
"url":"https://{{ hostvars[groups['tag_Group_cm'][0]]['ec2_private_ip_address'] }}:7183",
"access":"proxy",
"isDefault":false,
"basicauth":true,
"basicAuthUser":"{{ managerUser }}",
"basicAuthPassword":"{{ managerPassword }}",
"jsonData": {
"cmAPIVersion":"{{ cmapi }}",
"tlsAuthWithCACert": true},
"secureJsonData":{
"tlsCACert": "{{ cert['content'] | b64decode | string }}"
},
"database": "foursquare-clouderamanager-datasource"}
I got this error when I use this template with variable
fatal: [10.0.1.31]: FAILED! => {"cache_control": "no-cache", "changed": false, "connection": "close", "content": "[{\"classification\":\"DeserializationError\",\"message\":\"invalid character '\\\\\\\\' looking for beginning of object key string\"},{\"fieldNames\":[\"Name\"],\"classification\":\"RequiredError\",\"message\":\"Required\"},{\"fieldNames\":[\"Type\"],\"classification\":\"RequiredError\",\"message\":\"Required\"},{\"fieldNames\":[\"Access\"],\"classification\":\"RequiredError\",\"message\":\"Required\"}]", "content_length": "359", "content_type": "application/json; charset=utf-8", "date": "Thu, 14 Nov 2019 10:48:45 GMT", "elapsed": 0, "expires": "-1", "json": [{"classification": "DeserializationError", "message": "invalid character '\\\n' looking for beginning of object key string"}, {"classification": "RequiredError", "fieldNames": ["Name"], "message": "Required"}, {"classification": "RequiredError", "fieldNames": ["Type"], "message": "Required"}, {"classification": "RequiredError", "fieldNames": ["Access"], "message": "Required"}], "msg": "Status code was 400 and not [200]: HTTP Error 400: Bad Request", "pragma": "no-cache", "redirected": false, "status": 400, "strict_transport_security": "max-age=86400; preload", "url": "https://127.0.0.1:3000/api/datasources", "x_frame_options": "deny", "x_xss_protection": "1; mode=block"}
When i use template without variable works fine
example debug output without variable:
"body": {
"access": "proxy",
"basicAuthPassword": "passs",
"basicAuthUser": "user",
"basicauth": true,
"database": "foursquare-clouderamanager-datasource",
"isDefault": false,
"jsonData": {
"cmAPIVersion": "v4-5",
"tlsAuthWithCACert": true
},
"name": "Cloudera Manager",
"secureJsonData": {
"tls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Q8B\nAf8EBAMCAgQwDQYJKoZIhvcNAQELBQADggGBAHykOktg6mWPwAXh5RyCKLv+2bVQ\nrtAy4JkTiAsroURm+sdYqQ7KD61vfFI7V1twytOmohfbtJ/4qhcGrh1w1s7yv/a0\nbm7fcG7qViX3QoMaVrgs1wkUQC2JNcT9vPFjHcKA/YtvHVcoYYTPVvr+jS6sbh9e\nvTMu14klVyaqRlPsF30I+xjzCLgZoO7eXCuNV9Lu4zTNWIap6jPKOu8QEXWweUza\nhmn4GyKmrT+1mLhXMqh4U7B2GZdVo9/iY/xcHlVp7UhfOqx1K0OetPn/x+entBR5\nH1uBXU1Yx7tSZ/RN192Af6czMw+THXBh0LgzzJgBIIKdjyy5acLBfh7bnV6PV6G+\nnWWyr4WVrrH4wH3pKisCnIoPpsjEXPSJRnu4PTVELM71l8hZlES9dazRPiMOaxOj\nTfaz1vGa1mDPMbobiN5NH0ueX4LAUDMkpWFuAP+AJ9UqAax+Cq0KX+dUMXqyWY82\nV7jPmgHqYTNRw/zvfdOP1qeqhkIeTp8vPbp3lw==\n-----END CERTIFICATE-----\n"
},
"type": "foursquare-clouderamanager-datasource",
"url": "https://127.0.0.1:7183"
}
Example debug output with variable:
"body": "{\n\"name\": \"Cloudera Manager\",\n\"type\": \"foursquare-clouderamanager-datasource\",\n\"url\":\"https://127.0.0.1:7183\",\n\"access\":\"proxy\",\n\"isDefault\":false,\n\"basicauth\":true,\n\"basicAuthUser\":\"user\",\n\"basicAuthPassword\":\"pass\",\n\"jsonData\": {\n\"cmAPIVersion\":\"v4-5\",\n\"tlsAuthWithCACert\": true},\n\"secureJsonData\":{\n \"tlsCACert\": \"-----BEGIN CERTIFICATE-----\nMIIEmDCCAwCgAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJVUzEL\nMAkGA1UECAwCQ0ExQTA/BgNVBAMMOFNDTSBMb2NhbCBDQSBvbiBkZXBsb3ltZW50\nIGFicnluZHphLWRldi1kZXZsaWdodC1tYW5h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vr+jS6sbh9e\nvTMu14klVyaqRlPsF30I+xjzCLgZoO7eXCuNV9Lu4zTNWIap6jPKOu8QEXWweUza\nhmn4GyKmrT+1mLhXMqh4U7B2GZdVo9/iY/xcHlVp7UhfOqx1K0OetPn/x+entBR5\nH1uBXU1Yx7tSZ/RN192Af6czMw+THXBh0LgzzJgBIIKdjyy5acLBfh7bnV6PV6G+\nnWWyr4WVrrH4wH3pKisCnIoPpsjEXPSJRnu4PTVELM71l8hZlES9dazRPiMOaxOj\nTfaz1vGa1mDPMbobiN5NH0ueX4LAUDMkpWFuAP+AJ9UqAax+Cq0KX+dUMXqyWY82\nV7jPmgHqYTNRw/zvfdOP1qeqhkIeTp8vPbp3lw==\n-----END CERTIFICATE-----\n\"\n},\n\"database\": \"foursquare-clouderamanager-datasource\"}"
I think maybe I have problem in this string "tlsCACert": "{{ cert['content'] | b64decode | string }}" but i don`t have any idea how to solve this problem
The problem is that you are using string templating to compose a structured document (in this case JSON); jinja2 does not know it is JSON, only that it is text. You would receive a similar error if you were to try and template {"hello": "{{ world | string }}" using a variable of world="abc\ndef" because the \n in the string is literally inserted in the mustaches, but JSON does not allow newlines in string literals.
You have two paths forward: either ensure the rendering is JSON safe with | to_json instead of | string, or compose the body as an actual dict so that uri: will serialize it correctly
I suspected that is what was happening, but I confirmed it the same way you can: echo that {"body": "{\n\"name\": \"Cloudera Mana... string through jq -r .body (or python -c "import sys, json;print(json.load(sys.stdin)['body'])" if you don't have jq handy) and you will see that tlsCACert has newlines in it