Get Azure VM size inside on a windows machine - windows

I do only have access on a Windows VM which is hosted on Azure.
Is there a way to find out the VM size inside of the virtual machine, lets say for example over commandline (powershell / cmd), without having further information about the envrionment like for example Ressource Group or VM Ressource Name?
I did find a way like this, but it requires the information about the name of VM and Ressource group:
$VM = Get-AzureRMVM –Name HSG-Linux1 –ResourceGroupName HSG-AzureRG
$VM.HardwareProfile
Source

You can use the metada to get the VM information inside the VM like this:
Invoke-RestMethod -Headers #{"Metadata"="true"} -URI http://169.254.169.254/metadata/instance/compute?api-version=2019-03-11 -Method get
For more details, see Azure Instance Metadata service. You can also put the output as a variable, then get the special properties. For example:
$vm = Invoke-RestMethod -Headers #{"Metadata"="true"} -URI http://169.254.169.254/metadata/instance/compute?api-version=2019-03-11 -Method get
$vm.vmSize
Or get the property directly through the request like this:
$vmSize = Invoke-RestMethod -Headers #{"Metadata"="true"} -URI "http://169.254.169.254/metadata/instance/compute/vmSize?api-version=2019-03-11&&format=text" -Method get

Related

Automating Windows Server Updates with PSwindowsUpdate module. Issue

I am trying to automate windows server update instllation for multiple servers. I have installed the module on all servers and also added the hostnames in winrm trust hosts.
All server hostnames are stored in txt file and are looped trought for each loop with different commands from teh PSwindowswupdate module.
$Hostname = Get-Content -Path "C:\TEMP\powershell_patching_script\module\hostnamesallwsus.txt"
Import-Module PSWindowsUpdate
foreach ($i in $Hostname) {
write-host $i
Get-WUHistory -ComputerName $i -last 3
}
Issue is that randomly the loop is failing for some hostnames, with error :
BGxxxxxxx01 #this is the hostname
Get-WUHistory : BGxxxxxxx01: Unknown failure.
At C:\TEMP\powershell_patching_script\Module\History.ps1:10 char:1
+ Get-WUHistory -ComputerName $i -last 3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [Get-WUHistory], Exception
+ FullyQualifiedErrorId : Unknown,PSWindowsUpdate.GetWUHistory
If I run the command with the hostname instead of variable it is failing again with the same error.
If I run the same but with $ in front of the hostname (even if such varaiable is not defined) the command works!ly appriciated
Get-WUHistory -ComputerName $BGxxxxxxx01 -last 3
Localy executed the commands are also working.
This issue seams to occure on random bases for multiple hostnames form my list.
I am unable find anything helpful regarding this error.
Any help will be highly appriciated!
Thanks in advance!
I found that Invoke-command works.
Just need to put the command in the script block of Invoke-command.

Easily catch error from maven install task in build pipeline in Azure Devops?

