Saturday, October 28, 2017

Adding the service principle connection for automation account in azure

 $connectionName = "AzureRunAsConnection"
        $global:servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
        Add-AzureRmAccount `
            -ServicePrincipal `
            -TenantId $servicePrincipalConnection.TenantId `
            -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint | Write-Verbose

How to create a hash for a string value in powershell



#MD5 output is 128bits=16bytes
#Output is always 22 characters long

$bytesFromInput = [System.Text.UTF8Encoding]::UTF8.GetBytes($InputString)
        $sha1= [System.Security.Cryptography.MD5]::Create()
        $bytesToOutput= $sha1.ComputeHash($bytesFromInput)
        [System.Convert]::ToBase64String($bytesToOutput).ToLower().Replace('+','0').Replace('/','0').Replace('=','')

How to lock object in powershell similar to c#


$hashTable = @{}
    Lock-Object -InputObject $hashTable.SyncRoot -ScriptBlock {
        $hashTable.Add("Key", "Value")
    }



function Lock-Object
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [AllowEmptyString()]
        [AllowEmptyCollection()]
        [object]
        $InputObject,

        [Parameter(Mandatory = $true, Position = 1)]
        [scriptblock]
        $ScriptBlock
    )

    # Since we're dot-sourcing the caller's script block, we'll use Private scoped variables within this function to make sure
    # the script block doesn't do anything fishy (like changing our InputObject or lockTaken values before we get a chance to
    # release the lock.)

    Set-Variable -Scope Private -Name __inputObject -Value $InputObject -Option ReadOnly -Force
    Set-Variable -Scope Private -Name __scriptBlock -Value $ScriptBlock -Option ReadOnly -Force
    Set-Variable -Scope Private -Name __threadID -Value ([System.Threading.Thread]::CurrentThread.ManagedThreadId) -Option ReadOnly -Force
    Set-Variable -Scope Private -Name __lockTaken -Value $false

    if ($__inputObject.GetType().IsValueType)
    {
        $params = @{
            Message      = "Lock object cannot be a value type."
            TargetObject = $__inputObject
            Category     = [System.Management.Automation.ErrorCategory]::InvalidArgument
            ErrorId      = 'CannotLockValueType'
        }

        Write-Error @params
        return
    }

    try
    {
        Write-Verbose "Thread ${__threadID}: Requesting lock on $__inputObject"
        [System.Threading.Monitor]::Enter($__inputObject)
        $__lockTaken = $true
        Write-Verbose "Thread ${__threadID}: Lock taken on $__inputObject"

        . $__scriptBlock
    }
    catch
    {
        $params = @{
            Exception    = $_.Exception
            Category     = [System.Management.Automation.ErrorCategory]::OperationStopped
            ErrorId      = 'InvokeWithLockError'
            TargetObject = New-Object psobject -Property @{
                ScriptBlock = $__scriptBlock
                InputObject = $__inputObject
            }
        }

        Write-Error @params
        return
    }
    finally
    {
        if ($__lockTaken)
        {
            Write-Verbose "Thread ${__threadID}: Releasing lock on $__inputObject"
            [System.Threading.Monitor]::Exit($__inputObject)
            Write-Verbose "Thread ${__threadID}: Lock released on $__inputObject"
        }
    }
}

How to invoke a child build definition from powershell using VSTS

Get the buildid(parent and child) of the build defintions and use the powershell script to invoke the build from powershell


$buildQueUri = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/builds?api-version=2.0"


$parameters = @{
"system.debug" = $env:SYSTEM_DEBUG
"deploymentEnvironment" = $deploymentEnvironment
"region" = $regions
"deploymentPaths" =  $deploymentPaths
"parentBuildID" = $buildId
"requestedBy" = $requestedBy
}|ConvertTo-Json -Compress

$body = @{
"definition" = @{ "id" = $childBuildId }
"requestedFor" = @{ "id" = $env:BUILD_REQUESTEDFORID }
"sourceBranch" = $sourceBranch
"sourceVersion" = $sourceVersion
"parameters" = $parameters
}|ConvertTo-Json -Compress

$buildResponse = Invoke-RestMethod -Method Post -Uri $buildQueUri -Headers $headers -Body $body -ContentType 'application/json' -ErrorAction Stop

Saturday, October 7, 2017

Getting Azure advisor details from powershell using REST API

            
$advisorName = "Azure Advisor";            
function Invoke-AzureManagementPostMethod {            
             
 process {            
            
    $ClientId = "3fb00cf8-b7a6-42e0-bfdd-ae703499a52c"            
    $ClientSecret = "40v/urtrK+QLZzU5LalL75iNJ5wv9I4EUkygbM+6EtQ="            
                
    $TenantId = (Get-AzureRmContext).Tenant.Id            
    $Resource = "https://management.azure.com/"            
     $authData = Invoke-RestMethod -Method Post `
   -Uri "https://login.windows.net/$TenantId/oauth2/token?api-version=1.0" `
   -Body @{ "grant_type"="client_credentials"; "resource"=$Resource; "client_id"=$ClientId; "client_secret"=$ClientSecret; } `
   -ContentType "application/x-www-form-urlencoded"            
  $headers = @{"Authorization"="Bearer $($authData.access_token)"}            
  return $headers            
 }            
}            
            
