Usuário com melhor resposta
Iniciando serviços via Azure Automation

Pergunta
-
Prezados, bom dia.
Preciso de um help.....
Montei um script em powershell para inicializar e desligar 03 servidores no azure e funcionam perfeitamente, porém tenho alguns serviços que precisam ser iniciados que estão em manual, e não consigo que esses serviços subam, me trás o seguinte erro:
Obs: O serviço existe no servidor com esse nome ( RabbitMQ )
Iniciando o servico RabbitMQ no servidor SERVER01
08/12/2015 17:25:25, Error: Get-Service : Cannot find any service with service name 'RabbitMQ'.
At StartBBMH:27 char:27
+
+ CategoryInfo : ObjectNotFound: (RabbitMQ:String) [Get-Service], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand
08/12/2015 17:25:26, Output
[12/8/2015 7:25:26 PM] -
Tentando iniciar o servico. ServiceName: '' - []
08/12/2015 17:25:26, Error: Start-Service : Failed to compare two elements in the array.
At StartBBMH:27 char:27Alguém pode me dar uma ajuda?...não gostaria de deixar esse serviço dentro do scheduller do servidor depois de ligado e sim no automation do azure depois que o servidor estiver ligado.
Respostas
-
Boa tarde.
Por falta de retorno do usuário, esta thread será encerrada.
Caso seja necessário, por favor, abrir uma thread nova.
Excelente semana.
- Marcado como Resposta Cristopher C I_ segunda-feira, 14 de dezembro de 2015 18:41
-
Olá Regram,
Seu script está quase todo certo, o problema é que você precisa conectar na VM no Azure antes de executar as operações com serviços internos da VM, a partir da linha 130 (##FUNÇÕES SERVICES). Para isso, eu sugiro que você utilize os cmdlets Connect-AzureVM e Invoke-command, isso permite que você execute um comando dentro da VM. Dá uma olhada nesse exemplo abaixo de como executar essa operação que está disponível na galeria do Technet.
https://gallery.technet.microsoft.com/scriptcenter/How-to-Use-a-PowerShell-59b2e28c
Qualquer dúvida, avise.
Se a resposta fornecida nessa thread ajudou na sua solução, não esqueça de marcar como resposta!
Abraço,
Gustavo Zimmermann Montesdioca - MTAC, MCT
Blog: www.gm9.com.br<# .SYNOPSIS This runbook calls a command inside of an Azure VM .DESCRIPTION This runbook connects into an Azure virtual machine and runs the PowerShell command passed in. It has a dependency on the Connect-AzureVM runbook to set up the connection to the virtual machine before the command can be run. .PARAMETER AzureSubscriptionName Name of the Azure subscription to connect to .PARAMETER AzureOrgIdCredential A credential containing an Org Id username / password with access to this Azure subscription. If invoking this runbook inline from within another runbook, pass a PSCredential for this parameter. If starting this runbook using Start-AzureAutomationRunbook, or via the Azure portal UI, pass as a string the name of an Azure Automation PSCredential asset instead. Azure Automation will automatically grab the asset with that name and pass it into the runbook. .PARAMETER ServiceName Name of the cloud service where the VM is located. .PARAMETER VMName Name of the virtual machine that you want to connect to .PARAMETER VMCredentialName Name of a PowerShell credential asset that is stored in the Automation service. This credential should have access to the virtual machine. .PARAMETER PSCommand PowerShell command that you want to run inside the Azure virtual machine. .EXAMPLE Invoke-PSCommandSample -AzureSubscriptionName "Visual Studio Ultimate with MSDN" -ServiceName "Finance" -VMName "WebServer01" -VMCredentialName "FinanceCredentials" -PSCommand "ipconfig /all" -AzureOrgIdCredential $cred .NOTES AUTHOR: System Center Automation Team LASTEDIT: Aug 14, 2014 #> Workflow Invoke-PSCommandSample { Param ( [parameter(Mandatory=$true)] [String] $AzureSubscriptionName, [parameter(Mandatory=$true)] [PSCredential] $AzureOrgIdCredential, [parameter(Mandatory=$true)] [String] $ServiceName, [parameter(Mandatory=$true)] [String] $VMName, [parameter(Mandatory=$true)] [String] $VMCredentialName, [parameter(Mandatory=$true)] [String] $PSCommand ) # Get credentials to Azure VM $Credential = Get-AutomationPSCredential -Name $VMCredentialName if ($Credential -eq $null) { throw "Could not retrieve '$VMCredentialName' credential asset. Check that you created this asset in the Automation service." } # Set up Azure connection by calling the Connect-Azure runbook. You should call this runbook after # every CheckPoint-WorkFlow to ensure that the management certificate is available if this runbook # gets interrupted and starts from the last checkpoint $Uri = Connect-AzureVM -AzureSubscriptionName $AzureSubscriptionName -AzureOrgIdCredential $AzureOrgIdCredential -ServiceName $ServiceName -VMName $VMName # Run a command on the Azure VM $PSCommandResult = InlineScript { Invoke-command -ConnectionUri $Using:Uri -credential $Using:Credential -ScriptBlock { Invoke-Expression $Args[0] } -Args $Using:PSCommand } $PSCommandResult }
- Sugerido como Resposta GustavoZimmermannMicrosoft employee terça-feira, 15 de dezembro de 2015 16:34
- Marcado como Resposta Regram terça-feira, 15 de dezembro de 2015 18:20
-
Olá Regram,
Você deve criar uma credencial na área de automation com o usuário e senha da VM, por exemplo, VMCredentialName. Depois, quando você for rodar o workflow, tem que executar:
# Get credentials to Azure VM $Credential = Get-AutomationPSCredential -Name $VMCredentialName
Por fim, quando for rodar, basta especificar a variável $Credential que já possui o usuário e senha da VM:
Invoke-command -ConnectionUri $Using:Uri -credential $Using:Credential -ScriptBlock {...}
Abraço,
Gustavo Zimmermann Montesdioca - MTAC, MCT
Blog: www.gm9.com.br- Marcado como Resposta Regram quinta-feira, 17 de dezembro de 2015 00:01
Todas as Respostas
-
Olá Regram,
Você pode enviar o script em PowerShell? Uma segunda pergunta, você está utilizando uma conta da máquina virtual para fazer a autenticação? Você precisa no mínimo utilizar o Start-PSSession para conectar na máquina virtual antes de executar o script.
Se a resposta fornecida nessa thread ajudou na sua solução, não esqueça de marcar como resposta!
Abraço,
Gustavo Zimmermann Montesdioca - MTAC, MCT
Blog: www.gm9.com.br- Sugerido como Resposta GustavoZimmermannMicrosoft employee quinta-feira, 10 de dezembro de 2015 19:24
-
Boa tarde.
Por falta de retorno do usuário, esta thread será encerrada.
Caso seja necessário, por favor, abrir uma thread nova.
Excelente semana.
- Marcado como Resposta Cristopher C I_ segunda-feira, 14 de dezembro de 2015 18:41
-
Olá Gustavo..., bom dia...
Preciso executar o script pronto dentro do servidor pelo menos....
o Servidor consigo ligar, depois de ligado quero chamado o script pronto em powershell no C:\temp\script.ps1 por exemplo que funciona executando dentro do servidor...
Porém quero que seja executado depois que o servidor ficar online no azure, e ir através do automation.
Segue o script que liga as VMS:
Obs: eu até coloquei os serviços para iniciarem junto no script, mais não funcionou.
workflow StartBBMH {
inlineScript {
$urlAP1 = "BBMH-AP1"
$urlWS1 = "BBMH-WS1"
$TEMPO_ESPERA_SERVICOS = 20
$TEMPO_ESPERA_SISTEMA = 120
$ServiceNames = @("BBMH-DB1","BBMH-AP1","BBMH-WS1") # Adicione os "ServiceName" de cada Servidor que vai ser ligado.
$HostNames = @("BBMH-DB1","BBMH-AP1","BBMH-WS1") # Adicione os "HostName" de cada Servidor que vai ser ligado.
$cred = Get-AutomationPSCredential –Name "BBM Automation"
Add-AzureAccount –Credential $cred
Select-AzureSubscription -SubscriptionName "Microsoft Azure Enterprise"###################################################################################################################
########################### FUNÇÕES PARA CHAMADAS DO AMBIENTE <<BBM>> HOMOLOGAÇÃO #################################
###################################################################################################################
##FUNÇÕES STOP/START AZURE
function WaitForStarted($vm)
{
do
{
$VMDetails = GetStatus($vm)
OutPutLog("Aguardando que a VM seja iniciada. ServiceName: '" + $vm.ServiceName + "' - VMName: '" + $vm.Name + "' - [" + $VMDetails.PowerState + "]")
Start-Sleep -s 5
}while($VMDetails.PowerState -ne "Started")
}
function WaitForStopped($vm)
{
do
{
$VMDetails = GetStatus($vm)
OutPutLog("Aguardando que a VM seja parada. ServiceName: '" + $vm.ServiceName + "' - VMName: '" + $vm.Name + "' - [" + $VMDetails.PowerState + "]")
Start-Sleep -s 1
}while($VMDetails.PowerState -ne "Stopped")
}
function GetStatus($vm)
{
Try
{
$VMDetails = Get-AzureVM $vm.ServiceName $vm.VmName -ErrorAction Stop
}
Catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
OutPutLog("Erro ao executar o comando 'Get-AzureVM'. Mensagem de erro: \n" + $ErrorMessage)
OutPutLog("Aguardando 5 segundos para tentar executar novamente.")
Start-Sleep -s 5
$VMDetails = GetStatus($vm)
}
return $VMDetails;
}
function StopVM($vm)
{
Try
{
OutPutLog("STOP - SN: " + $vm.ServiceName + " | VN: " + $vm.Name )
Stop-AzureVM -ServiceName $vm.ServiceName -Name $vm.Name -Force -ErrorAction Stop
}
Catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
OutPutLog("Erro ao executar o comando 'Stop-AzureVM'. Mensagem de erro: \n" + $ErrorMessage)
OutPutLog("Aguardando 5 segundos para tentar executar novamente.")
Start-Sleep -s 5
StopVM($vm)
}
}
function StartVM($vm)
{
Try
{
OutPutLog("START - SN: " + $vm.ServiceName + " | VN: " + $vm.Name )
Start-AzureVM -ServiceName $vm.ServiceName -Name $vm.Name -ErrorAction Stop
}
Catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
OutPutLog("Erro ao executar o comando 'Start-AzureVM'. Mensagem de erro: \n" + $ErrorMessage)
OutPutLog("Aguardando 5 segundos para tentar executar novamente.")
Start-Sleep -s 5
StartVM($vm)
}
}
function ProcessaAmbienteStart($vmsToProcess)
{
ForEach ($vm in $vmsToProcess) {
$vm = Get-AzureVM | where-object -FilterScript{$_.name -eq $vm -and $_.status -like 'Stopped*'}
OutPutLog($vm)
OutPutLog("Starting AzureVM. ServiceName: '" + $vm.ServiceName + "' - VMName: '" + $vm.Name + "'")
StartVM($vm)
WaitForStarted($vm)
}
}
function ProcessaAmbienteStop($vmsToProcess)
{
[array]::Reverse($vmsToProcess)
ForEach ($vm in $vmsToProcess) {
$vm = Get-AzureVM | where-object -FilterScript{$_.name -eq $vm -and $_.status -ne 'Stopped*' -and $_.status -ne 'StoppedDeallocated'}
OutPutLog($vm)
OutPutLog("Stopping AzureVM. ServiceName: '" + $vm.ServiceName + "' - VMName: '" + $vm.Name + "'")
StopVM($vm)
WaitForStopped($vm)
}
}
function OutPutLog($value)
{
$a = "[{0:G}] - " -f (get-date)
# Converter: Changed Write-Host to Write-Verbose. Write-Host is not usable in PowerShell Workflow
Write-Output $a $value
}
##FUNÇÕES SERVICES
function GetServiceStatus($parametro)
{
$service = Get-Service $parametro.ServiceName -ComputerName $parametro.Server
OutPutLog("Servico " + $parametro.ServiceName + " no servidor " + $parametro.Server + " [" + $service.Status + "]...")
return $service
}function StopServiceExecute($parametro)
{
Set-Service $parametro.ServiceName -ComputerName $parametro.Server -Status Stopped
}function StartServiceExecute($parametro)
{
OutPutLog("Tentando iniciar o servico. ServiceName: '" + $parametro.ServiceInstance.Name + "' - [" + $parametro.ServiceInstance.Status + "]")
Start-Service -InputObject $parametro.ServiceInstance
}function RestartService($parametro)
{
OutPutLog("Reiniciando o servico " + $parametro.ServiceName + " no servidor " + $parametro.Server + "...")
$service = GetServiceStatus($parametro)
if ($service.Status -eq "Running")
{
StopServiceExecute($parametro)
}
StartServiceExecute($parametro)
GetServiceStatus($parametro)
OutPutLog("Servico " + $parametro.ServiceName + " reiniciado com sucesso!")
}
function RestartIIS($parametro)
{
OutPutLog("Reiniciando o IIS no servidor " + $parametro.Server + "...")
iisreset $parametro.Server /restart
OutPutLog("IIS reiniciado com sucesso!")
}function StartService($parametro)
{
OutPutLog("Iniciando o servico " + $parametro.ServiceName + " no servidor " + $parametro.Server + "...")
$service = GetServiceStatus($parametro)
$parametro.ServiceInstance = $service
if ($service.Status -ne "Running")
{
StartServiceExecute($parametro)
GetServiceStatus($parametro)
OutPutLog("Servico " + $serviceName + " iniciado com sucesso!")
}
else
{
OutPutLog("Servico " + $serviceName + " ja esta rodando!")
}
}###################################################################################################################
################## CHAMADAS PARA INICIALIZAÇÃO/DESLIGAMENTO DO AMBIENTE <<BBM>> HOMOLOGAÇÃO #######################
##################################################################################################################### 1- INICIALIZAÇÃO DE VMs HOMOLOGAÇÃO
<#
OutPutLog("Iniciando")
OutPutLog("Maquinas: " + $HostNames)
ProcessaAmbienteStart($HostNames);
#>## 2 - INICIALIZAÇÃO DE SERVICES HOMOLOGAÇÃO
OutPutLog("Aguardando " + $TEMPO_ESPERA_SISTEMA + " segundos para que o sistema esteja pronto para ser ativado")
#Start-Sleep -s $TEMPO_ESPERA_SISTEMAStartService(@{Server = $urlAP1
ServiceName = "NCacheSvc"})OutPutLog("Aguardando " + $TEMPO_ESPERA_SERVICOS + " segundos para a subida do servico NCacheSvc")
Start-Sleep -s $TEMPO_ESPERA_SERVICOS
StartService(@{Server = $urlAP1
ServiceName = "RabbitMQ"})StartService(@{Server = $urlAP1
ServiceName = "Open Office Service"})StartService(@{Server = $urlWS1
ServiceName = "NCacheSvc"})OutPutLog("Aguardando " + $TEMPO_ESPERA_SERVICOS + " segundos para a subida do servico NCacheSvc")
Start-Sleep -s $TEMPO_ESPERA_SERVICOSStartService(@{Server = $urlAP1
ServiceName = "BBMNET WCFService Site"})StartService(@{Server = $urlAP1
ServiceName = "BBMNET WCFService Age"})StartService(@{Server = $urlAP1
ServiceName = "BBMNET WCFService File"})StartService(@{Server = $urlAP1
ServiceName = "CFinanceiroService"})
StartService(@{Server = $urlAP1
ServiceName = "SINAPService"})
RestartIIS(@{Server = $urlWS1
ServiceName = "W3SVC"})}
} -
Olá Regram,
Seu script está quase todo certo, o problema é que você precisa conectar na VM no Azure antes de executar as operações com serviços internos da VM, a partir da linha 130 (##FUNÇÕES SERVICES). Para isso, eu sugiro que você utilize os cmdlets Connect-AzureVM e Invoke-command, isso permite que você execute um comando dentro da VM. Dá uma olhada nesse exemplo abaixo de como executar essa operação que está disponível na galeria do Technet.
https://gallery.technet.microsoft.com/scriptcenter/How-to-Use-a-PowerShell-59b2e28c
Qualquer dúvida, avise.
Se a resposta fornecida nessa thread ajudou na sua solução, não esqueça de marcar como resposta!
Abraço,
Gustavo Zimmermann Montesdioca - MTAC, MCT
Blog: www.gm9.com.br<# .SYNOPSIS This runbook calls a command inside of an Azure VM .DESCRIPTION This runbook connects into an Azure virtual machine and runs the PowerShell command passed in. It has a dependency on the Connect-AzureVM runbook to set up the connection to the virtual machine before the command can be run. .PARAMETER AzureSubscriptionName Name of the Azure subscription to connect to .PARAMETER AzureOrgIdCredential A credential containing an Org Id username / password with access to this Azure subscription. If invoking this runbook inline from within another runbook, pass a PSCredential for this parameter. If starting this runbook using Start-AzureAutomationRunbook, or via the Azure portal UI, pass as a string the name of an Azure Automation PSCredential asset instead. Azure Automation will automatically grab the asset with that name and pass it into the runbook. .PARAMETER ServiceName Name of the cloud service where the VM is located. .PARAMETER VMName Name of the virtual machine that you want to connect to .PARAMETER VMCredentialName Name of a PowerShell credential asset that is stored in the Automation service. This credential should have access to the virtual machine. .PARAMETER PSCommand PowerShell command that you want to run inside the Azure virtual machine. .EXAMPLE Invoke-PSCommandSample -AzureSubscriptionName "Visual Studio Ultimate with MSDN" -ServiceName "Finance" -VMName "WebServer01" -VMCredentialName "FinanceCredentials" -PSCommand "ipconfig /all" -AzureOrgIdCredential $cred .NOTES AUTHOR: System Center Automation Team LASTEDIT: Aug 14, 2014 #> Workflow Invoke-PSCommandSample { Param ( [parameter(Mandatory=$true)] [String] $AzureSubscriptionName, [parameter(Mandatory=$true)] [PSCredential] $AzureOrgIdCredential, [parameter(Mandatory=$true)] [String] $ServiceName, [parameter(Mandatory=$true)] [String] $VMName, [parameter(Mandatory=$true)] [String] $VMCredentialName, [parameter(Mandatory=$true)] [String] $PSCommand ) # Get credentials to Azure VM $Credential = Get-AutomationPSCredential -Name $VMCredentialName if ($Credential -eq $null) { throw "Could not retrieve '$VMCredentialName' credential asset. Check that you created this asset in the Automation service." } # Set up Azure connection by calling the Connect-Azure runbook. You should call this runbook after # every CheckPoint-WorkFlow to ensure that the management certificate is available if this runbook # gets interrupted and starts from the last checkpoint $Uri = Connect-AzureVM -AzureSubscriptionName $AzureSubscriptionName -AzureOrgIdCredential $AzureOrgIdCredential -ServiceName $ServiceName -VMName $VMName # Run a command on the Azure VM $PSCommandResult = InlineScript { Invoke-command -ConnectionUri $Using:Uri -credential $Using:Credential -ScriptBlock { Invoke-Expression $Args[0] } -Args $Using:PSCommand } $PSCommandResult }
- Sugerido como Resposta GustavoZimmermannMicrosoft employee terça-feira, 15 de dezembro de 2015 16:34
- Marcado como Resposta Regram terça-feira, 15 de dezembro de 2015 18:20
-
Gustavo, obrigado pela ajuda.
Porém tenho um último erro e não consigo fechar esse ponto, com erro abaixo:
16/12/2015 17:43:26, Error: [teste.cloudapp.net] Connecting to remote server teste.cloudapp.net failed with the following error message
: Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (teste-7comm.cloudapp.net:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBrokenPreciso saber como imputar esse acesso dentro do script.
WinRM está ok, a porta 5985 e 5986 estão ok....já rodei o PS dentro do servidor e está ok...
Help.
Abraço
-
Olá Regram,
Você deve criar uma credencial na área de automation com o usuário e senha da VM, por exemplo, VMCredentialName. Depois, quando você for rodar o workflow, tem que executar:
# Get credentials to Azure VM $Credential = Get-AutomationPSCredential -Name $VMCredentialName
Por fim, quando for rodar, basta especificar a variável $Credential que já possui o usuário e senha da VM:
Invoke-command -ConnectionUri $Using:Uri -credential $Using:Credential -ScriptBlock {...}
Abraço,
Gustavo Zimmermann Montesdioca - MTAC, MCT
Blog: www.gm9.com.br- Marcado como Resposta Regram quinta-feira, 17 de dezembro de 2015 00:01