In Azure Devops when your Maven build task fails it will display an an error like below in the build summary:
Maven build error
Now if you click in and scroll up you will be able to find the error next to the reactor summary. This is easy enough to do at home with a mouse and a big screen but for some of our devs on trains or in cafes it can be quite an effort for them to find the error. I want to be able to make the error easier to find. Some suggestions I've thought of but not sure how to implement are below. Do you have any other good ideas?
Reduce output of maven logs - I've tried the -q flag but it doesn't seem to work for this task?
Use rest api somehow to find the error and then send it to a slack channel with a webhook - Not sure how to find the log or error with the rest api though
So I can help with how you might grab the error out of the build logs and send it over to slack.
Assuming we are going to run this task as the next task after the build error.
We can get the build logs via the API. Make sure to add the system_access token so you can auth.
Once we have all the logs grab the url out of the response to download the last log
Download the last log
Parse it and find the [[error]] lines
Marshal the message to slack \ or do whatever else you want with it
YAML
- pwsh: |
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $env:System_AccessToken)))
$uriLogs = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/builds/$env:BUILD_BUILDID/logs?api-version=5.1"
$response = Invoke-RestMethod -Uri $uriLogs -Method 'GET' -Headers #{Authorization = ("Basic {0}" -f $base64AuthInfo)}
$logUrl =$response.value[-1].url
$webContent = Invoke-WebRequest -Uri $logUrl -Method 'GET' -Headers #{Authorization = ("Basic {0}" -f $base64AuthInfo)}
$ErrorMessage = $webContent.Content.tostring() -split "[`r`n]" | select-string "[[Error]]"
Write-Output "Error lines found " $ErrorMessage
$postSlackMessage = #{token=$env:SLACK_TOKEN;channel="#user,#channel-name";text=$ErrorMessage}
Invoke-RestMethod -Uri https://slack.com/api/chat.postMessage -Body $postSlackMessage
env:
system_accesstoken: $(System.AccessToken)
condition: failed()
Other alternatives:
parse the log, find the error, and then send a link to the failure directly at that line number. There is a well known format for direct links to each line.
send a direct link to download just the error part of the log. See startLine and endLine parameters here.
I added a line to top of powershell script to solve the error
Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a receive.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
If you don't have any problem about tls you don't need to add this line.
Powershell:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$uriLogs = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/builds/$env:BUILD_BUILDID/logs?api-version=5.0"
$response = Invoke-RestMethod -Uri $uriLogs -Method Get -Headers #{ Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
$logUrl = $response.value[-1].url
$webContent = Invoke-WebRequest -Uri $logUrl -Method GET -Headers #{ Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
$ErrorMessage = $webContent.Content.tostring() -split "[`r`n]" | select-string "[[error]]"
Write-Output "Error lines found " $ErrorMessage

Ansible Tower REST API: Is there any way to get the logs/output of a job?

