PowerShell GET/POST to Bitbucket API

I guarantee there is a better way to do this, but it took me a while to find the powershell syntax to do GET/POSTing, so hopefully this helps save someone some time.  And yeah, I'm aware that it's saving the password variable in plaintext.  Something to consider for v2.

The idea behind this (partial) script is that you can get most of the pre-setup done automatically.  One of the issues I haven't resolved yet is automatically accepting the ssh prompts (tried pre-injecting stuff, bunch of other things, no luck).  Not a huge deal since the biggest issue is the POSTing of the ssh key to Bitbucket.

This is a small piece of a project to automagically set up a dev workstation from a bare machine.  I think I'll try to post all of the code up when it's done - seems to be a common issue.

Also, I am really starting to get annoyed w. Blogger's inability to do code snippets.  One of these days I'll fix it...or move to Github gists for everything...
<#
    initDevEnviro.ps1
    User input required is bitbucket user/pass
#>
function Pause {Read-Host 'Press Enter to continue...' | Out-Null}
& {
 $wid=[System.Security.Principal.WindowsIdentity]::GetCurrent()
 $prp=new-object System.Security.Principal.WindowsPrincipal($wid)
 $adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator
 $IsAdmin=$prp.IsInRole($adm)
 if ($IsAdmin)
 {
  Write-Host "Script is being executed as admin, proceeding..." -ForegroundColor Green
 }
 else {
    Write-Host "Please re-run the script as an admin." -ForegroundColor Red
    pause
    Exit 1
 }
}
$rootPath = "$env:USERPROFILE\git\projectPath" # This should model the repo structure, plus all IIS config below relies on it.
Write-Host "This is a new workstation (right?), so the user sshkey needs to be generated" -ForegroundColor Cyan
if (!(Test-Path "$env:USERPROFILE\.ssh")) {
    New-Item -ItemType directory "$env:USERPROFILE\.ssh"
}
$PkeyFile = "$env:USERPROFILE\.ssh\id_rsa"
if (!(Test-Path $PkeyFile)) {
    Try {
        Write-Host "No $PkeyFile found, generating one for you..." -ForegroundColor Cyan
        [string]$command = "C:\tools\cmder\vendor\msysgit\bin\ssh-keygen.exe"
        [array]$arguments = "-f", "$pkeyFile", "-t", "rsa", "-N", "''"
        & $command $arguments;
    }
    Catch {
        Write-Host "Generating the SSH key failed!"
        Write-Host $_.Exception.Message -ForegroundColor Red
    }
}
else {
    Write-Host "Looks like you already have an SSH key, skipping the generation process!" -ForegroundColor Green
}
Write-Host "Setting some key variables..."
$keyFile = "$env:USERPROFILE\.ssh\id_rsa.pub"
$key = Get-Content $keyFile -Raw
   
Write-Host "PROMPT: ensure the user has been added to our bitbucket account before continuing `r
 Now we need to connect to bitbucket and install the new ssh key" -ForegroundColor Cyan
 Pause
$cred = Get-Credential -Message "Enter your BitBucket credentials"
[string]$userName = $cred.GetNetworkCredential().username # Save the username as a variable
[string]$password = $cred.GetNetworkCredential().password # Save the password as a variable
$uri = "https://api.bitbucket.org/1.0/users/$userName/ssh-keys"
[string]$label = hostname
$postData = @{
    key = "$key" #get id-rsa key here
    label = "$label" #just a label, can be anything
}
Write-Host "Now we actually connect to the Bitbucket REST API" -ForegroundColor Cyan
Try {
    Write-Host "Is there already a key in Bitbucket?" -ForegroundColor Cyan
    Try {
        $params = @{
            Uri = $uri;
            Method = 'GET';
            Headers = @{
            Authorization = 'Basic ' + [Convert]::ToBase64String(
                [Text.Encoding]::ASCII.GetBytes("$($userName):$($password)"));
            }
            ContentType = 'application/json';
        }
        $APIcallResults = Invoke-RestMethod @params
        $returnedLabel = $APIcallResults.label
        $labelMatch = $returnedLabel -match $label
    }
    Catch {
        Write-Host "GETing from the Bitbucket API failed!"
        Write-Host $_.Exception.Message -ForegroundColor Red
    }
    if ($returnedLabel | Where-Object {$_ -eq $label}) {
        Write-Host "Key already exists in Bitbucket, skipping..." -ForegroundColor Green
    }
    else {
        Write-Host "Key doesn't exist in Bitbucket, adding..." -ForegroundColor Cyan
        Write-Host "Doing the POST..."
        $params = @{
            Uri = $uri;
            Method = 'POST';
            Headers = @{
            Authorization = 'Basic ' + [Convert]::ToBase64String(
                [Text.Encoding]::ASCII.GetBytes("$($userName):$($password)"));
            }
            ContentType = 'application/json';
            Body = (ConvertTo-Json $postData -Compress)
        }
        Invoke-RestMethod @params
        Write-Host "Let's test to ensure the key was stored correctly..." -ForegroundColor Cyan
        Try {
            $params = @{
                Uri = $uri;
                Method = 'GET';
                Headers = @{
                Authorization = 'Basic ' + [Convert]::ToBase64String(
                    [Text.Encoding]::ASCII.GetBytes("$($userName):$($password)"));
                }
                ContentType = 'application/json';
            }
            $APIcallResults = Invoke-RestMethod @params
            $returnedLabel = $APIcallResults.label
            if ($returnedLabel | Where-Object {$_ -eq $label}) {
                Write-Host "Bling! Key successfully imported to Bitbucket!" -ForegroundColor Green
            }
            else {
                Write-Host "Ruh roh Shaggy, key import broke - the key hasn't been added!"
                Pause
                Exit 1
            }
        }
        Catch {
            Write-Host "GETing from the Bitbucket API failed!"
            Write-Host $_.Exception.Message -ForegroundColor Red
        }
    }
}
Catch {
    Write-Host "Connecting to the Bitbucket API failed!"
    Write-Host $_.Exception.Message -ForegroundColor Red
}

Comments

Popular posts from this blog

DFSR - eventid 4312 - replication just won't work

Fixing duplicate SPNs (service principal name)

Logstash to Nagios - alerting based on Windows Event ID