Unable to extract specific value from Azure Key vault Secret using az keyvault secret show command - azure-cli

I am new to AzureCLI script. I request some guidance here:
Please find the secret(masked value) from my Azure key vault.
{
"**attributes**": {
"created": "2021-10-23T04:26:19+00:00",
"enabled": true,
"id": "https://app-kv-axderfctt.vault.azure.net/secrets/connectionstr/cbcncbc",
"name": "connectionstr",
"**value**": "\"{\\\"eventHubNameSpace\\\":\\\"Pji-11111111-132d-46f7-af0f-aq1234\\\",\\\"eventHubName\\\":\\\"pipeline-swswsw-fb95-4e16-8364-oiu8ikji\\\",\\\"**ConnectionString**\\\":\\\"Endpoint=sb://pji-uit8tihj-132d-46f7-af0f-89897899.servicebus.windows.net/;SharedAccessKeyName=343456-ddddd-4720-b3db-oi89087;SharedAccessKey=xxxx+xxxxxxxx=;EntityPath=pipeline-ttrgfrtyh-fb95-4e16-8364-897uy678i\\\"}\""
I am able to get the complete value but not the specific property(ConnectionString) using below command
CONNECTION_STRING=$(az keyvault secret show --vault-name ${{ parameters.KeyVault }} --name ${{ parameters.SecretName}}--query 'value.ConnectionString')
echo "$CONNECTION_STRING"
I get below error:
ERROR: incorrect usage: [Required] --value VALUE | --file PATH
Please advise on how to extract ConnectionString value excluding EntityPath by escaping slashes \\\.
Thanks in advance.

I resolved this issue using jq library
task: Bash#3
displayName: "Parse WarmRepo Connection String"
inputs:
targetType: 'inline'
script: |
# Parse WarmRepo Connection String
echo 'Parse WarmRepo Connection String'
#Refer https://stedolan.github.io/jq/ to know about jq queries
PipelineConnectionString=`jq -r '.ConnectionString' <<<'$(${{ parameters.StreamingPipelineName }}-EventHub-connectionString)'`

Related

Loganalytics workspace ID parameter template

I tried to create a container group and want to push those container logs in Loganalytics.
apiVersion: 2019-12-01
location: eastus2
name: mycontainergroup003
properties:
containers:
- name: mycontainer003
properties:
environmentVariables: []
image: fluent/fluentd
ports: []
resources:
requests:
cpu: 1.0
memoryInGB: 1.5
osType: Linux
restartPolicy: Always
diagnostics:
logAnalytics:
workspaceId: /subscriptions/f446b796-978f-4fa0-8462-......../resourcegroups/v_deployment-docker_us/providers/microsoft.operationalinsights/workspaces/deployment-docker-logs
workspaceKey: nEZSOUGe1huaCksRB2ahsFz/ibcaQr3WPdAHiLc............
tags: null
type: Microsoft.ContainerInstance/containerGroups
Now whenever I try to run :
az container create --resource-group rg-deployment-docker --name mycontainergroup003 --file .\azure-deploy-aci.yaml
then I would get the error as :
(InvalidLogAnalyticsWorkspaceId) The log analytics setting is invalid. WorkspaceId contains invalid character, e.g. '/', '.', etc.
Code: InvalidLogAnalyticsWorkspaceId
Message: The log analytics setting is invalid. WorkspaceId contains invalid character, e.g. '/', '.', etc.
Now I wish to create such parameter type with the help of parameter json file as mentioned in the URL:
https://learn.microsoft.com/en-us/azure/azure-monitor/logs/resource-manager-workspace
{
"$schema": "https://schema.management.azure.com/schemas/2019-08-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"workspaceId": {
"type": "string"
}
},
}
Now I would run the below command:
az container create --resource-group rg-deployment-docker --name mycontainergroup003 --file .\azure-deploy-aci.yaml --parameters parameters.json
but getting the error as :
unrecognized arguments: --parameters parameters.json
It seems such arguments are invalid with az container create command. Can someone please suggest an alternate.
You need to pass the log analytics workspace GUID instead of passing the entire ResourceId in your Yaml file and also As per the documentation az container create cmdlet doesn't have any parameter to pass --parameterflag.
Post making the above changes, i am able to deploy the container without any issues.
Here is the sample screenshot output for reference:

Get data from post request with Rundeck webhook plugin

