Một số hướng dẫn với EC2 Windows Server

  1. Tạo user cho Windows Server:
$password = Read-Host -AsSecureString ## Set password

New-LocalUser -Name "Administrator" -Password $password
Add-LocalGroupMember -Group Administrators -Member Administrator

Để có thể nó ăn cái user bên trên thì phải reboot server

shutdown -r -t 1

2. Nếu có nhu cầu đổi port:

Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -name "PortNumber"
Set-NetFirewallProfile -Profile Domain, Public, Private -Enabled False
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -name "PortNumber" -Value

3. Join domain và setup CloudWatch agent:

<runasLocalSystem>true</runasLocalSystem>

<powershell>

Set-TimeZone -Id "SE Asia Standard Time" -PassThru

$ErrorActionPreference = 'Stop'
$AdOuParameter = 'ad/organizational_unit_distinguished_name'
$AdFqdnParameter = 'ad/fully_qualified_domain_name'
$domainJoinCredentialSecretName = 'ad-credentials'
$cloudWatchConfigParameter = 'cloudwatch/windows_agent_configuration_db'

# Function to get SSM parameter value
function Get-SSMParameterValue {
    param (
        [string]$Name
    )
    $parameter = Get-SSMParameter -Name $Name -ErrorAction Stop
    return $parameter.Value
}

# Fetch and apply CloudWatch Logs agent configuration
Try {
    $cloudWatchConfig = Get-SSMParameterValue $cloudWatchConfigParameter
    $cloudWatchConfigPath = "C:\Program Files\Amazon\AmazonCloudWatchAgent\CloudWatchConfig.json"
    $cloudWatchConfig | Out-File -FilePath $cloudWatchConfigPath -Encoding ascii
    & "C:\Program Files\Amazon\AmazonCloudWatchAgent\amazon-cloudwatch-agent-ctl.ps1" -a fetch-config -m ec2 -c file:$cloudWatchConfigPath -s
    Write-Output " Successfully applied CloudWatch Logs agent configuration."
} Catch [System.Exception] {
    Write-Output " Failed to apply CloudWatch Logs agent configuration $_"
    Exit 1
}


If ((Get-CimInstance -ClassName 'Win32_ComputerSystem' -ErrorAction SilentlyContinue | Select-Object -ExpandProperty 'PartOfDomain') -eq $false) {

    Try {
        $targetOU = Get-SSMParameterValue $AdOuParameter
        $domainName = Get-SSMParameterValue $AdFqdnParameter
    } Catch [System.Exception] {
        Write-Output " Failed to get SSM Parameter(s) $_"
    }

    Try {
        $secretsManagerResponse = Get-SECSecretValue -SecretId $domainJoinCredentialSecretName
        $creds = $secretsManagerResponse.SecretString | ConvertFrom-Json
        if ((!$creds.username) -or (!$creds.password)) {
           throw " Secret Values not found in Secrets Manager secret. Ensure that Secret Values are configured properly."
        }
        $domainJoinUserName = $domainName + '\' + $creds.username
        $domainJoinPassword = ConvertTo-SecureString -String $($creds.password) -AsPlainText -Force
    } Catch [System.Exception] {
        Write-Output " Failed to get Secrets Manager secret $_"
    }

    $domainCredential = [PSCredential]::new($domainJoinUserName, $domainJoinPassword)

    Try {
        Write-Output " Attempting to join $env:COMPUTERNAME to Active Directory domain: $domainName and moving $env:COMPUTERNAME to the following OU: $targetOU."
        Add-Computer -ComputerName $env:COMPUTERNAME -DomainName $domainName -Credential $domainCredential -OUPath $targetOU -Force -Confirm:$false -PassThru -Restart:$false -ErrorAction Stop
    } Catch [System.Exception] {
        Write-Output " Failed to add computer to the domain $_"
        Exit 1
    }

    Write-Host " Going to restart"
    exit 3010
} Else {
    Write-Output " $env:COMPUTERNAME is already part of the Active Directory domain $domainName."
    Exit 0
}

</powershell>

script check join thành công chưa:

##########check if computer join domain or not ##########
if ((gwmi win32_computersystem).partofdomain -eq $true) {
    write-host -fore green "I am domain joined!"
} else {
    write-host -fore red "Ooops, workgroup!"
}

Set up CW:

{
    "logs": {
        "logs_collected": {
            "windows_events": {
                "collect_list": [
                    {
                        "event_format": "xml",
                        "event_levels": [
                            "WARNING",
                            "ERROR",
                            "CRITICAL"
                        ],
                        "event_name": "System",
                        "log_group_name": "${CloudWatchLogGroupName}",
                        "log_stream_name": "{instance_id}"
                    }
                ]
            }
        }
    },
    "metrics": {
        "append_dimensions": {
            "InstanceId": "$$${aws:InstanceId}"
        },
        "metrics_collected": {
            "LogicalDisk": {
                "measurement": [{
                    "name" : "% Free Space",
                    "rename" : "FreeDiskSpaceInPercent",
                    "unit" : "Percent"
                }],
                "metrics_collection_interval": 60,
                "resources": [
                    "*"    
                ]
            },
            "Memory": {
                "measurement": [
                    "% Committed Bytes In Use",
                    "Available MBytes"
                ],
                "metrics_collection_interval": 60
            }
        }
    }
}

Lưu ý: metrics ăn ra sẽ theo dimension, nên là autoscaling thì set riêng, mà chỉ instance id thì set riêng, nếu không tạo alarm không đủ applied dimension sẽ lỗi insufficient data ở metrics

Cho ASG:

{
    "logs": {
        "logs_collected": {
            "windows_events": {
                "collect_list": [
                    {
                        "event_format": "xml",
                        "event_levels": [
                            "WARNING",
                            "ERROR",
                            "CRITICAL"
                        ],
                        "event_name": "System",
                        "log_group_name": "${CloudWatchLogGroupName}",
                        "log_stream_name": "{instance_id}"
                    }
                ]
            }
        }
    },
    "metrics": {
        "append_dimensions": {
            "AutoScalingGroupName": "$$${aws:AutoScalingGroupName}"
        },
        "metrics_collected": {
            "LogicalDisk": {
                "measurement": [{
                    "name" : "% Free Space",
                    "rename" : "FreeDiskSpaceInPercent",
                    "unit" : "Percent"
                }],
                "metrics_collection_interval": 60,
                "resources": [
                    "*"    
                ]
            },
            "Memory": {
                "measurement": [
                    "% Committed Bytes In Use",
                    "Available MBytes"
                ],
                "metrics_collection_interval": 60
            }
        }
    }
}

4. Check log user data:

C:\ProgramData\Amazon\EC2-Windows\Launch\Log\Ec2Launch.log
C:\ProgramData\Amazon\EC2-Windows\Launch\Log\UserdataExecution.log
C:\ProgramData\Amazon\EC2Launch\log\agent.log

5. Để đổi password cho user:

Get-LocalUser

$Password = Read-Host "Enter the new password" -AsSecureString # Nhập password

$UserAccount = Get-LocalUser -Name "Administrator" # đổi tên người dùng nếu cần
$UserAccount | Set-LocalUser -Password $Password

shutdown -r -t 1

6. Gắn EBS:

Nếu có attach windows ebs, thì phải make it available

Stop-Service -Name ShellHWDetection
Get-Disk | Where PartitionStyle -eq 'raw' | Initialize-Disk -PartitionStyle MBR -PassThru | New-Partition -AssignDriveLetter -UseMaximumSize | Format-Volume -FileSystem NTFS -NewFileSystemLabel "Volume Label" -Confirm:$false
Start-Service -Name ShellHWDetection

7. thay đổi drive letter và drive label:


Get-Disk
Get-Partition -DiskNumber 1 | Set-Partition -NewDriveLetter D
# Lưu ý: https://stackoverflow.com/questions/68644394/powershell-set-partition-newdriveletter-returns-set-partition-the-requested-ac
# Link:  https://pureinfotech.com/change-drive-letter-powershell-windows-10/
Get-Volume
Set-Volume -DriveLetter D -NewFileSystemLabel "DATA"
# Link: https://pureinfotech.com/change-drive-label-windows-10/

6. Extend Windows file system sau khi resizing volume:

# Variable specifies the disk drive to extend
$drive_letter = "C"

# Script gets the partition sizes, and resizes the volume
$size = (Get-PartitionSupportedSize -DriveLetter $drive_letter)
Resize-Partition -DriveLetter $drive_letter -Size $size.SizeMax