function Get-AzureAdvisorRecommendations {            
param(            
    [Parameter(Mandatory=$true)][String]$SubscriptionId            
)            
            
    $method = "GET"            
    $URI = "https://management.azure.com/subscriptions/$SubscriptionId/providers/Microsoft.Advisor/recommendations?api-version=2017-03-31"            
    $managementHeaders = Invoke-AzureManagementPostMethod            
    $allRecommendations = Invoke-RestMethod -Uri $URI -Method $method -Headers $managementHeaders             
    $resourcegroupRecommendations=@{}             
            
    foreach($recommendation in $allRecommendations.Value | where { $_.properties.category -in ("HighAvailability", "Performance", "Cost")} )            
    {            
        $values = $recommendation.id.Split('/')            
        $resourceGroup = $values[4]            
        $resourceName = $values[8]            
        $recommendation = @{            
            Resource          =  $resourceName            
            Source            =  $advisorName                    
            Policy            =  $recommendation.properties.shortDescription.problem                     
            Severity          =  $recommendation.properties.impact                    
            Recommendation    =  $recommendation.properties.shortDescription.solution            
            Message           =  ""            
        }             
        $recommendationObject = New-Object PSObject -Property $recommendation            
        if($resourcegroupRecommendations.ContainsKey($resourceGroup))            
        {            
            $recommendationpreviousObject = $resourcegroupRecommendations.Get_Item($resourceGroup)            
            $resourcegroupRecommendations["$resourceGroup"] = $recommendationpreviousObject,$recommendationObject            
        }            
        else            
        {            
            $resourcegroupRecommendations.Add($resourceGroup, $recommendationObject)            
        }             
    }             
    $resourcegroupRecommendations            
                
}            
            
            
$output = Get-AzureAdvisorRecommendations (Get-AzureRmContext).Subscription.Id

Azure Key vault

Creating Key Vault and keys and secret

New-AzureRmKeyVault -VaultName 'ContosoKeyVault' -ResourceGroupName 'ContosoResourceGroup' -Location 'East Asia'

$key = Add-AzureKeyVaultKey -VaultName 'ContosoKeyVault' -Name 'ContosoFirstKey' -Destination 'Software'

$secretvalue = ConvertTo-SecureString 'Pa$$w0rd' -AsPlainText -Force

$secret = Set-AzureKeyVaultSecret -VaultName 'ContosoKeyVault' -Name 'SQLPassword' -SecretValue $secretvalue

Integration with Azure active directory

Applications that use a key vault must authenticate by using a token from Azure Active Directory. To do this, the owner of the application must first register the application in their Azure Active Directory

Authorize the application to use the key or secret

Set-AzureRmKeyVaultAccessPolicy -VaultName 'ContosoKeyVault' -ServicePrincipalName 8f8c4bbd-485b-45fd-98f7-ec6300b7b4ed -PermissionsToKeys decrypt,sign

Set-AzureRmKeyVaultAccessPolicy -VaultName 'ContosoKeyVault' -ServicePrincipalName 8f8c4bbd-485b-45fd-98f7-ec6300b7b4ed -PermissionsToSecrets Get

Regenerate the Keys

$regenerationPeriod = [System.Timespan]::FromDays(1)
$parameters = @{
VaultName = $keyVaultName
AccountResourceId = $storageAccountId
AccountName = "mystoragetest1"
ActiveKeyName = "key1"
RegenerationPeriod = $regenerationPeriod
}
Add-AzureKeyVaultManagedStorageAccount @parameters

Get-AzureKeyVaultManagedStorageAccount

Update-AzureKeyVaultManagedStorageAccountKey

Accessing the Keys from the web application


https://docs.microsoft.com/en-us/azure/key-vault/key-vault-use-from-web-application