I am trying to get data with rundeck webhook plugin, and for this i am usig curl command:
curl -X POST -d '{"name":"John", "age":30, "car":null}' https://rundeck_server/api/12/webhook/QSxTDYd08dcYxKh1R5YJNOPQvmSJH2Z8#Netbox_Job
In rundeck webhook plugin options i add those 2 variables, 'whkpayload' to get all the json data and 'name' to get the name only (must return John in this example):
-whkpayload ${raw} -name ${data.name}
And finally i show them with those lines:
echo #option.whkpayload#
echo #option.name#
I get an empty result and i can't figure out why. Any one may help me please ?
Following this, you need to use an option called whkpayload in your job, and set it as ${raw} in the webhook configuration.
I made an example:
The job definition in YAML format (with the whkpayload option):
- defaultTab: nodes
description: ''
executionEnabled: true
id: 0fcfca07-02f6-4583-a3eb-0002276bdf2d
loglevel: INFO
name: HelloWorld
nodeFilterEditable: false
options:
- name: age
- name: car
- name: name
- name: whkpayload
plugins:
ExecutionLifecycle: null
scheduleEnabled: true
sequence:
commands:
- description: command step
exec: echo "name ${option.name} - age ${option.age} - car ${option.car} - payload
${option.whkpayload}"
- description: inline-script step
fileExtension: .sh
interpreterArgsQuoted: false
script: echo "name #option.name# - age #option.age# - car #option.car# - payload
#option.whkpayload#"
scriptInterpreter: /bin/bash
keepgoing: false
strategy: node-first
uuid: 0fcfca07-02f6-4583-a3eb-0002276bdf2d
The webhook configuration.
The webhook calling from cURL:
curl -H "Content-Type: application/json" -X POST -d '{"field1":"John", "field2":30, "field3":"chevy"}' http://localhost:4440/api/40/webhook/0vBZjWWrnXWvqENEdxkn0JRvjn5R63J0#MyWebhook
The result.

How can I pass Rundeck variables to a JSON file?

I have a JSON with key pairs and I want to access the values from Rundeck Options dynamically during the job execution.
For shell script, we can do a $RD_OPTIONS_<>.
Similarly is there some format I can use in a JSON file?
Just use #option.myoption# in a inline-script step.
You need a tool to use on an inline script step to manipulate JSON files on Rundeck. I made an example using JQ. Alternatively, you can use bash script-fu to reach the same goal.
For example, using this JSON file:
{
"books": [{
"fear_of_the_dark": {
"author": "John Doe",
"genre": "Mistery"
}
}]
}
Update the file with the following jq call:
To test directly in your terminal
jq '.books[].fear_of_the_dark += { "ISBN" : "9999" }' myjson.json
On Rundeck Inline-script
echo "$(jq ''.books[].fear_of_the_dark += { "ISBN" : "#option.isbn#" }'' myjson.json)" > myjson.json
Check how looks on an inline-script job (check here to know how to import the job definition to your Rundeck instance).
- defaultTab: nodes
description: ''
executionEnabled: true
id: d8f1c0e7-a7c6-43d4-91d9-25331cc06560
loglevel: INFO
name: JQTest
nodeFilterEditable: false
options:
- label: isbn number
name: isbn
required: true
plugins:
ExecutionLifecycle: null
scheduleEnabled: true
sequence:
commands:
- description: original file content
exec: cat myjson.json
- description: pass the option and save the content to the json file
fileExtension: .sh
interpreterArgsQuoted: false
script: 'echo "$(jq ''.books[].fear_of_the_dark += { "ISBN" : "#option.isbn#"
}'' myjson.json)" > myjson.json'
scriptInterpreter: /bin/bash
- description: modified file content (after jq)
exec: cat myjson.json
keepgoing: false
strategy: node-first
uuid: d8f1c0e7-a7c6-43d4-91d9-25331cc06560
Finally, check the result.
Here you can check more about executing scripts on Rundeck and here more about the JQ tool.

AWS CLI- What is the syntax for assigning multiple values on a parameter

For example, I have this CF template that ask for these parameters
----- cftemplate.yaml -----
...
Parameters:
**Subnet:
Description: Subnet for the Instance
Type: 'AWS::EC2::Subnet::Id'
SecurityGroups:
Description: Security Group for Instance
Type: 'List<AWS::EC2::SecurityGroup::Id>'**
...
Resources:
EC2Instance:
Type: AWS::EC2::Instance
Properties:
...
**SubnetId: !Ref Subnet
SecurityGroupIds: !Ref SecurityGroups**
...
----- cftemplate.yaml -----
For me to deploy the stack, I use this command:
aws cloudformation create-stack --stack-name StackName --template-body file://cftemplate.yaml --parameters file://params.json
Where params.json contains:
----- params.json -----
[
{
"ParameterKey":"Subnet",
"ParameterValue":"subnet-11111111"
},
{
"ParameterKey":"SecurityGroups",
"ParameterValue":"sg-111111111",
"ParameterValue":"sg-222222222"
}
]
----- params.json -----
Now, my goal is to eliminate the use of .json file. Does anyone know the shorthand syntax of the command that should achieve the same effect as above command? Can't seem to find this on the documentations online. Thanks in advance!
The command line equivalent would be (little re-formatted for clarify):
aws cloudformation create-stack \
--stack-name StackName \
--template-body file://cftemplate.yaml \
--parameters ParameterKey=Subnet,ParameterValue=subnet-11111111 ParameterKey=SecurityGroups,ParameterValue=sg-111111111\\,sg-222222222
In the above attention to spaces and commas are important.
I verified the command using my own parameters and my sandbox account:
aws cloudformation create-stack --stack-name StackName --template-body file://instance.yaml --parameters ParameterKey=Subnet,ParameterValue=subnet-0ae6ce0f9bbf52251 ParameterKey=SecurityGroups,ParameterValue=sg-06d2a3e9c8aa99620\\,sg-004d23d188ec1146f
which is correct and results in starting the process of deploying the stack:
{
"StackId": "arn:aws:cloudformation:us-east-1:xxxxxx:stack/StackName/61fbacd0-d3b0-11ea-970a-0ad23187ddb2"
}
From the cli documentation,
$ aws cloudformation create-stack help
...
"--parameters" (list)
A list of "Parameter" structures that specify input parameters for
the stack. For more information, see the Parameter data type.
Shorthand Syntax:
ParameterKey=string,ParameterValue=string,UsePreviousValue=boolean,ResolvedValue=string ...
JSON Syntax:
[
{
"ParameterKey": "string",
"ParameterValue": "string",
"UsePreviousValue": true|false,
"ResolvedValue": "string"
}
...
]
...
where the list elements are separated by space.
you might want to take a look at the rain cli. It's developed but someone from the cloudformation team and it's much better than the aws cli.
https://github.com/aws-cloudformation/rain

Ansible: Invalid JSON when using --extra-vars

Hi community,
I have been struggling with an issue in ansible issue for days now.
Everything is executed wihtin a Jenkins pipeline.
The ansible command looks like:
sh """
ansible-playbook ${env.WORKSPACE}/cost-optimization/ansible/manage_dynamo_db.yml \
--extra-vars '{"projectNameDeployConfig":${projectNameDeployConfig},"numberOfReplicas":${numberOfReplicas},"dynamodbtask":${dynamodbtask}}'
"""
And the playbooks is:
playbook.yml
---
- hosts: localhost
vars:
numberOfReplicas: "{{numberOfReplicas}}"
dynamodbtask: "{{dynamodbtask}}"
namespace: "{{projectNameDeployConfig}}"
status: "{{status}}"
- tasks:
- name: "Get replica number for the pods"
command: aws dynamodb put-item --table-name pods_replicas
register: getResult
when: dynamodbtask == "get"
- name: "Update replica number for specified pods"
command: |
aws dynamodb put-item
--table-name pods_replicas
--item '{"ProjectNameDeployConfig":{"S":{{namespace}}},"NumberReplicas":{"N":{{numberOfReplicas}}}}'
register: updatePayload
when: dynamodbtask == "put" and getResult is skipped
However, there is always the following error:
fatal: [localhost]: FAILED! => {"changed": true, "cmd": ["aws", "dynamodb", "put-item", "--table-name",
"pods_replicas", "--item", "{\"ProjectNameDeployConfig\":{\"S\":LERN-PolicyCenterV10},\"NumberReplicas\":
{\"N\":0}}"], "delta": "0:00:01.702107", "end": "2020-02-09 16:58:26.055579",
"msg": "non-zero return code", "rc": 255, "start": "2020-02-09 16:58:24.353472", "stderr": "\nError parsing parameter '--item': Invalid JSON: No JSON object could be decoded\nJSON received: {\"ProjectNameDeployConfig\":{\"S\":LERN-PolicyCenterV10},\"NumberReplicas\":{\"N\":0}}", "stderr_lines": ["", "Error parsing parameter '--item': Invalid JSON: No JSON object could be decoded", "JSON received: {\"ProjectNameDeployConfig\":{\"S\":LERN-PolicyCenterV10},\"NumberReplicas\":{\"N\":0}}"], "stdout": "", "stdout_lines": []}
There are two answers to your question: the simple one and the correct one
The simple one is that had you actually fed the JSON into jq, or python -m json.tool, you would have observed that namespace is unquoted:
"{\"ProjectNameDeployConfig\":{\"S\": LERN-PolicyCenterV10 },\"NumberReplicas\": {\"N\":0}}"
where I added a huge amount of space, but didn't otherwise alter the quotes
The correct answer is that you should never use jinja2 to try and assemble structured text when there are filters that do so for you.
What you actually want is to use the to_json filter:
- name: "Update replica number for specified pods"
command: |
aws dynamodb put-item
--table-name pods_replicas
--item {{ dynamodb_item | to_json | quote }}
vars:
dynamodb_item:
"ProjectNameDeployConfig":
"S": '{{ projectNameDeployConfig }}'
"NumberReplicas":
"N": 0
register: updatePayload
when: dynamodbtask == "put" and getResult is skipped
although you'll notice that I changed your variable name because namespace is the name of a type in jinja2, so you can either call it ns or I just used the interpolation value from your vars: block at the top of the playbook, as it doesn't appear that it changed from then