![](/img/trans.png)
[英]Ansible AWS using a role_arn with ansible playbook not giving permissions
[英]Python boto3 how to parse role_arn from AWS_CONFIG_FILE?
我有一个 AWS 配置文件,我的 boto3 session 可以通过 AWS_CONFIG_FILE 环境变量访问它。 配置文件如下所示:(多帐户环境)
[profile profile1]
credential_source Environment
region=us-east-whatever
role_arn=arn:aws:iam:<ACCOUNT NUMBER 1>:role/all-profiles-same-role-name
[profile profile2]
credential_source Environment
region=us-east-whatever
role_arn=arn:aws:iam:<ACCOUNT NUMBER 2>:role/all-profiles-same-role-name
[profile profileN]
credential_source Environment
region=us-east-whatever
role_arn=arn:aws:iam:<ACCOUNT NUMBER N>:role/all-profiles-same-role-name
在我的 Python 代码中,我尝试使用这样的东西设置 RefreshableCredentails(boto3 方法):(不包括完整代码,因为我认为问题主要是关于解析 aws_config_file):
def __get_session_credentials(self):
# hardcode one role_arn for now but need to variablize
session_ttl=3000
aws_role_arn="arn:aws:iam::<ACCOUNT NUM>:role/all-profiles-same-role-name
...
我可以以某种方式在每个配置文件的基础上从配置文件中解析“role_arn”以使 function 更具可扩展性吗? 我该怎么做?
您可以使用标准库中的configparser
模块:
import configparser
from pathlib import Path
def main():
path_to_config = Path(Path.home(), ".aws", "config")
parser = configparser.ConfigParser()
parser.read(path_to_config)
for profile in parser.sections():
if "role_arn" in parser[profile]:
print(
"Found profile", profile, "with role_arn", parser[profile]["role_arn"]
)
if __name__ == "__main__":
main()
不过,我不会在这里分享 output;-)
我认为如果您配置一个新的环境变量AWS_PROFILE
,您的问题就可以解决
根据 boto3 文档[1] :
AWS_PROFILE
要使用的默认配置文件(如果有)。 如果未指定值,Boto3 会尝试搜索共享凭证文件和默认配置文件的配置文件。
和 aws-cli(仅供参考)文档[2] :
AWS_PROFILE
指定 AWS CLI 配置文件的名称以及要使用的凭证和选项。 这可以是存储在凭据或配置文件中的配置文件的名称,或者是使用默认配置文件的默认值。
如果已定义,此环境变量将覆盖在配置文件中使用名为 [default] 的配置文件的行为。 您可以使用 --profile 命令行参数覆盖此环境变量。
所以,只需将此环境变量设置为profileN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.