I have a Ansible job started by another Process. Now I need to check the status of the current running job in Ansible Tower.
I am able to track the status whether it is running/success/failed/canceled with /jobs/{id} using REST API.
But I would also need the information of the console logs/ouputs of the task for processing as well. Is there any direct API call for the same?
You can access the job log via a link similar to:
https://tower.yourcompany.com/api/v1/jobs/12345/stdout?format=txt_download
Your curl command would be similar to:
curl -O -k -J -L -u ${username):${password} https://tower.company.com/api/v1/jobs/${jobnumber}/stdout?format=txt_download
obviously replacing ${username}, ${password}, and ${jobnumber} with your own values
The curl flags used:
-O : output the filename that is actually downloaded
-k : insecure SSL (don't require trusted CAs)
-J : content header for file download https://curl.haxx.se/docs/manpage.html#-J
-L : follow redirects
-u : username and password
You can do this via their restful call.
To get the job number use a GET against https://yourtowerinstance/api/v2/job_templates/
this will return your templates, and their IDs
To get the output in real time I use this powershell code
$stdouturl = "https://yourtowerinstance/api/v2/jobs/$($templateResult.id)/stdout/?format=txt"
$resultstd = Invoke-Restmethod -uri $stdouturl -Method 'Get' -Headers $authHeader
while ($resultstd -notmatch 'PLAY RECAP') {
$resultstd = Invoke-Restmethod -uri $stdouturl -Method 'Get' -Headers $authHeader
start-sleep -s 5
}
$resultstd
Once you launch a template you get the job-id in response but I don't think there is a API to get the output of the job. However from the dashboard under jobs section you can download the individual job output.

Deleting Report Server (2014 Native Mode) Encrypted Keys & Data [PowerShell]

After I clone an instance from an image, a few manual steps need to be carried out to get the report server working correctly. Among them is the deletion of all encrypted data, including symmetric key instances on the report server database.
This step requires me to RDP to the server in question, open the Reporting Services Configuration Manager and delete the encrypted data manually.
Without carrying out this step, I get the following error when I try to load up the report server interface of the new server:
The report server cannot open a connection to the report server
database. A connection to the database is required for all requests
and processing. (rsReportServerDatabaseUnavailable)
I'm trying to automate this step, so that it runs as part of a PowerShell script to remotely delete the encrypted data.
I am aware of 'rskeymgmt -d' but this prompts the user for input when run and has no force flag available to circumvent this additional input, rendering it unusable for running remotely as far as I can see:
C:\>rskeymgmt -d
All data will be lost. Are you sure you want to delete all encrypted data from
the report server database (Y/N)?
I've found a solutions to solving this problem. Calling RSKeyMgmt -d through a remote PowerShell session and piping the Y string to the call passes the parameter that RSKeyMgmt prompts the user for. This method is based on Som DT's post on backing up report server encryption keys
I've attached the full script I am using as part of my environment cloning process.
<#
.SYNOPSIS
Deletes encrypted content from a report server
.PARAMETER MachineName
The name of the machine that the report server resides on
.EXAMPLE
./Delete-EncryptedSsrsContent.ps1 -MachineName 'dev41pc123'
Deletes encrypted content from the 'dev41pc123' report server
#>
param([string]$MachineName = $(throw "MachineName parameter required, for command line usage of this script, type: 'get-help ./Delete-EncryptedSSRS.ps1 -examples'"))
trap [SystemException]{Write-Output "`n`nERROR: $_";exit 1}
Set-StrictMode -Version Latest
try
{
Write-Output "`nCreating remote session to the '$machineName' machine now..."
$session = New-PSsession -Computername $machineName
Invoke-Command -Session $Session -ScriptBlock {"Y" | RSKeyMgmt -d}
}
catch
{
Write-Output "`n`nERROR: $_"
}
finally
{
if ($Session)
{
Remove-PSSession $Session
}
}
This is a generalisation of ShaneC's solution, to support deletion of encrypted content on non default instances:
<#
.SYNOPSIS
Deletes encrypted content from a report server
.PARAMETER MachineName
The name of the machine that the report server resides on
.EXAMPLE
./Delete-EncryptedSsrsContent.ps1 -MachineName 'dev41pc123'
Deletes encrypted content from the default instance (MSSQLSERVER) of the 'dev41pc123' report server
.EXAMPLE
./Delete-EncryptedSsrsContent.ps1 -MachineName 'dev41pc123' -InstanceName 'NonDefault'
Deletes encrypted content from the specified non-default instance (e.g. NonDefault) of the 'dev41pc123' report server
#>
param(
[Parameter(Mandatory=$true)]
[string]$MachineName = $(throw "MachineName parameter required, for command line usage of this script, type: 'get-help ./Delete-EncryptedSSRS.ps1 -examples'"),
[Parameter(Mandatory=$false)]
[string]$InstanceName)
trap [SystemException]{Write-Output "`n`nERROR: $_";exit 1}
Set-StrictMode -Version Latest
try
{
Write-Output "`nCreating remote session to the '$MachineName' machine now..."
$session = New-PSsession -Computername $MachineName
if ([string]::IsNullOrEmpty($instanceName))
{
Invoke-Command -Session $Session -ScriptBlock {"Y" | RSKeyMgmt.exe -d}
}
else
{
Write-Output "`nDeleting all encrypted content from the $InstanceName instance on the $MachineName machine now...`n"
$command = """Y""| RSKeyMgmt.exe -d -i""" + $InstanceName + """"
Invoke-Command -Session $Session -ScriptBlock { Invoke-Expression $args[0] } -ArgumentList $command
Write-Output "`n"
}
}
catch
{
Write-Output "`n`nERROR: $_"
}
finally
{
if ($Session)
{
Remove-PSSession $Session
}
}

Invoke-RestMethod : Content-Length or Chunked Encoding cannot be set for an operation that does not write data

I am looking for cURL equivalent command in powershell and then found the below mentioned URL :
https://superuser.com/questions/344927/powershell-equivalent-of-curl
Based on the above URL I tried the below mentioned powershell script in a system which has Powershell version 4.0
Invoke-RestMethod -Uri www.discoposse.com/index.php/feed -Method Get -OutFile C:\Temp\DiscoPosseFeed.xml
Once I run the above command I see a xml file in the specified location but if now I specify the encoding as mentioned below:
Invoke-RestMethod -Uri www.discoposse.com/index.php/feed -TransferEncoding compress -Method Get -OutFile C:\Temp\DiscoPosseFeed.xml
I am getting an error :
Can anyone help me to know is there anything I am missing here?
The explanation is tha your command line does not write anything on the line. TransferEncoding specifies a value for the transfer-encoding HTTP response header. Valid values are Chunked, Compress, Deflate, GZip and Identity.

Resources