Python脚本中的AWS ecr get-login-password凭证问题



我正在编写一个python脚本来将docker映像推送到Elastic Container Registry。在下面的脚本中,我使用环境变量以编程方式设置AWS CLI凭据,因为我的凭据是为每次调用生成的。

env = os.environ.copy()
env['AWS_DEFAULT_REGION'] = "my-region"
env['AWS_ACCESS_KEY_ID'] = "ACCESS_KEY_ID_I_KNOW_WORKS"
env['AWS_SECRET_ACCESS_KEY'] = "SECRET_KEY_I_KNOW_WORKS"
#Working credentials can be seen in this command output, proving(?) that they are usable
subprocess.call(f'aws configure list', shell=True, env=env)
#This fails despite 'aws configure list' showing the working credentials
subprocess.call(f'aws ecr get-login-password --region my-region', shell=True, env=env)

这个脚本给出了最后一个命令的错误:

An error occurred (UnrecognizedClientException) when calling the GetAuthorizationToken operation: The security token included in the request is invalid.

现在,在bash中直接运行每个命令(导出环境变量)就可以了,但是脚本不行。我还尝试了几种使用存储在~/中的配置文件的变体。但是没有一个能给我更好的结果。

我不知道为什么AWS CLI似乎不接受凭据。你知道我错过了什么吗?提前谢谢。

终于想通了

我提到过我的凭据是在每次调用时生成的。

结果是我不能立即使用这些凭证,我必须在生成和使用之间等待大约10秒。

所以,我只是在创建和使用之间添加了一个睡眠:
creds = generateCredentials()
time.sleep(10)
env = os.environ.copy()
env['AWS_DEFAULT_REGION'] = "my-region"
env['AWS_ACCESS_KEY_ID'] = creds.aws_access_key_id
env['AWS_SECRET_ACCESS_KEY'] = creds.secret_access_key
...

这就解释了为什么当我手动放入凭证时,它们似乎可以工作,而实际上我只是比脚本慢。

另一种选择是在脚本开始时请求凭据,然后做其他事情,如运行构建,然后返回并使用它们,如果这对你有用的话。