-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDigitalOcean.ps1
635 lines (546 loc) · 16.6 KB
/
DigitalOcean.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
# Uses version 2 of the DigitalOcean RESTful Web API
# https://developers.digitalocean.com/
# On Error - Stop
$ErrorActionPreference = "Stop"
# The scriptpath is the path for storing files and settings such as
# your API key. The default path is the same directory as the script.
$scriptpath = Split-Path $MyInvocation.MyCommand.Path
# Uncomment if you want to use your my documents folder
#$scriptpath = ([environment]::getfolderpath("mydocuments"))
# Reads api.txt file for the API key
Function ReadAPIKey
{
if (Test-Path $scriptpath\api.txt)
{
return Get-Content $scriptpath\api.txt
}
else
{
$ignore = New-Item $scriptpath\api.txt -type file
Write-Host "ERROR: API is missing from api.txt file!" -foregroundcolor red
break
}
}
# Your API key is read from a separate text file called api.txt
# This file should only contain your API key
$api_key = ReadAPIKey
#$api_key = {{ THIS IS MY PRIVATE DIGITALOCEAN API KEY HARDCODE IN }}
# Default settings for your new droplets
$defaultregion = "lon1"
$defaultsize = "1gb"
$defaultimage = "ubuntu-14-04-x32"
$defaultbackups = "true"
$defaultipv6 = "true"
$defaultprivate_networking = "false"
# You need to create the domain first in order to automatically create
# the pointer records, but you must first create the domain which
# requires you to set an IP address. To get around the chicken and egg
# scenerio we set a temporary IP address and change it to the droplets
# IP address once it's created. The default is the local loopback
# address - 127.0.0.1
$tempip = "127.0.0.1"
# DigitalOcean API URL
$url = "https://api.digitalocean.com/v2"
# URL where to download Putty \ PuttyGen
# Putty is a free Windows SSH client and PuttyGen is a SSH keygen
$putty_download_site = "http://the.earth.li/~sgtatham/putty/latest/x86"
#######################################################################
###### #####
###### DON'T EDIT ANYTHING BELOW THIS LINE #####
###### #####
#######################################################################
if ($api_key -eq $null)
{
Write-Host "ERROR: No API key set in api.txt file!" -foregroundcolor red
break
}
$header = @{"Authorization"="Bearer " + $api_key;"Content-Type"="application/json"}
# List all the droplets on your DigitalOcean account
Function ListAllDroplets
{
$r = Invoke-WebRequest -Uri $url/droplets -Method GET -Headers $header
return $r.Content | ConvertFrom-Json
}
# List all the domains on your DigitalOcean account
Function ListAllDomains
{
$r = Invoke-WebRequest -Uri $url/domains -Method GET -Headers $header
return $r.Content | ConvertFrom-Json
}
# Lists all the DC regions
Function ListAllRegions
{
$r = Invoke-WebRequest -Uri $url/regions -Method GET -Headers $header
return $r.Content | ConvertFrom-Json
}
# Lists all the OS images avalible
Function ListAllImages
{
$r = Invoke-WebRequest -Uri $url/images -Method GET -Headers $header
return $r.Content | ConvertFrom-Json
}
# Lists all the server sizes (512mb \ 1gb \ 2gb etc)
Function ListAllSizes
{
$r = Invoke-WebRequest -Uri $url/sizes -Method GET -Headers $header
return $r.Content | ConvertFrom-Json
}
# Creates a new domain in DNS on your DigitalOcean account
Function CreateDomain($content)
{
$r = Invoke-WebRequest -Uri $url/domains -Method POST -Headers $header -Body $content
return $r.Content | ConvertFrom-Json
}
# Creates a new droplet on your DigitalOcean account
Function CreateDroplet($settings)
{
$r = Invoke-WebRequest -Uri $url/droplets -Method POST -Headers $header -Body $settings
return $r.Content | ConvertFrom-Json
}
# Lists the IPs (both IPv4 and IPv6) of your droplet
Function GetIPAddress($id)
{
$r = Invoke-WebRequest -Uri $url/droplets/$id -Method GET -Headers $header
return $r.Content | ConvertFrom-Json | select droplet
}
# List all the DNS records for the newly created domain
Function ListAllRecords
{
$r = Invoke-WebRequest -Uri $url/domains/$newdomain/records -Method GET -Headers $header
return $r.Content | ConvertFrom-Json
}
# Create a DNS record for the newly created domain
Function CreateRecord ($data)
{
$r = Invoke-WebRequest -Uri $url/domains/$newdomain/records -Method POST -Headers $header -Body $data
return $r.Content | ConvertFrom-Json
}
# Update DNS record for the newly created domain
Function UpdateRecord ($data, $recordid)
{
$r = Invoke-WebRequest -Uri $url/domains/$newdomain/records/$recordid -Method PUT -Headers $header -Body $data
return $r.Content | ConvertFrom-Json
}
# Creates a DNS MX record on your new domain
Function CreateMXRecord($priority, $address)
{
$mxrecord = @{priority=$priority;data=$address;type="MX"} | ConvertTo-Json
CreateRecord -data $mxrecord
}
# Creates a DNS SPF record on your new domain
Function CreateSPFRecord($spf)
{
$spfrecord = @{name="@";data=$spf;type="TXT"} | ConvertTo-Json
CreateRecord -data $spfrecord
}
# Creates a DNS CNAME record on your new domain
Function CreateCNameRecord($cname, $address)
{
$cnamerecord = @{name=$cname;data=$address;type="CNAME"} | ConvertTo-Json
CreateRecord -data $cnamerecord
}
# Lists all the SSH public keys on your DigitalOcean account
Function ListAllKeys
{
$r = Invoke-WebRequest -Uri $url/account/keys -Method GET -Headers $header
return $r.Content | ConvertFrom-Json
}
# Uploads the local SSH public key onto your DigitalOcean account
Function UploadSSHKey
{
$sshrecord = @{name="PowerShell";public_key=$localkey} | ConvertTo-Json
$r = Invoke-WebRequest -Uri $url/account/keys -Method POST -Headers $header -Body $sshrecord
$sshresult = $r.Content | ConvertFrom-Json
return $sshresult.ssh_key.fingerprint
}
# Checks if the local SSH public key is loaded onto your DigitalOcean account
Function CheckRemoteSSHKey
{
$allkeys = ListAllKeys
$keys = $allkeys.ssh_keys
Write-Host "Number of remote ssh keys:" $keys.Count
If ($keys.Count -gt 0)
{
foreach ($key in $keys)
{
$remoteKeyResult = $key.public_key
if ($remoteKeyResult -eq $localkey)
{
return $key.fingerprint
}
}
}
return $null
}
# Checks if Putty and Puttygen is present if not downloads it.
Function DownloadPutty
{
if (!(Test-Path $scriptpath\putty.exe))
{
Invoke-WebRequest $putty_download_site/putty.exe -OutFile $scriptpath\putty.exe
}
if (!(Test-Path $scriptpath\puttygen.exe))
{
Invoke-WebRequest $putty_download_site/puttygen.exe -OutFile $scriptpath\puttygen.exe
}
}
# Runs PuttyGen so the user can generate a secure (public\private) SSH key
Function RunPuttyGen
{
DownloadPutty
Start-Process $scriptpath\puttygen.exe -Wait
}
# Check if the local SSH key has been generated, otherwise run PuttyGen
Function CheckLocalSSHKey
{
if ( (Test-Path $scriptpath\public) -and (Test-Path $scriptpath\private.ppk) )
{
Write-Host "Local SSH key found"
}
else
{
Write-Host "================================="-foregroundcolor red
Write-Host "= No local SSH keys found!"-foregroundcolor red
Write-Host "================================="-foregroundcolor red
Write-Host ""
Write-Host "Please create a public\private SSH key and re-run."
Write-Host "Visit: for more information."
Write-Host ""
# Run PuttyGen to generate a SSH key to use
RunPuttyGen
# Abort
break
}
}
# Generates a secure password
# - 24 characters long
# - upper and lower case alphanumeric
# - and at least 1 special character
Function GenPass
{
$chars = [Char[]]"012@;:,.<>#STUV3789qr4LMNOIJKcdABP6ab0I-CDEO1*23uvwxyzbcdefstuCDQR(_+IJKLMabvwxA)yzEWXYZF=BGHef!£^ghijklmnop56N4TUV$%WXRSYZ5678klmnopqrs0abcdeFGHOTfghij1290123agPQRSLMNFGHIJK678EFGHPQ9defghij456UVWXYZ789klopqrst3mn45chi7LMNJKABCDOPQRjklmnopqrstuvwS89TUVWxyzXYZ012ABC012345DE3456789"
$genpass = ($chars | Get-Random -Count 24) -join ""
if
(($genpass.Contains("@")) -or ($genpass.Contains(';'))-or ($genpass.Contains(':')) -or ($genpass.Contains(',')) -or ($genpass.Contains('.')) -or ($genpass.Contains('<')) -or ($genpass.Contains('>')) -or ($genpass.Contains('#')) -or ($genpass.Contains('-')) -or ($genpass.Contains('*')) -or ($genpass.Contains('(')) -or ($genpass.Contains('_')) -or ($genpass.Contains('+')) -or ($genpass.Contains(')')) -or ($genpass.Contains('=')) -or ($genpass.Contains('!')) -or ($genpass.Contains('£')) -or ($genpass.Contains('^')) -or ($genpass.Contains('$')) -or ($genpass.Contains('%')) -or ($genpass.Contains('"')))
{
return $genpass
}
else
{
Write-Host "Error"
return GenPass
}
}
# Connect over SSH to new droplet using putty
Function RunPutty ($build_script)
{
$ipadd = $ipv4.ip_address
$sshaddress = "root@" + $ipadd
$usrsshkey = $scriptpath+"\private.ppk"
$args = "-ssh", $sshaddress, "-i", $usrsshkey
Start-Process $scriptpath\putty.exe -Wait -ArgumentList $args
}
# Creates a new droplet [entire process]
Function CreateNewDroplet
{
Clear-Host
Write-Host "Create new droplet"
Write-Host "=================="
Write-Host ""
##
# Create domain
$newdomain = Read-Host 'Domain name'
# Check if domain not exists:
If ($domains.name -contains $newdomain)
{
# Domain already exists, abort!
Write-Host "Domain already exists!" -foregroundcolor white -backgroundcolor red
break
}
$newdomainbody = @{name=$newdomain;ip_address=$tempip} | ConvertTo-Json
$createddomain = CreateDomain -content $newdomainbody
##
# Create droplet
##
# Images
Clear-Host
$images = ListAllImages
$imageCnt = $images.images.Count
$imageUpTo = 1
$publicImages = @()
[int]$xMenuChoiceA = 0
while ( $xMenuChoiceA -lt 1 -or $xMenuChoiceA -gt $imageCnt ){
foreach ($image in $images.images)
{
if ($image.public -eq 'true')
{
if ($defaultimage -eq $image.name)
{
Write-Host ' '$imageUpTo'. ' $image.name ' (default)'
}
else
{
Write-Host ' '$imageUpTo'. ' $image.name
}
$publicImages = $publicImages + $image.name
$imageUpTo = $imageUpTo + 1
}
}
[Int]$xMenuChoiceA = read-host "Select a image for your new droplet" }
$newimage = $publicImages[$xMenuChoiceA -1]
##
# Regions
Clear-Host
$regions = ListAllRegions
$regionCnt = $regions.regions.Count
$regionUpTo = 1
[int]$xMenuChoiceA = 0
while ( $xMenuChoiceA -lt 1 -or $xMenuChoiceA -gt $regionCnt ){
foreach ($region in $regions.regions)
{
if ($defaultregion -eq $region.name)
{
Write-Host ' '$regionUpTo'. ' $region.name ' (default)'
}
else
{
Write-Host ' '$regionUpTo'. ' $region.name
}
$regionUpTo = $regionUpTo + 1
}
[Int]$xMenuChoiceA = read-host "Select a region\data centre for your new droplet" }
$newregion = $regions.regions[$xMenuChoiceA -1].slug
##
# Sizes
Clear-Host
$sizes = ListAllSizes
$sizesCnt = $sizes.sizes.Count
$sizesUpTo = 1
[int]$xMenuChoiceA = 0
while ( $xMenuChoiceA -lt 1 -or $xMenuChoiceA -gt $sizesCnt ){
foreach ($size in $sizes.sizes)
{
if ($defaultsize -eq $size.slug)
{
Write-Host ' '$sizesUpTo'. ' $size.slug ' (default)'
}
else
{
Write-Host ' '$sizesUpTo'. ' $size.slug
}
$sizesUpTo = $sizesUpTo + 1
}
[Int]$xMenuChoiceA = read-host "Select a size for your new droplet" }
$newsize = $sizes.sizes[$xMenuChoiceA -1].slug
##
# Backups
Clear-Host
[int]$xMenuChoiceA = 0
while ( $xMenuChoiceA -lt 1 -or $xMenuChoiceA -gt 2 )
{
if ($defaultbackups -eq 'true')
{
Write-Host ' 1. Enable Backups (Default)'
Write-Host ' 2. Disable Backups'
}
else
{
Write-Host ' 1. Enable Backups'
Write-Host ' 2. Disable Backups (Default)'
}
[Int]$xMenuChoiceA = read-host "Enable backups?"
}
Switch( $xMenuChoiceA )
{
1 { $newbackups = 'true' }
2 { $newbackups = 'false' }
}
##
# IPv6
Clear-Host
[int]$xMenuChoiceA = 0
while ( $xMenuChoiceA -lt 1 -or $xMenuChoiceA -gt 2 )
{
if ($defaultipv6 -eq 'true')
{
Write-Host ' 1. Enable IPv6 (default)'
Write-Host ' 2. Disable IPv6'
}
else
{
Write-Host ' 1. Enable IPv6'
Write-Host ' 2. Disable IPv6 (default)'
}
[Int]$xMenuChoiceA = read-host "Enable IPv6?"
}
Switch( $xMenuChoiceA )
{
1 { $newipv6 = 'true' }
2 { $newipv6 = 'false' }
}
##
# Private networking
Clear-Host
[int]$xMenuChoiceA = 0
while ( $xMenuChoiceA -lt 1 -or $xMenuChoiceA -gt 2 )
{
if ($defaultprivate_networking -eq 'true')
{
Write-Host ' 1. Enable Private Networking (default)'
Write-Host ' 2. Disable Private Networking'
}
else
{
Write-Host ' 1. Enable Private Networking'
Write-Host ' 2. Disable Private Networking (default)'
}
[Int]$xMenuChoiceA = read-host "Enable Private Networking?"
}
Switch( $xMenuChoiceA )
{
1 { $newprivate_networking = 'true' }
2 { $newprivate_networking = 'false' }
}
##
# And actually create it
$newdropletbody = @{name=$newdomain;region=$newregion;size=$newsize;image=$newimage;backups=$newbackups;ipv6=$newipv6;private_networking=$newprivate_networking;ssh_keys=@($sshid)} | ConvertTo-Json
$createddroplet = CreateDroplet -settings $newdropletbody
# Get the return droplet id
$id = $createddroplet.droplet.id
Write-Host ""
Write-Host "=========================================="
Write-Host ""
Write-Host " droplet - id: " $id
Write-Host " please wait while the droplet is build..."
Start-Sleep -s 30
Write-Host "`r"
Write-Host ""
# Get the IP address for the newly created droplet
$ip = GetIPAddress($id)
# Get IPv4 address
foreach ($ipv4 in $ip.droplet.networks.v4)
{
Write-Host " IPv4 address: " $ipv4.ip_address
}
# Get IPv6 address
foreach ($ipv6 in $ip.droplet.networks.v6)
{
Write-Host " IPv6 address: " $ipv6.ip_address
}
$records = ListAllRecords
foreach ($record in $records.domain_records)
{
if ($record.type -Match "A")
{
$recordid = $record.id
}
}
##
# Update IPv4 record with new droplet IP from the tempip (default: 127.0.0.1)
$newipv4record = @{data=$ipv4.ip_address} | ConvertTo-Json
UpdateRecord -data $newipv4record -recordid $recordid
##
# Create IPv6 record with new droplet IP
$newipv6record = @{name="@";data=$ipv6.ip_address;type="AAAA"} | ConvertTo-Json
CreateRecord -data $newipv6record
##
# Create default aliases (www)
$address = $newdomain + "."
CreateCNameRecord -cname "www" -address $address
####
#
# Run build script on new droplet
#
####
Write-Host " please wait while the droplet starts up..."
Start-Sleep -s 120
RunPutty
}
#######################################################################
#
Function ConnectToDroplet
{
Clear-Host
Write-Host "Connect to an existing droplet"
Write-Host "=============================="
[int]$xMenuChoiceA = 0
while ( $xMenuChoiceA -lt 1 -or $xMenuChoiceA -gt $droplets.Count ){
for($counter=0;$counter -lt $droplets.Length;$counter++)
{
$dropno = $counter + 1
Write-host $dropno - $droplets[$counter].name
}
[Int]$xMenuChoiceA = read-host "Connect to"
}
$usrdropnets = $droplets[$xMenuChoiceA -1].networks
foreach ($usrdropnet in $usrdropnets)
{
$ipv4 = $usrdropnet.v4
}
RunPutty
}
#######################################################################
#######################################################################
Write-Host ""
Write-Host "DigitalOcean API v2 - PowerShell"
Write-Host "================================"
# Check to see if we have a local SSH key (public \ private)
CheckLocalSSHKey
# Read the public SSH key
$localkey = $null
$localkeylines = Get-Content $scriptpath\public |?{ $_ -notmatch 'BEGIN SSH2 PUBLIC KEY' } |?{ $_ -notmatch 'Comment: ' } |?{ $_ -notmatch 'END SSH2 PUBLIC KEY' }
foreach ($keyline in $localkeylines)
{
$localkey = $localkey + $keyline
}
$localkey = "ssh-rsa " + $localkey + " PowerShell"
#break
# Read what public SSH keys we have with DigitalOcean
$sshid = CheckRemoteSSHKey
If ($sshid -eq $null) {
# Local Public SSH key not on DigitalOcean, lets upload it
Write-Host "Adding local SSH public key to your DigitalOcean account"
$sshid = UploadSSHKey
}
Write-Host "Using SSH key: PowerShell - Fingerprint: "$sshid
Write-Host ""
Write-Host "Account status"
Write-Host "=============="
Write-Host ""
##
# Droplets
$alldroplets = ListAllDroplets
$droplets = $alldroplets.droplets
Write-Host "Number of droplets:" $droplets.Count
##
# Domains
$alldomains = ListAllDomains
$domains = $alldomains.domains
Write-Host "Number of domains:" $domains.Count
If ($domains.Count -gt 0)
{
Write-Output $domains
}
If ($droplets.Count -gt 0)
{
[int]$xMenuChoiceA = 0
while ( $xMenuChoiceA -lt 1 -or $xMenuChoiceA -gt 4 ){
Write-host "1. Create a new droplet"
Write-host "2. Connect to an existing droplet"
[Int]$xMenuChoiceA = read-host "What would you like to do?" }
Switch( $xMenuChoiceA ){
1 {
# 1. Create a new droplet
CreateNewDroplet
}
2 {
# 2. Connect to an existing droplet
ConnectToDroplet
}
}
}
else
{
# No droplets created, let's create one!
CreateNewDroplet
}