繁体   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