我已经安装了AWS-CLI在我的本地机器上。我已经创建了一个配置文件。但我不知道如何从我的代码中的配置文件中获取区域。
代码
var credentials = new AWS.SharedIniFileCredentials({ profile: node_env });
console.log(credentials);
我可以获取访问 ID
,但无法获取该区域。还有其他方法获取区域吗?
最佳答案
当您使用 aws configure
设置凭证时,它会创建两个文件
~/.aws/config
~/.aws/credentials
区域和输出信息保存在 ~/.aws/config
下,access_key
和 secret_key
存储在 ~/.aws/credentials
下。
使用aws-cli
aws configure getregion --profile test
它将返回配置文件测试的区域。
但是 Nodejs 的情况有点不同,它 does not set region当您打印凭据时,您会得到空区域。
The SDK for JavaScript doesn't select a Region by default. However, you can set the Region using an environment variable, a shared config file, or the global configuration object.
所以你有两个选择。
使用共享配置文件
Much like the shared credentials file lets you store credentials for use by the SDK, you can keep your Region and other configuration settings in a shared file named config that is used by SDKs. If the AWS_SDK_LOAD_CONFIG environment variable has been set to a truthy value, the SDK for JavaScript automatically searches for a config file when it loads. Where you save the config file depends on your operating system:
Linux、macOS 或 Unix 用户:~/.aws/config
Windows 用户:C:\Users\USER_NAME\.aws\config
如果您还没有共享配置文件,您可以在指定目录中创建一个。在以下示例中,配置文件设置区域和输出格式。
[default]
region=us-west-2
output=json
setting-region与 loading-node-credentials-shared
设置区域的优先顺序
区域设置的优先顺序如下:
如果将某个区域传递给客户端类构造函数,则使用该区域。如果没有,那么...
如果在全局配置对象上设置了某个区域,则使用该区域。如果没有,那么...
如果
AWS_REGION
环境变量是真值,则使用该Region。如果没有,那么...如果
AMAZON_REGION
环境变量为真值,则使用该Region。如果没有,那么...如果
AWS_SDK_LOAD_CONFIG
环境变量设置为真实值,并且共享凭证文件(~/.aws/credentials 或 AWS_SHARED_CREDENTIALS_FILE 指示的路径)
包含已配置配置文件的区域,则使用该区域。如果没有,那么...如果
AWS_SDK_LOAD_CONFIG
环境变量设置为真实值,并且配置文件(~/.aws/config 或 AWS_CONFIG_FILE 指示的路径)
包含已配置配置文件的区域,则使用该区域。
或者您可以使用 SharedIniFileCredentials
方法将 ~/.aws/config
作为文件读取,而不是作为 NodeJS 中的 AWS 配置。
关于javascript - 使用 Node 从 AWS CLI 获取区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57768714/