首页 > 解决方案 > ec2 用户数据跳过 Powershell 块

问题描述

我将此脚本烘焙到 AWS-AMI 中,运行登录到 ec2-instance 的脚本可以工作,但是当从用户数据调用时,使用新名称加入 AD部分被跳过。

# Get Credentials from SSM
echo $new_name
$domain = "xxxx"
$username = (Get-SSMParameterValue -Name ad_domain_user).Parameters[0].Value
$password = (Get-SSMParameterValue -Name ad_domain_password -WithDecryption $True).Parameters[0].Value | ConvertTo-SecureString -asPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username,$password)

# Get VPC Tags for OU Name
$vpc_id=(Invoke-RestMethod -uri http://169.254.169.254/latest/meta-data/network/interfaces/macs/$mac/vpc-id)
$env_name=(aws ec2 describe-vpcs --vpc-ids $vpc_id --query 'Vpcs[*].[Tags[?Key==`Name`] | [0].Value]' --output text)
echo "Attempting to join AD for env_name:$env_name" | Out-File "C:\Program Files\Amazon\Ec2ConfigService\Logs\pslog.txt" -Append


# Join AD with newname
Try {
    if ("$env_name" -match "xxxx*") {
    Add-Computer -DomainName $domain -ComputerName $env:computername -newname $new_name -Credential $credential -Force -Restart -ErrorAction 'Stop'
    } elseif ("$env_name" -match "xxxx-xxxx-*") {
      $oupath = "OU=Member Servers,OU=xxxx-xxxx,OU=xxxx,DC=aws,DC=ABC,DC=ORG"
      Add-Computer -DomainName $domain -ComputerName $env:computername -newname $new_name -Credential $credential -Force -Restart -ErrorAction 'Stop' -OUpath$oupath
    } elseif ("$env_name" -match "xxxx-xxxx-*") {
      $oupath = "OU=Member Servers,OU=xxxx-xxxx,OU=xxxx,DC=aws,DC=ABC,DC=ORG"
      Add-Computer -DomainName $domain -ComputerName $env:computername -newname $new_name -Credential $credential -Force -Restart -ErrorAction 'Stop' -OUpath $oupath
    } 
} Catch  {
  echo $_.Exception | Out-File "C:\Program Files\Amazon\Ec2ConfigService\Logs\Error-JoinDomain.txt" -Append
}

## If Error File Exists try again
Try{
    If (Test-Path "C:\Program Files\Amazon\Ec2ConfigService\Logs\Error-JoinDomain.txt" -PathType Leaf) {
        if ("$env_name" -match "xxxx*") {
        Add-Computer -DomainName $domain -ComputerName $env:computername -newname $new_name -Credential $credential -Force -Restart -ErrorAction 'Stop'
        } else {
            Add-Computer -DomainName $domain -ComputerName $env:computername -newname $new_name -Credential $credential -Force -Restart -ErrorAction 'Stop' -OUpath $oupath
        }
    }
} Catch {
  echo $_.Exception | Out-File "C:\Program Files\Amazon\Ec2ConfigService\Logs\Error-JoinDomain.txt" -Append
  echo $_.Exception | Out-File "C:\Program Files\Amazon\Ec2ConfigService\Logs\pslog.txt" -Append
}

标签: windowsamazon-web-servicespowershellamazon-ec2

解决方案


推荐阅读