我需要将以下PowerShell脚本转换为Bash脚本。有人可以帮帮我吗?我对Bash真的很新,并且不知道如何操纵curl命令的输出然后将其转换为Json。
$headers = @{"X-Octopus-ApiKey"="<api_key>"}
$machine = Invoke-RestMethod "http://my.url/api/machines/discover?host=<ip_address>&type=ssh" -Headers $headers -Method Get
$machine.Name = "<hostname>"
$machine.Roles += "<role>"
$machine.EnvironmentIds += "<environment>"
$machine.Endpoint.AccountId = "<account_id>"
Invoke-RestMethod "http://my.url/api/machines" -Headers $headers -Method Post -Body ($machine | ConvertTo-Json -Depth 10)
答案 0 :(得分:3)
Powershell从Invoke-RestMethod返回对象响应,但curl返回json字符串格式。 你必须解析curl的响应,使用像jq这样的json解析器工具来提取Roles和EnvironmentIds的值。
确保您安装了jq
以下脚本是Powershell脚本的转换:
headers='{"X-Octopus-ApiKey"="<api_key>"}'
#$machine = Invoke-RestMethod "http://my.url/api/machines/discover?host=<ip_address>&type=ssh" -Headers $headers -Method Get
response=$(curl -s -X GET -H $headers "http://my.url/api/machines/discover?host=<ip_address>&type=ssh")
echo $response
Name="Myhostname"
Roles=$(echo $response | jq -r ".Roles")
echo $Roles
Roles+="Myrole2"
EnvironmentIds=$(echo $response | jq -r ".EnvironmentIds")
echo $EnvironmentIds
EnvironmentIds+="Myenvironment2"
echo $EnvironmentIds
AccountId="Myaccount_id"
#compose json string to be passed as a body for the next curl call
machine=$(printf '
{"Name":"%s",
"Roles":"%s" ,
"EnvironmentIds":"%s" ,
"Endpoint" : {
"AccountId" : "%s"
}
}' "$Name" "$Roles" "$EnvironmentIds" "$AccountId")
echo $machine
#Invoke-RestMethod "http://my.url/api/machines" -Headers $headers -Method Post -Body ($machine | ConvertTo-Json -Depth 10)
response=$(curl -s -X POST -H $headers -d $machine "http://my.url/api/machines")
echo $response