我有一个aws_scheduler_schedule,计划每分钟向Lambda函数发送一条消息,如下所示:
resource "aws_scheduler_schedule" "event_scheduler" {
name = "${var.environment}-${var.account_name}-${var.service_name}-scheduler"
flexible_time_window {
mode = "OFF"
}
schedule_expression = "rate(1 minute)"
target {
arn = var.lambda_arn
role_arn = aws_iam_role.iam_for_eventbridge.arn
input = jsonencode({
MessageBody = "check_expired"
})
}
}
我想限制aws_scheduler_schedule的aws_iam_role,这样它只允许上面的调度器使用:这是我的aws_iam_role代码:
resource "aws_iam_role" "iam_for_eventbridge" {
name = "${var.environment}-${var.account_name}-${var.service_name}-eventbridge-role"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "scheduler.amazonaws.com"
},
"Action": "sts:AssumeRole",
"Condition": {
"ArnEquals": {
"aws:SourceArn": "${aws_scheduler_schedule.event_scheduler.arn}"
}
}
]
}
EOF
}
我得到这个错误:
Error: Cycle: aws_scheduler_schedule。event_scheduler, aws_iam_role.iam_for_eventbridge
我理解这是因为角色需要调度器,而调度器需要角色。如何实现限制?
这是一个经典问题,可以通过为IAM角色名创建一个变量来解决:
data "aws_caller_identity" "current" {}
locals {
role_name = "${var.environment}-${var.account_name}-${var.service_name}-eventbridge-role"
role_arn = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/${local.role_name}"
}
resource "aws_scheduler_schedule" "event_scheduler" {
name = "${var.environment}-${var.account_name}-${var.service_name}-scheduler"
flexible_time_window {
mode = "OFF"
}
schedule_expression = "rate(1 minute)"
target {
arn = var.lambda_arn
role_arn = local.role_arn
input = jsonencode({
MessageBody = "check_expired"
})
}
}
resource "aws_iam_role" "iam_for_eventbridge" {
name = local.role_name
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "scheduler.amazonaws.com"
},
"Action": "sts:AssumeRole",
"Condition": {
"ArnEquals": {
"iam:AssociatedResourceARN": [
"${aws_scheduler_schedule.event_scheduler.arn}"
]
}
}
]
}
EOF
}