-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add-PortainerStackFile.ps1
189 lines (152 loc) · 8.45 KB
/
Add-PortainerStackFile.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
<#
.SYNOPSIS
.Adiciona um Stack File no ambiente de Swarm através da API do Portainer usando o Metodo String
.PARAMETER PortainerURL
.Coloque o endereço HTTP do portainer do seu ambiente, por exemplo: https://portainer.mmgil.com.br/ ou http://DOCKERSERVER:9000
.PARAMETER StackName
Informe o nome do Stack para visualização no Portainer.
.PARAMETER StackFile
.Coloque o caminho do arquivo YAML.
.PARAMETER EndpointID
.(opcional) Seleciona o Endpoint que receberá o StackFile. Se este item não for definido o script ira randomizar os Endpoints existentes
.PARAMETER SwarmID
.(opcional) Seleciona o Swarm que receberá o StackFile.
.PARAMETER User
.Coloque o Usuario que tem acesso à API do Portainer. (necessário o parametro Password)
.PARAMETER Password
.Coloque a Senha do usuario que tem acesso à API do Portainer. (necessário o parametro Usuario)
.PARAMETER Credential
.Coloque um objeto PSCredential ou informa o nome de usuario para que sozinho ele pergunte a senha durante o processo. (Nao usar os parametros Usuario e Senha)
.EXAMPLE
C:\PS>$password = Read-Host -AsSecureString
C:\PS>Add-PortainerStackFile.ps1 -PortainerURL http://127.0.0.1:9000 -StackName wordpress -StackFile ./stack.yaml -User admin -Password $password
Cadastra um stack com nome wordpress usando o usuario admin e sua respectiva senha
.EXAMPLE
C:\PS>Add-PortainerStackFile.ps1 -PortainerURL http://127.0.0.1:9000 -StackName wordpress -StackFile ./objects/stack.yaml -Credential admin
Cadastra um stack com nome wordpress usando o usuario admin atraves do parametro Credential
.NOTES
Author: Moises de Matos Gil
Date: Junho 29, 2019
2019
#>
[CmdletBinding()]
param(
# PARAMETROS
[Parameter( Mandatory = $True, ValueFromPipeline = $True, position = 0, HelpMessage = "Informe o endereço HTTP do Portainer" )]
[string]$PortainerURL = $( Read-Host "PortainerURL" ),
[Parameter( Mandatory = $True, ValueFromPipeline = $True, position = 1, HelpMessage = "Informe o nome do Stack" )]
[string]$StackName = $( Read-Host "StackName" ),
[Parameter( Mandatory = $True, ValueFromPipeline = $True, position = 2, HelpMessage = "Informe o caminho do arquivo YAML" )]
[string]$StackFile = $( Read-Host "StackFile" ),
[Parameter( Mandatory = $false, position = 3, HelpMessage = "EndpointID é o ID do Endpoint cadastrado no Portainer" )]
[string]$EndpointID,
[Parameter( Mandatory = $false, position = 4, HelpMessage = "SwarmID é o ID do Swarm" )]
[string]$SwarmID,
[Parameter( Mandatory = $false, ParameterSetName='UserAsPlanText', position = 5, HelpMessage = "Informe o usuario que tem acesso a API do Portainer" )]
[string]$User,
[Parameter( Mandatory = $false, ParameterSetName='UserAsPlanText', position = 6, HelpMessage = "Informe a senha do usuario que tem acesso a API do Portainer" )]
[SecureString]$Password,
[Parameter( Mandatory = $false, ParameterSetName='SecureCredential', position = 5, HelpMessage = "Informea senha do usuario que tem acesso a API do Portainer" )]
[System.Management.Automation.PSCredential]$Credential
)
Begin {
Write-Host "$(Get-Date) - [INFO]: INICIANDO ACOES (Add-PortainerStackFile)" -ForegroundColor Cyan
Write-Host "$(Get-Date) - [INFO]: MOTANDO VARIAVEIS" -ForegroundColor Cyan
[uri]$portainerApiAuth = $PortainerURL+"/api/auth"
[uri]$portainerApiEndpoint = $PortainerURL+"/api/endpoints"
[uri]$stackUrl = $PortainerURL+"/api/stacks?type=1&method=string&endpointId=1"
if( -not([string]::IsNullOrEmpty($EndpointID)) ) {
[uri]$stackUrl = $PortainerURL+"/api/stacks?type=1&method=string&endpointId=$EndpointID"
}
Write-Host "$(Get-Date) - [INFO]: MOTANDO CREDENCIAIS DE ACESSO A API" -ForegroundColor Cyan
try {
if( -not([string]::IsNullOrEmpty($Credential)) ) {
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credential.Password)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
$jsonAuth = @{Username=$User;Password=$UnsecurePassword}
$jsonAuth = $jsonAuth | ConvertTo-Json
Write-Host "--> $(Get-Date) - [SUCESS]: USANDO PARAMETRO CREDENTIAL" -ForegroundColor Green
}
if( -not([string]::IsNullOrEmpty($User)) -and -not([string]::IsNullOrEmpty($Password)) ) {
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
$jsonAuth = @{Username=$User;Password=$UnsecurePassword}
$jsonAuth = $jsonAuth | ConvertTo-Json
Write-Host "--> $(Get-Date) - [SUCESS]: USANDO PARAMETROS USER E PASSWORD" -ForegroundColor Green
} else {
Write-Host "$(Get-Date) - [WARNING]: USER OU PASSWORD FALTANDO" -ForegroundColor Yellow
exit $LASTEXITCODE = 1
}
} catch {
Write-Host "--> $(Get-Date) - [ERROR]: DEU RUIM" -ForegroundColor Red
exit $LASTEXITCODE = 1
}
Write-Host "$(Get-Date) - [INFO]: OBTENDO JSON WEB TOKEN" -ForegroundColor Green
try {
$sessionVar = (Invoke-RestMethod -Uri $portainerApiAuth.AbsoluteUri -Method Post -Body $jsonAuth -ContentType "application/json").jwt
if( -not( [string]::IsNullOrEmpty($sessionVar) ) ) {
Write-Host "--> $(Get-Date) - [SUCESS]: JSON WEB TOKEN OBTIDO" -ForegroundColor Green
}
} catch {
Write-Host "--> $(Get-Date) - [ERROR]: DEU RUIM" -ForegroundColor Red
exit $LASTEXITCODE = 1
}
Write-Host "$(Get-Date) - [INFO]: OBTENDO INFORMACOES DO PORTAINER" -ForegroundColor Cyan
try {
if( [string]::IsNullOrEmpty($EndpointID) ) {
Write-Host "--> $(Get-Date) - [INFO]: RANDOMIZANDO O EndpointID" -ForegroundColor Cyan
$EndpointData = Invoke-RestMethod -Method Get -UseBasicParsing -Uri $portainerApiEndpoint.AbsoluteUri -Headers @{Authorization="Bearer $sessionVar"}
$EndpointID = Get-Random ($EndpointData | Where-Object Status -eq "1").ID
}
[uri]$portainerApiEndpoint = $PortainerURL+"/api/endpoints/$EndpointID/docker/swarm"
$dockerData = Invoke-RestMethod -Method Get -UseBasicParsing -Uri $portainerApiEndpoint.AbsoluteUri -Headers @{Authorization="Bearer $sessionVar"}
if( [string]::IsNullOrEmpty($SwarmID) ) {
$SwarmID = $dockerData.ID
}
Write-Host "--> $(Get-Date) - [SUCESS]: DADOS OBTIDOS" -ForegroundColor Green
} catch {
Write-Host "--> $(Get-Date) - [ERROR]: DEU RUIM" -ForegroundColor Red
exit $LASTEXITCODE = 1
}
Write-Host "$(Get-Date) - [INFO]: OBTENDO INFORMACOES DO ARQUIVO YAML" -ForegroundColor Cyan
try {
$FilePath = (Get-Location).Path+$StackFile
if( -not([string]::IsNullOrEmpty($StackFile)) -and (Test-Path $FilePath)) {
$FileBin = [IO.File]::ReadAllBytes($FilePath)
$FileEnc = [System.Text.Encoding]::GetEncoding('UTF-8').GetString($FileBin);
$FileEnc = $FileEnc -replace "`r`n","\n"
$FileEnc = $FileEnc -replace "`"", "'"
Write-Host "$(Get-Date) - [SUCESS]: CONTEUDO DO YAML OBTIDO" -ForegroundColor Green
} else {
Write-Host "$(Get-Date) - [WARNING]: YAML NÃO ENCONTRADO" -ForegroundColor Yellow
exit $LASTEXITCODE = 1
}
} catch {
Write-Host "--> $(Get-Date) - [ERROR]: DEU RUIM" -ForegroundColor Red
exit $LASTEXITCODE = 1
}
Write-Host "$(Get-Date) - [INFO]: PREPARANDO DADOS PARA ENVIAR" -ForegroundColor Cyan
$Headers = @{
Accept= "*/*";
"Authorization"="Bearer $sessionVar";
"User-Agent"="powershell/5.1";
"Cache-Control"="no-cache";
"accept-encoding"="gzip, deflate";
}
$jsonFile = @{
Name = $stackName;
SwarmID = $swarmID;
StackFileContent = "tempdata";
}
$jsonFile = $jsonFile | ConvertTo-Json
$jsonFile = $jsonFile -replace "tempdata",$FileEnc
Write-Host "$(Get-Date) - [INFO]: ENVIANDO REQUISIÇÃO PARA A API DO PORTAINER" -ForegroundColor Cyan
try {
$portainer = Invoke-RestMethod -Uri $stackUrl -Method Post -ContentType "application/json" -Body $jsonFile -Headers $Headers
$portainer
} catch {
$ErrorMessage = $_.Exception.Message
Write-Host "--> $(Get-Date) - [ERROR]: DEU RUIM -> $ErrorMessage" -ForegroundColor Red
exit $LASTEXITCODE = 1
}
}