我有一组EC2实例,它们通过实例配置文件被授予从AWS秘密管理器读取秘密的权限。这用于引导服务器,但是在引导完成后,其他用户可能在此服务器上运行任意作业。
我可以在引导期间从运行实例中以编程方式删除与秘密管理器相关的IAM策略吗?
否则,我如何在引导阶段(通过user_data
脚本)获得一些短暂的凭据,这些凭据只能访问一次秘密,然后不允许任意作业能够访问?
这可以通过在引导完成后删除特权来实现。为了做到这一点,我们首先需要在实例中添加一些权限。
下面的Terraform片段显示了一个IAM策略,该策略允许实例解除与实例配置文件的关联。
执行disassociate命令需要DescribeIamInstanceProfileAssociations
获取association-id
。
data "aws_iam_policy_document" "instance-disassociate-iam-profile" {
statement {
sid = ""
effect = "Allow"
resources = ["*"]
actions = [
"ec2:DisassociateIamInstanceProfile",
"ec2:DescribeIamInstanceProfileAssociations"
]
}
}
设置了权限后,引导脚本的末尾可以删除与该实例关联的实例配置文件。
# Downgrade the IAM role now that we've finished accessing the secrets manager :)
association_id=$(aws ec2 describe-iam-instance-profile-associations
--filters 'Name=instance-id,Values='$(ec2metadata --instance-id)
| jq -r '.IamInstanceProfileAssociations[0].AssociationId')
aws ec2 disassociate-iam-instance-profile --association-id ${association_id}
如果你有多个关联,你可能需要更多的过滤器,等等。这展示了如何在只有一个关联的情况下删除关联。因为这是在ubuntu上,我们使用ec2metadata
命令,但如果你是在AL2或类似的系统上,你可以使用ec2-metadata
命令代替。
一旦解关联发生,EC2实例的权限就减少了:
$ aws secretsmanager get-secret-value --secret-id SUPER_SECRET
Unable to locate credentials. You can configure credentials by running "aws configure".