I am trying with ansible to make 2 calls api.
The first one is a GET which have to return a json response and match (or not) with a variable.
The second one is a POST only if the GET match the variable.
- name: check if hostname exist
uri:
url: 'some_url'
headers:
Authorization: 'api-key'
Accept: 'application/json'
method: GET
validate_certs: yes
return_content: yes
body_format: json
register: result
- name: defined the new variable
register: resultmatch
when: "{{ ansible_hostname }} is in result.content"
- name: create the group with the hostname
uri:
url: ""
headers:
Authorization: 'api-key'
Accept: 'application/json'
method: POST
validate_certs: yes
body: "{
'{{ hostname }}': '{{ ansible_hostname }}'
}"
return_content: yes
body_format: json
register: add_secret
when: resultmatch is defined
I expect that the script create a new group when the hostname is setted into the variable.
But it seems that the variable result is not seen as a json content and I have one other problem which is:
name: defined the new variable
^ here
You cannot register without an ansible module. there is no output to be registered here.
- name: defined the new variable
register: resultmatch
when: "{{ ansible_hostname }} is in result.content"
Use as below if you need to define a new variable.
- name: defined the new variable
set_fact:
resultmatch: true
when: "{{ ansible_hostname }} is in result.content"
Related
I am getting this error trying to update a card for my application. Here's a look at the rails server log. The ID is coming back "nil". I can't figure out why. Here is the PATCH update block of code:
function handleEdit(e) {
e.preventDefault()
fetch(`/items/${item.id}`,{
method: "PATCH",
body: JSON.stringify({
item: id,
bottle: bottle,
size: size,
count: count,
}),
headers: {
"Content-Type": "application/json",
},
})
.then(res=>res.json())
.then((updatedItem)=>setItem(updatedItem))
}
Here are all the routes:
resources :items, only: [:index,:show,:update]
get '/me', to: 'couriers#show'
get "/home", to: 'couriers#show'
get '/courier', to: 'couriers#show'
get '/items', to: 'items#index'
get 'items/:id', to: 'items#update'
get '/items/:id', to: 'items#show'
patch '/items/:id', to: 'items#update'
post '/login', to: 'sessions#create'
post '/signupform', to: 'couriers#create'
delete '/logout', to: 'sessions#destroy'
Here is the error log:
Started PATCH "/items/undefined" for 127.0.0.1 at 2022-08-01 19:27:47 -0400
Processing by ItemsController#update as */*
Parameters: {"item"=>nil, "bottle"=>"Glass", "size"=>"400", "count"=>"4", "id"=>"undefined"}
Item Load (0.2ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT $2 [["id", nil], ["LIMIT", 1]]
↳ app/controllers/items_controller.rb:19:in `update'
Completed 404 Not Found in 4ms (Views: 0.2ms | ActiveRecord: 0.9ms | Allocations: 1234)
Here is the code in the ItemsController:
class ItemsController < ApplicationController
skip_before_action :authorize, except: :index
def index
items = Item.all
render json: items, status: :ok
end
def show
item=Item.find_by(id:session[:id])
if item
render json: item
else
render json: {error: 'Not Found'}, status: :not_found
end
end
def update
item = Item.find_by(id:params[:id])
if item
item.update(item_params)
render json: item
else
render json: { error: "Item not found" }, status: :not_found
end
end
private
def item_params
params.permit(:id,:item,:bottle, :size, :count)
end
end
If anyone has an idea or resolution, please share. I'm sure it's something I may be doing wrong, so anything helps.
Not super sure how React apps work, but should that ${items.id} in the patch code be ${item.id} (singular)?
Out of curiosity, where is the item (or items) var actually set? Again, I'm not familiar with React, but that's the source of the 'undefined' text being passed to the controller. Whatever is rendered in the ${ } section is undefined. It is being turned into the literal text 'undefined' and that is being sent to your controller.
Cannot seem to access the image link received in JSON from the below api call, gives me a status 403 forbidden error.
var axios = require('axios').default;
var options = {
method: 'POST',
url: 'someURL',
headers: {"someKey":"someValue"},
data: {"somekey":"someValue"}
};
axios.request(options).then((response)=>{
console.log(response);
this.setState({data:response.data.userListDetails})
}).catch(function(error){
console.error(error);
});
JSON received back, StudentPhoto is where the link to the image is :-
AcademicYear: ""
Board: "`Board Name"
ClassTeacher: ""
CurrentDateTime: "Date"
Division: ""
Last_Login: "Date"
Name: "Name"
OrganizationId: "2"
RoleId: "6"
SchoolId: "40"
SchoolLogo: ""
SchoolName: "School Name"
ShiftName: ""
Standard: ""
StudentEmail: "email"
StudentId: ""
StudentPhoto: ""
StudentUniqueId: ""
UserId: ""
poppup_flag: 0
poppup_imgurl: ""
For privacy reasons I could not put in the exact values!
Code 403 means the server understood the request but refuses to authorize it. Maybe you're using the wrong method, like using POST instead of GET, or you might need to send some authorization with your request. If your response includes a payload it might state a reason why you're getting a 403.
Can you access the file's URL through your regular browser? Do you need to be logged in to view the image? Would it be easier to store the images on your own server?
I'm trying to build a configuration file dynamically with Ansible, using a Jinja2 template.
In Ansible, I've defined a role in which I have the template and the set of variables.
I want my output file to look like this :
models:
model1:
username: user1
password: password1
model2:
username: user2
password: password2
I have defined my variables like so :
model_list:
name:
- model1
- model2
user:
- user1
- user2
pass:
- password1
- password2
My .j2 template :
{% for model in vars[model_list] %}
{{ model.name }}
username: {{ model.user }}
password: {{ model.pass }}
{% endfor %}
My playbook is quite simple :
- name: Building config file
template:
src: ./config.j2
dest: my/path/config
When I run the playbook I've got the following error :
fatal: [FRADEV048]: FAILED! => {"changed": false, "msg":
"AnsibleUndefinedVariable: dict object has no element {u'user':
u'user1', u'name': u'model1', u'pass': u'password1'}"}
I'm quite new in programming so I don't really see where my error is ... Any clues ?
Thanks in advance for your help,
Simon
Template content
models:
{% for model in model_list.name %}
{{ model }}:
username: {{ model_list.user[loop.index0] }}
password: {{ model_list.pass[loop.index0] }}
{% endfor %}
Reference: https://stackoverflow.com/a/24959173/5439195
Here i wrote simple code for saving data into api when i user data: $httpParamSerializerJQLike(savingdata) is Binding data into server side but when i use data: JSON.stringify(savingdata) its not Binding at server side what is the reason
this.saveEmp = function (savingdata) {
var sersave = $http({
url: Privateurl2 + 'SaveEmpData',
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded ;charset=utf-8'
},
// data: $httpParamSerializerJQLike(savingdata),
data: JSON.stringify(savingdata),
})
return sersave;
}
You ask
what is Difference between $httpParamSerializerJQLike and json.stringify
The answer is simple. The former produces a string in form-url-encoded format, the latter JSON. To illustrate...
const savingdata = {
foo: 'abc',
bar: 123,
baz: ['A', 'B']
}
$httpParamSerializerJQLike(savingdata)
// <- foo=abc&bar=123&baz%5B%5D=A&baz%5B%5D=B
JSON.stringify(savingdata)
// <- {"foo":"abc","bar":123,"baz":["A","B"]}
As for why one works with your server and the other does not; you are setting the request Content-type to application/x-www-form-urlencoded. If you attempt to send a JSON formatted request body, your server will fail to decode it because it does not match the format you specified.
Your server may be able to handle a JSON request payload (if it has been coded / configured to do so) in which case you can simply use the AngularJS defaults and use
return $http.post(Privateurl2 + 'SaveEmpData', savingdata)
This will set the Content-type to application/json and will use JSON.stringify to serialize the request payload.
If your server is not set up to handle requests in this format, the operation will obviously fail.
I am very frustrated and could not find the soloution:
I am creating a project using angularjs and nodejs.I get image data from angular side in node js and send this data to further api.I got error
{
"error": {
"detail": "Multipart form parse error - Invalid boundary in multipart: None"
}
}
here is my code in nodejs side:
var request = require('request');
console.log(req.files);
var data = {
website:'www.gamail.xom',
contact_number:'dsdsd',
services_offered:'dsadasd',
contact_name:'dasdas',
provider_category:'exchange',
email:'kk#gmail.com',
image:req.files
}
var api_url = global.common.base_url + 'vcard/1.0.0/visit_card/' + req.param('uuid') +'/';
request({
url: api_url,
method: 'PUT',
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer '+req.cookies.apitoken
},
json: data
}, function(error, response, body) {
if(response.statusCode == 200 && !error){
res.end(JSON.stringify(body));
}else{
res.send(response.statusCode, { error: body });
}
});
}
In req.files i get
{ image:
[ { fieldName: 'image[0]',
originalFilename: 'icon_dd_chart_grey.png',
path: 'C:\\Users\\karakuma\\AppData\\Local\\Temp\\op74_gLSzPs-_49aT1GF0si
7.png',
headers: [Object],
size: 1474,
name: 'icon_dd_chart_grey.png',
type: 'image/png' } ] }
Try defining the content type as follows.
content_type='multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
I was facing the same issue and it worked for me in python.
I also faced this issue while trying to upload file. For me the issue was the FormData, which was coming as Object instead of FormData instance
So i converted my object to FormData using below code:
const getFormData = object => Object.keys(object).reduce((formData, key) => {
formData.append(key, object[key]);
return formData;
}, new FormData());
And the just executed my post request, in my case using Vue resource:
return Vue.http.post(url,
getFormData(formData),
{
headers: {
'Content-Type': 'multipart/form-data'
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
There is no need to mention the content type in header, fetch() will detect it's content type by itself.
let formData = new FormData()
formData.append("email", email);
formData.append("password", password);
formData.append("image", image);
const response = await fetch('http://localhost:8000/api/authentication/register/', {
method: 'POST',
headers: {'X-CSRFToken': csrftoken}, //django specific
body: formData,
});
I have been facing this problem in angular 11 connected to Django rest API, I was able to curl with something like this in order to upload a JSON with a form:
curl -X POST -S \
-H 'Accept: application/json' \
-u "user:password" \
-F "name=name" \
-F "label=mylabel" \
-F "otherfields=something" \
-F "photo=#./example.png;type=image/png" \
http://127.0.0.1:8000/api/v1/item/
But I was getting that exception using my header as httpOptions:
'content-type': 'multipart/form-data',
So I just commented out the content-type and it seems angular is so clever that he creates the header for you and will set the multipart together with the boundaries.
For more information on this:
What is the boundary in multipart/form-data?
A boundary is just the 'key' to separate the multiple "parts" of a multipart payload. Normally something like '&' is enough to separate the variables but you need something more unique to separate the payloads within the payload comment
You can use any value that not occurs in the data sent.
NOTE: Because boundary delimiters must not appear in the body parts being encapsulated, a user agent must exercise care to choose a unique boundary parameter value.
The simplest boundary delimiter line possible is something like "---", with a closing boundary delimiter line of "-----".