簡體   English   中英

無法將aws-cli命令存儲到bash中的變量中

[英]Impossible to store aws-cli command into a variable in bash

這是問題所在

我有一個腳本,該腳本檢查是否配置了AWS憑證,然后獲取配置的區域並創建VPC。

這里是:

#!/usr/bin/env bash

if [ -z "$(aws configure get aws_access_key_id)" ]; then
    echo "AWS credentials not configured. Aborting.";
    exit 1;
fi;

export REGION=$(aws configure get region)

export vpcId=$(aws --region "$REGION" ec2 create-vpc --cidr-block 10.0.0.0/24 --query 'Vpc.VpcId' --output text)

問題是,即使直接從控制台執行aws configure get region也會返回$REGION為空: us-west-1 在腳本內部,它什么也不返回。

另一個奇怪的事情是:

export vpcId=$(aws ec2 create-vpc --cidr-block 10.0.0.0/24 --query 'Vpc.VpcId' --output text)返回VPC ID,並將其成功存儲在vpcId變量中。

這有什么問題: export REGION=$(aws configure get region) 是否在那里發生了異步I / O( aws configure get從配置文件讀取數據, aws ec2 create-vpc從互聯網讀取數據)?

這是一開始的整個腳本:

#!/usr/bin/env bash

# Test availability of aws-cli
hash aws 2>/dev/null
if [ $? -ne 0 ]; then
    echo >&2 "'aws' command line tool required, but not installed. Aborting.";
    exit 1;
fi;

# Test availability of the AWS AccessKey
if [ -z "$(aws configure get aws_access_key_id)" ]; then
    echo "AWS credentials not configured. Aborting.";
    exit 1;
fi;

# Directory
export EC2_STARTER_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
export WORKING_DIR="$( pwd )"

# File
export AWS_CONFIG_FILE="${WORKING_DIR}/.aws"
CREATE_VPC="${EC2_STARTER_DIR}/setup/create_vpc.sh"

# Defaults
export REGION="$( aws configure get region )" # Empty variable

嘗試采購bash腳本,因為內部導出會將現有的內容導出到子shell。

source your_script 

或者您也可以嘗試以下方法:

 ./your_script  # Same as source command

這是一開始的整個腳本:

#!/usr/bin/env bash

aws configure get region # Output us-west-1

# Test availability of aws-cli
hash aws 2>/dev/null
if [ $? -ne 0 ]; then
    echo >&2 "'aws' command line tool required, but not installed. Aborting.";
    exit 1;
fi;

aws configure get region # Output us-west-1

# Test availability of the AWS AccessKey
if [ -z "$(aws configure get aws_access_key_id)" ]; then
    echo "AWS credentials not configured. Aborting.";
    exit 1;
fi;

aws configure get region # Output us-west-1

# Directory
export EC2_STARTER_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
export WORKING_DIR="$( pwd )"

aws configure get region # Output us-west-1

# File
export AWS_CONFIG_FILE="${WORKING_DIR}/.aws"
CREATE_VPC="${EC2_STARTER_DIR}/setup/create_vpc.sh"

aws configure get region # No output

原來, AWS_CONFIG_FILE是aws使用的環境變量,用於將aws configure get region命令從中讀取的配置文件設置為路徑。 因此,以下行export AWS_CONFIG_FILE="${WORKING_DIR}/.aws"只會覆蓋它。 (感謝@ 123)。

對於這個愚蠢的問題,我們深表歉意。 調試時,我不認為該錯誤是簡單的變量名沖突,而是因為其他原因。 我的錯...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM