How to prepare JSON in Azure Policy - json

In Azure Policy, How to prepare and return the result as following JSON object.
return { Id : 1, prototype: 'skeleton1', status: 'success'}
The value will be dynamically set to JSON data in policy.
When use straight as above JSON string then, its fail and unable to save the policy.

If you need a dynamic data response, then you probably need to look at the set-body policy and liquid templates:
https://blogs.msdn.microsoft.com/apimanagement/2017/09/25/deep-dive-on-set-body-policy/
For static response data, you can also use the set-body policy like this:
<set-body>{
"Id" : 1,
"prototype": "skeleton1",
"status": "success"
}</set-body>
This will result in the required body.

Related

Terraform AWS IAM Role “inline_policy.0.policy” contains an invalid JSON policy using ${file xyz} and jsonencode

Please see below. First, with only the assume role policy, it works. If I remove the inline the policy, it all validates. When left in, (it looks like this.) It does not validate. I am using Terragrunt, but I believe this is a Terraform error.
resource "aws_iam_role" "test_role" {
name = "my_test_role"
assume_role_policy = jsonencode("${file("..//Policies//policy_assume_role.json")}")
inline_policy {
name = "inline_s3_policy"
policy = jsonencode("${file("..//Policies//policy_s3_bucket.json")}")
}
}
Then my policy_s3_bucket.json looks like this
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": ["arn:aws:s3:::company-terragrunt-terraform-state-123456789-us-east-1"]
},
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::company-terragrunt-terraform-state-123456789-us-east-1/*"]
}
]
}
I get - ““inline_policy.0.policy” contains an invalid JSON policy” … but the JSON is valid. My configured user does have access to those buckets. Also, the assume role policy is working without the s3 inline in there. The assume role policy json looks to be the same format, and I’m pulling it in the same fashion.
In your configuration you seem to be passing the result of the file function into the jsonencode function.
The result of the file function is always a string representing the UTF-8-encoded contents of the file, and so if your file contains already-encoded JSON then it will return a string containing JSON.
If you pass a string to jsonencode then it will produce a JSON-formatted string, whereas an IAM policy requires a JSON object, and therefore the API will return an error as shown here.
To be more specific, your current configuration will set policy to something like the following (truncated for brevity):
"{\n \"Version\": \"2012-10-17\"m\n \"Statement\": ..."
If you know that your external file already contains valid JSON then you can assign the result of file directly to the policy argument, like this:
resource "aws_iam_role" "test_role" {
name = "my_test_role"
assume_role_policy = file("${path.module}/../Policies/policy_assume_role.json")
inline_policy {
name = "inline_s3_policy"
policy = file("${path.module}/../Policies/policy_s3_bucket.json")
}
}
If you'd like Terraform to parse the JSON and reencode it -- which will mean that Terraform will check whether the JSON content is valid locally first, and will always generate it in a consistent minified form, you can alternatively pass the file result to jsondecode first, and then pass that result to jsonencode, thereby "round-tripping" through the Terraform language type system and back to JSON again:
resource "aws_iam_role" "test_role" {
name = "my_test_role"
assume_role_policy = jsonencode(jsondecode(file("${path.module}/../Policies/policy_assume_role.json")))
inline_policy {
name = "inline_s3_policy"
policy = jsonencode(jsondecode(file("${path.module}/../Policies/policy_s3_bucket.json")))
}
}
However, this would be a pretty unusual approach and so if you adopt it then I would recommend including a comment explaining why you did it, so that a future reader can understand why this seemingly-redundant transformation is included.

Azure Logic App - Parse JSON with dynamic key/name

just want to know if and how I can parse a HTTP response with a dynamic name in a JSON?
I used the Azure Management API to receive the managed identities (system- and user assigned managed identities) to receive all managed identities.
With a foreach I am iterating the results.
If a resource has a system assigned managed identity and user assigned managed identity, the response looks like this:
{
"principalId": "<principalId1>",
"tenantId": "<tenantId>",
"type": "SystemAssigned, UserAssigned",
"userAssignedIdentities": {
"/subscriptions/<subscriptionId>/resourcegroups/<resourceGroupName>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/<userAssignedIdentitiesName>": {
"principalId": "<principalId2>",
"clientId": "<clientId>"
}
}
}
Now, I would like to get the <principalId2>.
Unfortunately, the Name of the object is dynamic related to the scope of the resource /subscriptions/<subscriptionId>/resourcegroups/<resourceGroupName>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/<userAssignedIdentitiesName>.
How can I parse the JSON to receive the needed <principalId2>?
For all other responses I can easily use the Data operations Parse JSON with the payload I inserted from the HTTP response.
Is there a way to use a wildcard? Otherwise, could I somehow just select the first object of userAssignedIdentities to receive the needed value?
Ok, this should work for you. This is the flow I tested with ...
Initialise JSON
Your JSON as a string, how you do that in your solution may differ slightly.
Initialize XPath Result
Defined as an Array and the expression is ...
xpath(xml(json(concat('{ root: ', replace(variables('JSON'), 'PrincipalId', 'principalId'), '}'))), '(//principalId)[2]')
Initialize Result
A bit more work again but defined as a String and the expression is ...
array(xpath(xml(base64ToString(variables('XPath Result')[0]?['$content'])), '//text()'))[0]
The end result should be your value ...

Django middleware find content type in response

I am looking to write middleware to modify response object that is generated by rest framework - JSON format.
I want to add to each JSON response some so called envelope that would wrap data object to something like:
{
"status" : "success",
"server" : "server name",
"source" : "cache", -- or "database"
"data" : ... original response from API ...
"errors" : [],
ect ....
}
I was thinking about creating middleware that would look for 'application/json' content and if yes capture response wrap it in that object but not react if other types 'application/text'
How I can access to content type in process_response method in middleware ?
And is it proper way to do such tasks ?
Your middleware's process_response method takes two arguments, request and response object.
In the method you can check the content type with response['Content-Type'].

How to Transfer a JSON value from a REST POST Response to a REST Get Request in SOAPUI

I have a REST service which I am testing with SoapUI. The first step in my TestSuite returns the following Response (Json):
{
"mtMessageId": 52003685,
"status":
{
"value": 0,
"code": "OK",
"text": "Text message submitted"
},
"custMessageId": 123,
"custMessageRef": null
}
I want to 'Transfer' the value from the mtMessageId into the HTTP Get Request in the next step.
The request is formatted like "/SMS/{id}"
How do I transfer the value into the Request?
First of all you have to set the resource of your get method in your request with a property for example using /SMS/${#TestCase#id} in order to retrieve it from the first request.
Then add a groovy script testStep between your requests. An use the follow code to get the id from the json response of the first request and set as a property for the second request.
import groovy.json.*
// get the response from the first request using its name
def response = context.expand('${Request 1#Response}')
// parse it
def json = new JsonSlurper().parseText(response)
log.info json.mtMessageId
// get the json value an set it as property in testCase
context.testCase.setPropertyValue("id",json.mtMessageId.toString())
Note that you can use property transfer testStep to get the value from your request and set it as a property, however since SOAPUI converts all to xml I prefer to use a groovy script to work json.
Hope it helps,

Rally JSON I/O error creating a test case result

I am trying to create a test case result using a REST client, but get this error:
"Errors": ["Cannot parse input stream due to I/O error as JSON document: Parse error: expected '{' but saw '\uFFFF' [ chars read = >>>\uFFFF<<< ]"]
I get the same error when the name of the object, testcaseresult is not specified in the request body. Here are the steps to create a test case result using a browser REST client:
a) Generate the authorize key using "GET" method and the following URL:
https://rally1.rallydev.com/slm/webservice/v2.0/security/authorize
This is the response that I get back, with the security token: "123abc..."
{"OperationResult": {"_rallyAPIMajor": "2", "_rallyAPIMinor": "0", "Errors": [], "Warnings": [], "SecurityToken": "abc123..."}}
b) Use "POST" method, and the following URL:
https://rally1.rallydev.com/slm/webservice/v2.0/testcaseresult/create?key=abc123...
notice the security token in the end.
c) here is an example of a request body:
{
"testcaseresult":
{
"Build":"1",
"Tester":"/user/777",
"Date":"2010-09-04T19:56:05.000Z",
"TestCase":"/testcase/1111",
"Verdict":"Pass"
}
}
Only the required fields and the fields you want to set need to be referenced. Notice the outer key/value pair
{
"testcaseresult":{}
}
The fields that point to a full object, like "Tester" (points to User object) and "TestCase" (points to a TestCase object that owns the result) have to be referenced by their ObjectIDs:
"Tester":"/user/777",
"TestCase":"/testcase/1111",