Powershell 脚本自动安装 AWS CLI 并将 s3 上传的文件复制到 Windows 服务器

问题描述 投票:0回答:1

我开发了一个脚本,可以使用 .env 文件下载并安装 AWS CLI 和 Config。即使它已成功安装和配置,当我尝试将 s3 文件复制到服务器时,它无法下载该文件。当我在另一个 Powershell 会话中运行

aws --version
aws configure list
时,我得到了结果。

我希望在一个触发器中自动执行整个过程:下载 AWS CLI、安装它以及将文件下载到服务器。如何从 s3 下载文件?是否需要刷新路径或帮助我解决此问题?

提前致谢!

错误:

Error getting Downloading SolarWinds installer from S3 bucket...
 
Downloading s3://s3bucketlifecycle/Solarwinds-OOAE-Installer. Eval.exe to 
C:\Users\Administrator\Downloads\Solarwinds-00AE-Installer.Eval.e Download-SolarWinds Installer: 
Failed to download SolarWinds installer from S3. Error: The term 'aws' is not
recognized as the name of a cmdlet, function, script file, or operable program. 
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

我的代码:

function Ensure-AWSCLIInstalled {
    Write-Host "Checking if AWS CLI is installed..."
    $awsInstalled = $false

    try {
        # Check if AWS CLI is already installed
        if (Get-Command aws -ErrorAction SilentlyContinue) {
            Write-Host "AWS CLI is already installed."
            $awsInstalled = $true
        } else {
            Write-Host "AWS CLI not found. Installing AWS CLI v2..."

            # Set the path for downloading the AWS CLI installer
            $awsInstallerPath = Join-Path $DownloadDirectory "AWSCLIV2.msi"
            $AWSCLIInstallerURL = "https://awscli.amazonaws.com/AWSCLIV2.msi"

            # Enable TLS 1.2 for secure downloads
            [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

            # Check if the installer is already downloaded
            if (-Not (Test-Path $awsInstallerPath)) {
                Write-Host "Downloading AWS CLI installer..."
                try {
                    # Use Invoke-WebRequest to download the AWS CLI installer
                    Invoke-WebRequest -Uri $AWSCLIInstallerURL -OutFile $awsInstallerPath
                    Write-Host "AWS CLI installer downloaded successfully."
                } catch {
                    Write-Error "Failed to download AWS CLI. Error: $_"
                    throw
                }
            } else {
                Write-Host "AWS CLI installer already exists at $awsInstallerPath."
            }

            # Install AWS CLI using the downloaded MSI
            try {
                Write-Host "Installing AWS CLI..."
                Start-Process -FilePath "msiexec.exe" `
                              -ArgumentList "/i `"$awsInstallerPath`" /qn" `
                              -Wait -NoNewWindow -ErrorAction Stop
                Write-Host "AWS CLI installed successfully."
                $awsInstalled = $true
            } catch {
                Write-Error "Failed to install AWS CLI. Error: $_"
                throw
            }
        }

        # If AWS CLI was just installed, verify installation
        if ($awsInstalled) {
            # Check if AWS CLI is available in the current session
            if (-not (Get-Command aws -ErrorAction SilentlyContinue)) {
                if (-not $Restarted) {
                    Write-Host "AWS CLI installed."
                    
                    
                } else {
                    Write-Error "AWS CLI installed, but PowerShell still does not recognize it after restart."
                    throw "AWS CLI installation may require a system reboot or further troubleshooting."
                }
            } else {
                Write-Host "AWS CLI is now available in PowerShell."
            }
        }
    } catch {
        Write-Error "Failed to ensure AWS CLI installation. Error: $_"
        throw
    }
}
# Define function to read .env file and configure AWS CLI
function Configure-AWSCLIFromEnv {
    # Specify the path to your .env file
    $EnvFilePath = "C:\Users\Administrator\Downloads\.env"  

    # Check if the .env file exists
    if (-Not (Test-Path $EnvFilePath)) {
        Write-Host "The .env file was not found at the specified path: $EnvFilePath" -ForegroundColor Red
        return
    }

    # Load environment variables from the .env file
    $EnvVars = Get-Content $EnvFilePath | ForEach-Object {
        if ($_ -match "^\s*([^#].+?)=(.+)$") {
            [PSCustomObject]@{
                Key   = $matches[1].Trim()
                Value = $matches[2].Trim()
            }
        }
    } | Where-Object { $_ -ne $null }

    # Retrieve AWS credentials and region
    $AccessKey = ($EnvVars | Where-Object { $_.Key -eq 'AWS_ACCESS_KEY_ID' }).Value
    $SecretKey = ($EnvVars | Where-Object { $_.Key -eq 'AWS_SECRET_ACCESS_KEY' }).Value
    $Region    = ($EnvVars | Where-Object { $_.Key -eq 'AWS_DEFAULT_REGION' }).Value

    # Check if required variables are present
    if (-not $AccessKey -or -not $SecretKey -or -not $Region) {
        Write-Host "Missing required AWS environment variables." -ForegroundColor Red
        return
    }

    # Create a directory for AWS CLI config if it doesn't exist
    $AWSConfigDir = "C:\Users\Administrator\.aws"
    if (-not (Test-Path $AWSConfigDir)) {
        New-Item -ItemType Directory -Path $AWSConfigDir | Out-Null
    }

    # Create or overwrite the credentials file
    $CredentialsFile = "$AWSConfigDir\credentials"
    @"
[default]
aws_access_key_id = $AccessKey
aws_secret_access_key = $SecretKey
"@ | Set-Content -Path $CredentialsFile -Force

    # Create or overwrite the config file
    $ConfigFile = "$AWSConfigDir\config"
    @"
[default]
region = $Region
"@ | Set-Content -Path $ConfigFile -Force

    Write-Host "AWS CLI configured successfully using .env file!" -ForegroundColor Green
}
function Download-SolarWindsInstaller {
    Write-Host "Downloading SolarWinds installer from S3 bucket..."
    try {
        # Attempt to download the first file
        $result1 = aws s3 cp $S3BucketURL1 $SolarWindsOutput1 --quiet
        if (-not (Test-Path $SolarWindsOutput1)) {
            Write-Error "Failed to download $SolarWindsOutput1. The file does not exist."
            throw "Download failed for $SolarWindsOutput1"
        }

        # Attempt to download the second file
        $result2 = aws s3 cp $S3BucketURL2 $SolarWindsOutput2 --quiet
        if (-not (Test-Path $SolarWindsOutput2)) {
            Write-Error "Failed to download $SolarWindsOutput2. The file does not exist."
            throw "Download failed for $SolarWindsOutput2"
        }

        Write-Host "SolarWinds installer files downloaded successfully: $SolarWindsOutput1 and $SolarWindsOutput2"
        
    } catch {
        Write-Error "Failed to download SolarWinds installer from S3. Error: $_"
        throw
    }
}  
Ensure-AWSCLIInstalled
# Call the function to configure AWS CLI
Configure-AWSCLIFromEnv
Download-SolarWindsInstaller
amazon-web-services powershell aws-cli
1个回答
0
投票

看起来像是路径问题。安装 AWS CLI 时,系统/任何新进程的 PATH 都会更新,但 PATH 的更新不会自动应用于当前进程。

有多种方法可以解决此问题:

  • 使用 aws.exe 的绝对路径 - 将
    aws
    替换为
    "C:\Program Files\Amazon\AWSCLIV2\aws.exe"
    (或无论您安装它的位置)
  • 使用别名 -
    Set-Alias -Name aws -Value "C:\Program Files\Amazon\AWSCLIV2\aws.exe"
  • 修改当前powershell脚本的路径 -
    $env:Path += ";C:\Program Files\Amazon\AWSCLIV2"
    (由于路径中有空格,需要使用双引号)
© www.soinside.com 2019 - 2024. All rights reserved.