You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Bash脚本中设置AWS环境变量失效问题排查

问题

我编写了一个带可选参数-p的Bash脚本,希望将指定AWS profile的配置导出为当前Shell的环境变量。通过source执行脚本后,提示默认配置已设置,但执行echo $AWS_ACCESS_KEY_ID时无输出,请问问题出在哪里?

脚本代码如下:

#!/bin/bash

# This script is used to set an AWS profile for the current shell session.
# It is intended to be used with the AWS CLI and the AWS CLI v2.

usage() { echo "Usage: $0 [-p <string>]"; exit 1; }

while getopts "p:" options; do
    case "${options}" in
        p)
            p=${OPTARG}
            ;;

    esac
done

if [ -z "${p}" ]; then
  export AWS_ACCESS_KEY_ID=$(aws configure get default.aws_access_key_id)
  export AWS_SECRET_ACCESS_KEY=$(aws configure get default.aws_secret_access_key)
  export AWS_DEFAULT_REGION=$(aws configure get default.region)
  echo "Default profile set"
else
  aws configure list-profiles | grep -q "${p}"
  if [ $? -ne 0 ]; then
    echo "Profile ${p} not found"
    exit 1
  else
    export AWS_ACCESS_KEY_ID=$(aws configure get "${p}".aws_access_key_id)
    export AWS_SECRET_ACCESS_KEY=$(aws configure get "${p}".aws_secret_access_key)
    export AWS_DEFAULT_REGION=$(aws configure get "${p}".region)
  fi
fi

执行命令及输出:

source ./set-aws-profile
# 输出:
Default profile set
% echo $AWS_ACCESS_KEY_ID    
# 无任何输出
问题分析与解决
  • 核心问题:aws configure get命令参数格式错误
    你使用aws configure get default.aws_access_key_id的格式不符合AWS CLI规范,正确的写法应该是通过--profile参数指定profile,而非将profile名称拼接在配置项前。错误格式会导致命令返回空值,最终导出的环境变量为空,所以echo $AWS_ACCESS_KEY_ID无输出。

  • 修复后的脚本关键调整
    将所有aws configure get命令的格式修正,默认profile可省略--profile参数,指定profile时添加该参数:

    if [ -z "${p}" ]; then
      export AWS_ACCESS_KEY_ID=$(aws configure get aws_access_key_id)
      export AWS_SECRET_ACCESS_KEY=$(aws configure get aws_secret_access_key)
      export AWS_DEFAULT_REGION=$(aws configure get region)
      echo "Default profile set"
    else
      aws configure list-profiles | grep -q "${p}"
      if [ $? -ne 0 ]; then
        echo "Profile ${p} not found"
        exit 1
      else
        export AWS_ACCESS_KEY_ID=$(aws configure get aws_access_key_id --profile "${p}")
        export AWS_SECRET_ACCESS_KEY=$(aws configure get aws_secret_access_key --profile "${p}")
        export AWS_DEFAULT_REGION=$(aws configure get region --profile "${p}")
      fi
    fi
    
  • 额外优化建议

    • 可在导出变量前检查aws configure get的返回值,若为空则提示用户该profile配置项不完整,避免导出无效空变量。
    • 脚本开头增加aws命令存在性检查,防止因未安装AWS CLI导致的无意义错误。

内容的提问来源于stack exchange,提问作者A Simple Programmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:42:28