我想要允許讀取自己的標簽但不允許讀取任何其他資源的 AWS 實體?通常,允許實體做某事的想法由 iam_role 和 aws_profile_instance 表示,但是在為角色撰寫策略時,我不能參考實體的 ARN,因為它會創建回圈。
這是有道理的:通常,Terraform 按順序創建資源,一旦創建,它就不會重新訪問它們。我想要的是創建沒有 iam 角色的實體,并在創建實體后將角色附加到實體。
Terraform 有可能嗎?
編輯:(最小的例子):
; cat problem.tf
resource "aws_instance" "problem" {
instance_type = "t2.medium"
ami = "ami-08d489468314a58df"
iam_instance_profile = aws_iam_instance_profile.problem.name
}
resource "aws_iam_policy" "problem" {
name = "problem"
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{ Effect = "Allow"
Action = ["ssm:GetParameters"]
Resource = [aws_instance.problem.arn]
}
]
})
}
resource "aws_iam_role" "problem" {
name = "problem"
managed_policy_arns = [aws_iam_policy.problem.id]
# Copy-pasted from aws provider documentation. AWS is overcomplicated.
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "ec2.amazonaws.com"
}
},
]
})
}
resource "aws_iam_instance_profile" "problem" {
name = "problem"
role = aws_iam_role.problem.name
}
; terraform apply -refresh=false
Acquiring state lock. This may take a few moments...
Releasing state lock. This may take a few moments...
?
│ Error: Cycle: aws_iam_instance_profile.problem, aws_instance.problem, aws_iam_policy.problem, aws_iam_role.problem
│
│
?
uj5u.com熱心網友回復:
出現這里的問題是因為您使用managed_policy_arns速記將策略附加到宣告角色的同一資源中的角色。在簡單的情況下,這種簡寫可能很方便,但它也會產生回圈問題,正如您在此處所見,因為它導致角色參考策略,而不是策略參考角色。
好訊息是,您可以通過在相反的方向宣告該關系來避免回圈,方法是使用單獨的
The policy won't be connected to the role until both the role and the instance are both created, so it's important to consider here that the software running in the instance might start up before the role's policy is assigned, and so it should be prepared to encounter access violation errors for some time after boot and keep trying periodically until it succeeds, rather than aborting at the first error.
If this is part of a shared module that's using the functionality of the EC2 instance as part of the abstraction it's creating, it can help the caller of the module to be explicit about that hidden dependency on the aws_iam_role_policy by including it in any output values that refer to behavior of the EC2 instance that won't work until the role policy is ready. For example, if the EC2 instance is providing an HTTPS service on port 443 that won't work until the policy is active:
output "service_url" {
value = "https://${aws_instance.example.private_ip}/"
# Anything which refers to this output value
# should also wait until the role policy is
# created before taking any of its actions,
# even though Terraform can't "see" that
# dependency automatically.
depends_on = [aws_iam_role_policy.example]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347920.html
上一篇:從地圖中獲取不同值的串列
