cloudconeapi.psm1

<#

.DESCRIPTION
cloudcone.com vps Management tools
HTTPs://api.cloudcone.com/
.EXAMPLE
PS> CloudConeapi -compute -JsonKeyPath /xxx.json -name info
Get information on your compute instance

PS> CloudConeapi -compute -JsonKeyPath /xxx.json -name info -id xxxx
use id
.EXAMPLE
PS> CloudConeapi -compute -KEY xxxx -HASH xxxx -Name list

Get a list of all compute instances registered in your account

.EXAMPLE
PS> CloudConeapi -compute -KEY xxxx -HASH xxxx -Name create

Deploy a new compute instance
#>
 

function Set-CloudCone {
[CmdletBinding()]
param(
    [Parameter(ParameterSetName="Set1")]
    [Parameter(ParameterSetName="Set3")]
    [Switch]$Compute,
    [Parameter(ParameterSetName="Set2")]
    [Parameter(ParameterSetName="Set4")]
    [Switch]$Dedicated,
    [ValidateScript({
                    if (!($JsonKeyPath)) {
                    if($_ -match '^[A-zA-Z0-9]{10,}$'){
                    $True
                    }else {
                    throw "key error"
                    }}
                    else {
                    throw "This parameter cannot coexist with the [JsonKeyPath] parameter"
                    }
                }
    )]
    [Parameter(ParameterSetName="Set1")]
    [Parameter(ParameterSetName="Set2")]
    [string]$KEY,
    [ValidateScript({
                    if ($Key) {
                    if($_ -match '^[A-zA-Z0-9]{30,}$'){
                    $True
                    }else {
                    throw "error hash"
                    }}
                    else {
                    throw "This parameter depends on the [key] parameter"
                    }
                }
    )]
    [Parameter(ParameterSetName="Set1")]
    [Parameter(ParameterSetName="Set2")]
    [string]$HASH,
    [ValidateScript({
                    if (!($Key)) {
                    if(test-path -path $_){
                    $True
                    }else {
                    throw "error path"
                    }}
                    else {
                    throw "This parameter cannot coexist with the [key] parameter"
                    }
                }
    )]
    [Parameter(ParameterSetName="Set3")]
    [Parameter(ParameterSetName="Set4")]
    [string]$JsonKeyPath,
    [ValidateScript({

                $compute = @('graphs','boot','reboot','shutdown','Destroy','info','status','list-os','list',"reinstall","create","resize","reset-password")
                $dedicated = @('hypervisors','boot','graphs','info','reboot','shutdown','status')

                    if ($compute+$dedicated -contains $_) {
                    $True}
                    else {
                    throw "-name value error"
                    }
                }
    )]
    [ArgumentCompleter( {
            param ( $commandName,
                    $parameterName,
                    $wordToComplete,
                    $commandAst,
                    $fakeBoundParameters
            )

            $possibleValues = @{
                compute = @('graphs','boot','reboot','shutdown','Destroy','info','status','list-os','list',"reinstall","create","resize","reset-password")
                dedicated = @('hypervisors','boot','graphs','info','reboot','shutdown','status')
            }
            if ($fakeBoundParameters.ContainsKey('compute'))
            {
                $possibleValues['compute'] | Where-Object {
                    $_ -like "$wordToComplete*"
                }
            }
            elseif ($fakeBoundParameters.ContainsKey('dedicated'))
            {
                $possibleValues['dedicated'] | Where-Object {
                    $_ -like "$wordToComplete*"
                }
            }
        } )]
    [Parameter(Mandatory=$false)]
    [string] $Name
    )

    DynamicParam
    {
    $notid=@('list','list-os','create','hypervisors')
if ($notid -notcontains $Name){
        $Attributes = New-Object System.Management.Automation.ParameterAttribute
        $Attributes.Mandatory = $false
        $Attributes.ParameterSetName = '__AllParameterSets'
        $Attributes.ValueFromPipeline = $false
        $Attributes.ValueFromPipelineByPropertyName = $false

        $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
        $AttributeCollection.Add($Attributes)
        #$AttributeCollection.Add((New-Object System.Management.Automation.ValidateSetAttribute('')))

        $ParamDictionary = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameterDictionary
        $dname="id"
        $ParamDictionary.Add($dname,(New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter($dname,[int32],$AttributeCollection)))

        return $ParamDictionary
    }
    }

BEGIN {
    $id = $PSBoundParameters.id
    if(!($key) -or !($hash) -and  !($JsonKeyPath)){
    Write-Host -ForegroundColor Black -BackgroundColor White '缺少参数,请使用-KEY和-HASH参数,或使用-jsonkeypath指定key.json文件'
    break}
    $notid = $PSBoundParameters.notid
    Write-Verbose -Message "开始执行 $Name " -Verbose
} # end BEGIN

PROCESS {
if($key){
$headers = @{
    "App-Secret" = "$KEY"
    "Hash" = "$HASH"
}
}elseif($jsonkeypath){
get-content -path $jsonkeypath|convertfrom-json |ForEach-Object{$headers+=@{'App-Secret'=$_.'App-Secret';hash=$_.hash}}
}
$notid=@('list','list-os','create','hypervisors') #
$ispost=@('Create','Reinstall','reset-password','Resize') #请求方式:post

function set-api ($u,$m,$b=''){
Invoke-RestMethod -Uri $u -Method $m -Headers $headers -body $b
}
if($compute){
$uri='https://api.cloudcone.com/api/v1/compute/'
}else{
$uri='https://api.cloudcone.com/api/v1/dedicated/'
}


if($compute) {
if($notid -notContains $name){
$instances=(set-api -U "${uri}list/instances" -M get).__data.instances
if($instances.length -eq 0){write-output 'error,compute not found.';break}elseif($instances.length -eq 1){$id=$instances.id}elseif($instances.id -notContains $id ){
$instances | Format-Table id,distro,created,ips|out-host
Write-Host "请输入" -ForegroundColor DarkBlue -NoNewline; Write-Host "id:" -ForegroundColor black -BackgroundColor White -NoNewline; [int32]$id=Read-Host;
if($instances.id -notContains $id ){
Write-Host -ForegroundColor Black -BackgroundColor White "你输入的id无效,请重新执行命令"
break}
}
$uri="${uri}${id}/"
}

$uriall=switch ($name){
list-os {"${uri}list/os"}
list {"${uri}$name/instances"}
reset-password {"${uri}reset/pass"}
default {"${uri}${name}"}
}

if($name -eq "resize"){
$post=@('cpu','ram','disk')
$nm=@("1","1024","20")
$note=@('CPU 核心数(1-16)','RAM in MB(512-16000)','硬盘空间(GB)')
}
if($name -eq "reinstall"){
$post=@('os')
$nm=@("54")
$note=@('操作系统编号')
}
if($name -eq "reset-password"){
$post=@('password',"reboot")
$nm=@(";:.-/_:-,……-","false")
$note=@('修改密码')
}
if($name -eq "create"){
$note=@('主机名','CPU 核心数(1-16)','RAM in MB(512-16000)','硬盘空间(GB)','ipv4数量(1-100)','操作系统','启用 SSD (1/0)','启用专用网络 (1/0)','启用 IPv6 (on/off)')
$post=@('hostname','cpu','ram','disk','ips','os','ssd','pvtnet','ipv6')
$nm=@("test.com",1,1024,20,1,54,1,1,"on")
}
if($ispost -Contains $Name){
for($i=0;$i -lt ($post.Length);$i++){
if ("os" -eq $post[$i]){(set-api -U "${uri}list/os" -M get).__data|out-host}
$message="`r$($note[$i]) 默认值:$($nm[$i])"
if(-not($origpos)){
$origpos = $host.UI.RawUI.CursorPosition
$origpos.y=$origpos.y - 1
}
$read=Read-Host -prompt $message
$host.UI.RawUI.CursorPosition=$origpos
write-host (' '*($message.length +15+$read.length)) -nonewline
$var=if($read){$read}else{$nm[$i]}
$var1=$var1 + ("&" + $post[$i] + "=" + $nm[$i])
}
$var2=$var1 -replace "^."

$headers = $headers += @{'Content-Type' = 'application/x-www-form-urlencoded'}
#Invoke-RestMethod $uriall -Method post -Headers $headers -body "$var2"|ForEach-Object{$_.__data}
(set-api -U $uriall -M post -b $var2).__data

<#
$start=get-date
if("create" -Contains $Name ){
do{
if(-not($origpos)){
$origpos = $host.UI.RawUI.CursorPosition
$origpos.y=$origpos.y - 1
}
$getid=(set-api -U "${uri}list/instances" -M get).__data.instances|Sort-Object -property created -bottom 1
[int]$time=(new-timespan -start $start -end (get-date)).TotalSeconds
write-host "请稍后,正在获取密码。时间:$time"
$host.UI.RawUI.CursorPosition=$origpos
start-sleep 10}until((New-TimeSpan -start $($getid.created) -end $(get-date)).TotalSeconds -lt 120)
}
set-api -U "${uri}$($getid.id)/info" -M get|Select-Object mainip,"initial_root_password"|out-host
#>

}




if ($ispost -notContains $Name){
(set-api -U $uriall -M get).__data
}


    } elseif($dedicated) {
    write-host '未完成'
    break
if($notid -notContains $name){
$instances=(set-api -U "${uri}list/instances" -M get).__data.instances
if($instances.length -eq 0){write-output 'error,compute not found.';break}elseif($instances.length -eq 1){$id=$instances.id}elseif($instances.id -notContains $id ){
$instances | Format-Table id,distro,created,ips|out-host
Write-Host "请输入" -ForegroundColor DarkBlue -NoNewline; Write-Host "id:" -ForegroundColor black -BackgroundColor White -NoNewline; [int32]$id=Read-Host;
if($instances.id -notContains $id ){
Write-Host -ForegroundColor Black -BackgroundColor White "你输入的id无效,请重新执行命令"
break}
}
$uri="${uri}${id}/${name}"
}
set-api -U "${uri}" -M get

    }
} # end PROCESS
}