Friday, 14 December 2018

Multi-Boot Strap Powershell again

<powershell>
$Role = "Powerweb"
$Environment = "PROD-A"
$DeployScriptPath = '\\10.130.0.215\temp_share\tmp\userdata-scripts'
New-Item C:\Install -type directory
Copy-Item $DeployScriptPath\ec2-userdata-13082018.ps1 C:\Install
& C:\Install\ec2-userdata-13082018.ps1.ps1 -Role $Role -Environment $Environment

</powershell>

<powershell>
Param(
   [string]$Role, [string]$Environment
)

Set-ExecutionPolicy -Force Unrestricted

#Set source directory for install and pre-requisite files
#
$source = "C:\Deployment"
if(!(Test-Path -Path $source )){
    New-Item -ItemType directory -Path $source
}

#start Logging
Start-Transcript -Path $source\Bootstrap.txt

#initialize new Volumes Win 2016
if((Test-Path -Path C:\ProgramData\Amazon\EC2-Windows\Launch\Scripts)){
    C:\ProgramData\Amazon\EC2-Windows\Launch\Scripts\InitializeDisks.ps1
}

If (Test-Path -Path "D:\"){
  Set-Volume -DriveLetter D -NewFileSystemLabel Data
}

If (Test-Path "E:\"){
  Set-Volume -DriveLetter E -NewFileSystemLabel Logs
}

#Install Windows Tools and Features
#
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
Install-Module -Name 'Carbon' -AllowClobber -Force

Import-Module ServerManager

Install-WindowsFeature Web-Server,Web-Http-Redirect,Web-Custom-Logging,Web-Log-Libraries,Web-Request-Monitor,Web-Dyn-Compression,Web-Basic-Auth,Web-IP-Security,Web-Url-Auth,Web-Windows-Auth,Web-Net-Ext45,Web-Asp-Net45,Web-AppInit,Web-ISAPI-Ext,Web-ISAPI-Filter,Web-Mgmt-Console,Web-Mgmt-Tools,Web-Mgmt-Compat,Web-Metabase,Web-Lgcy-Mgmt-Console,Web-Lgcy-Scripting,Web-WMI,Web-Scripting-Tools,Web-Mgmt-Service,smtp-server
Add-WindowsFeature NET-WCF-HTTP-Activation45, NET-HTTP-Activation

Import-Module 'Carbon'
Import-Module AWSPowerShell

#Copy pre-requisite Files and Scripts
#
robocopy /MIR /NFL /NDL /Z \\10.130.0.215\Common\Scripts\Common $source
robocopy /MIR /NFL /NDL /Z \\10.130.0.215\temp_share\tmp\configs $source\API
robocopy /MIR /NFL /NDL /Z \\10.130.0.215\Common\Tools\AppDynamics\dotNetAgent $source\AppDynamics

Copy-Item \\10.130.0.215\Common\Tools\ConnectPerformanceCounterCategoryInstall.exe $source -Verbose

#Functions will be split from the main file and used later
#
#Import Functions
#. $source\IIS.ps1
#. $source\Misc.ps1
. $source\InstallOctopus.ps1
#. $source\Functions.ps1


#Set default region for AWS cli tools
#
$instance_az = Invoke-RestMethod -uri http://169.254.169.254/latest/meta-data/placement/availability-zone
$instance_region = $instance_az.Substring(0,$instance_az.Length-1)
Set-DefaultAWSRegion -Region $instance_region

#Update Hostname Tag in AWS
#
$hostname = $env:COMPUTERNAME
$aws_instance =  Invoke-RestMethod -uri http://169.254.169.254/latest/meta-data/instance-id

$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "Hostname"
$tag.Value = $hostname
New-EC2Tag -Resource $aws_instance -Tag $tag

### Will have a join domain function in CFN
#
#Add instance to AD
$username = 'tt.local\softixdomainaccount'
$password = 'PA$$word70'
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
Add-Computer -DomainName tt.local -OUPath "OU=AWS,OU=Computers,OU=TT-Managed,DC=tt,DC=local" -Force -Credential $cred
"complete join to domain"

### Add domain users to local Administrators
#
$users = @("softixdomainaccount","Appadmin Security","TT Server Desktop Administrators")

