Created
March 13, 2025 14:47
-
-
Save sagarpanchal/240beba3c42994ed18facc39edb416d3 to your computer and use it in GitHub Desktop.
Npm Aws code-artifact integration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function aws_login { | |
local CONFIG_FILE="$HOME/.aws/config" | |
# Extract SSO session name | |
local SSO_SESSION | |
SSO_SESSION=$(awk -F ' = ' '/^\[sso-session / {gsub(/^\[sso-session |\]$/, "", $0); print; exit}' "$CONFIG_FILE") | |
# Extract profile name and other required details | |
local PROFILE | |
PROFILE=$(awk -F ' = ' '/^\[profile / {gsub(/^\[profile |\]$/, "", $0); print; exit}' "$CONFIG_FILE") | |
local ACCOUNT_ID | |
ACCOUNT_ID=$(awk -F ' = ' '$1 == "sso_account_id" {print $2}' "$CONFIG_FILE") | |
local REGION | |
REGION=$(awk -F ' = ' '$1 == "region" {print $2}' "$CONFIG_FILE") | |
if [[ -z "$SSO_SESSION" || -z "$PROFILE" || -z "$ACCOUNT_ID" || -z "$REGION" ]]; then | |
echo "Error: Could not extract required AWS SSO and profile details." | |
return 1 | |
fi | |
# Run aws sso login | |
echo "[INFO] logging into aws sso" | |
aws sso login --sso-session "$SSO_SESSION" | |
# Run aws codeartifact login | |
echo "[INFO] logging into aws codeartifacts for npm" | |
aws codeartifact login --tool npm --repository NugetNPMRepo --domain oceantg --domain-owner "$ACCOUNT_ID" --profile "$PROFILE" --region "$REGION" | |
} | |
# Use the alias | |
alias aws-login="aws_login" | |
function npm_wrapper { | |
local cmd=$1 | |
shift # Remove the first argument (npm or npx) and pass the rest | |
# Create a unique temporary file for output | |
local tmp | |
tmp=$(mktemp /tmp/${cmd}_last_output.XXXXXX) | |
local exit_code | |
script -q /dev/null command $cmd "$@" | tee "$tmp" | |
exit_code=${pipestatus[1]} | |
# Read and remove the temporary file | |
local output | |
output=$(<"$tmp") | |
rm "$tmp" | |
# If an error occurred and the output includes "error code E401", run aws-login and retry | |
if [[ $output == *"E401"* ]]; then | |
echo "[INFO] 401 detected. Running aws-login" | |
aws-login | |
script -q /dev/null command $cmd "$@" | |
exit_code=$? | |
fi | |
return $exit_code | |
} | |
# Use the wrapper function for both npm and npx | |
alias npm="npm_wrapper npm" | |
alias npx="npm_wrapper npx" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment