I have developed a script that will download and install the AWS CLI and Config with .env file. Even though it is installed and configured successfully, when I’m trying to copy the s3 file to the server it is unable to download the file. When I run the aws --version
and aws configure list
in another Powershell session I’m getting the result.
I’m wanting to automate the entire process in a single trigger: downloading AWS CLI, installing it, and downloading files to the server. How can I download the file from s3? Might it require a path refresh or something assist me to resolve this?
Thanks in Advance!
The error:
Error getting Downloading SolarWinds installer from S3 bucket...
Downloading s3://s3bucketlifecycle/Solarwinds-OOAE-Installer. Eval.exe to
C:UsersAdministratorDownloadsSolarwinds-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.
My code:
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:UsersAdministratorDownloads.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:UsersAdministrator.aws"
if (-not (Test-Path $AWSConfigDir)) {
New-Item -ItemType Directory -Path $AWSConfigDir | Out-Null
}
# Create or overwrite the credentials file
$CredentialsFile = "$AWSConfigDircredentials"
@"
[default]
aws_access_key_id = $AccessKey
aws_secret_access_key = $SecretKey
"@ | Set-Content -Path $CredentialsFile -Force
# Create or overwrite the config file
$ConfigFile = "$AWSConfigDirconfig"
@"
[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
2
Answers
It looks like a PATH issue. When your installing the AWS CLI the PATH gets updated for the system / any new processes, but updates to the PATH are not automatically applied to the current process.
Theres several ways of working around this issue:
aws
with"C:Program FilesAmazonAWSCLIV2aws.exe"
(or whever you installed it)Set-Alias -Name aws -Value "C:Program FilesAmazonAWSCLIV2aws.exe"
$env:Path += ";C:Program FilesAmazonAWSCLIV2"
(you need to use double quotes due to the space in the path)
To add to MisterSmith’s helpful answer, which explains the problem well:
If you’ve just run an installer that has modified the persistent value of the
Path
environment variable in the registry and you want to instantly see this modification, in the current session (process), you can refresh the value from the registry as follows:You can place this right inside the body of your
if ($awsInstalled) {
statement.The only small caveat is that if your in-session
$env:Path
value has been modified dynamically – e.g. via a$PROFILE
file – such modifications are lost; if that is a concern, you can append+ ";$env:Path"
to the above, though this will create duplicate entries (in the current session only), and entries won’t be in the same order as in future sessions.For comprehensive troubleshooting of
$env:Path
issues, see this answer.