$group = [ADSI]("WinNT://$hostname/Administrators,group")
$groupname = $group.PSBase.Name

<#
#
#$user1 = [ADSI]("WinNT://tt.local/softixdomainaccount")
#$user2 = [ADSI]("WinNT://tt.local/Appadmin Security")
#$$user3 = [ADSI]("WinNT://tt.local/TT Server Desktop Administrators")
#$users = $user1,$user2,$user3
#"add users to admin group"
#"$user1"
#"$user2"
#"$user3"
#
#>

$membersObj = @($group.psbase.Invoke("Members"))
$members = ($membersObj | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)})

ForEach ($user in $users) {
$userads = [ADSI]("WinNT://tt.local/$user")
$name = $userads.PSBase.Name
If ($members -contains $userads.PSBase.Name ){
     Write-Host "$name exists in the group $groupname"
}
Else {
       Write-Host "$name not exists in the group $groupname"
       "add users to admin group"
       "$name has been added to the $group"
       $group.PSBase.Invoke("Add",$userads.PSBase.Path)
}
}

#Set instance System Locale
#
Import-Module International

tzutil /s "AUS Eastern Standard Time"

$currentlist = Get-WinUserLanguageList
$currentlist | ForEach-Object {if(($_.LanguageTag -ne "en-AU") -and ($_.LanguageTag -ne "en-US")){exit}}

Set-WinUserLanguageList en-AU -Force
Set-WinSystemLocale en-AU
Set-Culture en-AU

#Enable Remoting
#
Enable-PSRemoting

#Create Default Site Directories
New-Item D:\Ticketek\ -type directory
New-Item E:\Weblogs -type directory
New-Item E:\Logs -type directory  # to do, work out how to do permissions to .\IIS_IUSRS
New-Item D:\Common\LoadBalancer -type directory
New-Item D:\Common\LoadBalancer -Name "index.html" -type file

#Change ACL for new volumes
#
$Paths = @("E:\","D:\")

ForEach ($Path in $Paths) {
  $Acl = (Get-Item $Path).GetAccessControl('Access')
  $Ar = New-Object  system.security.accesscontrol.filesystemaccessrule("everyone","modify","ContainerInherit,Objectinherit","none","Allow")
  $Acl.SetAccessRule($Ar)
  $Acl | Set-Acl $Path
}


Remove-WebAppPool '.NET v4.5'
Remove-WebAppPool '.NET v4.5 Classic'

Set-WebConfigurationProperty "/system.applicationHost/sites/siteDefaults" -name logfile.directory -value E:\Weblogs

$p = (Get-Item IIS:\AppPools\DefaultAppPool)
$p.managedRunTimeVersion = ''
$p | Set-Item

Stop-Website -name 'Default Web Site'
Rename-Item 'IIS:\Sites\Default Web Site' 'Load Balancer'
Set-ItemProperty 'IIS:\Sites\Load Balancer' -Name bindings -Value @{protocol="http";bindingInformation="*:8000:"}
Set-ItemProperty 'IIS:\Sites\Load Balancer' -Name physicalPath -Value D:\Common\LoadBalancer
Set-ItemProperty 'IIS:\Sites\Load Balancer' -Name applicationPool -Value 'DefaultAppPool'
Set-ItemProperty 'IIS:\Sites\Load Balancer' -Name id -Value 1
Start-Website -name 'Load Balancer'

New-NetFirewallRule -DisplayName 'Load Balancer' -Direction Inbound -Protocol TCP -LocalPort 8000 -Action Allow
New-NetFirewallRule -DisplayName 'Octopus Tentacle' -Direction Inbound -Protocol TCP -LocalPort 10933 -Action Allow
New-NetFirewallRule -DisplayName 'SMB' -Direction Inbound -Protocol TCP -LocalPort 445 -Action Allow


Copy-Item \\10.130.0.215\Common\Utilities\IncreasePerformanceCounters.ps1 $source -Verbose

$regfiles = @("db_aliases-production.reg","localisation_au.reg","tls_1_2_change_for_NET_Apps.reg")
$utilpath = "\\10.130.0.215\Common\Utilities"
Foreach ($regfile in $regfiles)
{
  Copy-Item $utilpath\$regfile $source -Verbose
  regedit /s $source\$regfile
}

C:\Deployment\IncreasePerformanceCounters.ps1

##Install Chrome and notepad++
write-host "########## Installing Git, Notepad++ and Chrome ##########"

$nppUrl = "https://notepad-plus-plus.org/repository/7.x/7.5.8/npp.7.5.8.Installer.x64.exe"
$chromeUrl = "http://dl.google.com/chrome/install/375.126/chrome_installer.exe"
$nppoutput = "C:\Deployment\npp.exe"
$chromeoutput = "C:\Deployment\ChromeSetup.exe"
$wc = New-Object System.Net.WebClient
$wc.Headers.Add("user-agent", "PowerShell")
$wc.DownloadFile($nppUrl, $nppoutput)
$wc.DownloadFile($chromeUrl, $chromeoutput)

Start-Process -FilePath "C:\Deployment\npp.exe" /S -Wait
Start-Process -FilePath "C:\Deployment\ChromeSetup.exe" -Args "/silent /install" -Verb RunAs -Wait
#end installation

## Install connect Performance Counter for all App with connection to the Origin
#
C:\Deployment\ConnectPerformanceCounterCategoryInstall.exe
#end installation

#Set config path for SumoLogic and AppDynamics
#
$rolecfg = $Role.replace(' ','')
$configPath = "C:\Deployment\API\$rolecfg"

#Installing and configuring Sumo Logic
#
write-host "########## Install Sumologic Collector ##########"
#
New-Item -ItemType directory -Path $source\Sumo
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]'Tls,Tls11,Tls12'
Invoke-WebRequest 'https://collectors.sumologic.com/rest/download/win64' -outfile 'C:\Deployment\Sumo\SumoCollector.exe'

