编程语言
首页 > 编程语言> > php – AWS STS角色与EC2 AssumeRole

php – AWS STS角色与EC2 AssumeRole

作者:互联网

我想将我的代码部署到EC2实例,但我不想在AWS Key和Secret中进行烘焙. AWS提供IAM服务,允许我为我的EC2实例分配一个角色,允许这些实例使用临时密钥进行访问.

我如何让它工作?我已经尝试使用SDK和StsClient来假设角色,但这会引发错误

User:  arn:aws:sts::XXXXXXXXXXXX:assumed-role/ROLE-NAME/INSTANCE No is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::XXXXXXXXXXXX:role/ROLE-NAME

阅读并且似乎STS请求需要使用凭证本身来执行角色分配?但我认为会使用EC2实例密钥?

解决方法:

是的,STS调用假定角色DOES需要凭据才能工作,但是它使用构造时提供的凭据,如果省略这些凭据,它不会回退到基于实例的凭证.

要使用基于实例的凭据进行调用,您需要使用以下内容:

$credentials = \Aws\Credentials\CredentialProvider::instanceProfile();

这将获取关联角色的名称,然后获取临时实例凭据.如果您知道角色的名称,则可以在构造函数中指定它

$credentials = \Aws\Credentials\CredentialProvider::instanceProfile(['profile' => 'role-name-here']);

您还需要更新角色的信任关系,以允许实例承担角色.我假设服务条目会这样做,但是改变它以引用IAM角色似乎工作

{
  "Effect": "Allow",
  "Principal": {
    "AWS": "arn:aws:iam::XXXXXXXXXXXX:role/ROLE-NAME"
  },
  "Action": "sts:AssumeRole"
}

(不要忘记在上一节结束时添加逗号})

现在将这些凭据传递给Sts客户端的构造函数,并且您对AssumeRole的调用应该成功返回.我的测试代码是:

$credentials = \Aws\Credentials\CredentialProvider::instanceProfile();

$stsClient = new \Aws\Sts\StsClient(['region' => 'eu-west-1', 'version' => 'latest', 'credentials' => $credentials]);

$ar = $stsClient->assumeRole(['RoleArn' => 'arn:aws:iam::XXXXXXXXXXXX:role/Ec2Role-queue', 'RoleSessionName' => 'test']);

$creds = $stsClient->createCredentials($ar);

var_dump($creds);

哪个输出:

object(Aws\Credentials\Credentials)#96 (4) {
  ["key":"Aws\Credentials\Credentials":private]=>
  string(20) "XXXXIYH36RJ5NZCDXXXX"
  ["secret":"Aws\Credentials\Credentials":private]=>
  string(40) "eXXXX+azLUNi9LjwyX4MkNI4rnEpFrG9pNNXXXXX"
  ["token":"Aws\Credentials\Credentials":private]=>
  string(308)     "FQoDYXdzEH4aDIa3Rx/onWIa4ArZeyLHAX+muL7zKt9trAQhMa98pkzpGGmOGa0N5UhCjX2GXQ3Dc2APElwlpCfr9F+J2k5igAeonadgrwAOC/OvEDv34i1JdmkaUjEE14S2hVGz2dXXXXegYra7kvx0cdoOjCPIFmXSZJeD1PR27lFyacH2x5+F1XKFugveiYCD63axATp4t8fq0K+EPjXXXX/wYKm5tJt7hYkCV7+tThLYFDPZ6NkXXXXjsSKkOw9u52yGJY4yD50y+liSprHH+/ZJyQppDIJcZbbpyBoojoeRvwU="
  ["expires":"Aws\Credentials\Credentials":private]=>
  int(1474580894)
}

希望这有助于其他人保存一些毛囊:)

标签:php,amazon-web-services,amazon-iam
来源: https://codeday.me/bug/20190824/1703051.html