C:\Deployment\Sumo\SumoCollector.exe -console -q "-VskipRegistration=true" "-Vsumo.accessid=suf85JGx5cAUUq" "-Vsumo.accesskey=p32H3qFUErPdSQuxsgVBVT6VeVT6aXKqm1e3sRebNiWgJ95QUB8lYfKkWMmn3E2W" "-Vsources=" + $configPath + "\\" + $rolecfg + ".json"
timeout 30
start-service sumo-collector

#Installing and configuring AppDynamics
#
write-host " Installing App Dynamics..."
#
#Installs the .NET and Machine AppDynamics Agents
#Function requires the config parameter config to be specified. This dictates which .xml configuration file it will use to create the correct Application Tier for the dotNetAgent.
#
#Install-AppDynamics -config $Role
#

$tempDir = "C:\windows\temp"
$sourcePath = "C:\Deployment\AppDynamics"
$installer = "$sourcePath\dotNetAgentSetup.msi"
$configFile = $configPath + "\" + $rolecfg + ".xml"

$options = "/q /norestart /l $tempDir\AgentInstaller.log AD_SetupFile=$configFile"
$msiInstall = "/i $installer $options"
echo "start-process msiexec $msiInstall -wait"
start-process msiexec $msiInstall -wait
iisreset /noforce

## disabling Real Time Scan for Windows Defender - Applicable only for Windows 16 (Defender is not available on Windows 12)
Set-MpPreference -DisableRealtimeMonitoring 1 #toggle Real-time Protection ON/OFF
$preferences = Get-MpPreference #gets preferences for the Windows Defender scans and updates
$status = $preferences.DisableRealtimeMonitoring #store current status of Real-time Protection in $status
Write-host " "
if ($status) {
   Write-host "Real-time Protection is  OFF"
} Else {
   Write-host "Real-time Protection is  ON"
}
Write-host " "

####*********** SOME EXTRAS ***********###

#### Install a tentacle and create a role for Octopus server Using Cloud Formation ####

If (($Role -ne "NONE") -and ($Environment -ne "NONE")) {
Write-Host "Role is " $Role
Write-Host "Environment is " $Environment
InstallOctopus -Role $Role -Environments $Environment
}

# Stop logging
Stop-Transcript

Restart-Computer -Force

</powershell>

No comments:

Post a Comment