Как настроить azurerm_role_management_policy в области ресурса?

Я создал различные модули Terraform для управления областью действия на трех разных уровнях. Подписка, группа ресурсов и ресурс. Первые два работают нормально, поскольку они довольно универсальны по своей природе. Однако в последнем случае я столкнулся с проблемой с областью действия. Может ли кто-нибудь подсказать, как следует настроить область на определенном уровне ресурса, чтобы я мог настроить правила azurerm_role_management_policy?



resource "azurerm_role_management_policy" "role_policy_resource" {
  for_each = toset(var.role_definition_names)
  scope              = data.azurerm_key_vault.statickv.id           # Scope of the role management policy
  role_definition_id = data.azurerm_role_definition.roles[each.value].id  # ID of the role definition

  active_assignment_rules {
    expire_after = var.role_policy_rules.active_assignment_rules_expire_after  # Expiration period for active assignments
  }

  eligible_assignment_rules {
    expiration_required = false  # Whether expiration is required for eligible assignments
  }

  activation_rules {
    maximum_duration = var.role_policy_rules.activation_rules_maximum_duration  # Maximum duration for activation
    require_approval = var.role_policy_rules.activation_rules_require_approval   # Whether approval is required for activation
    dynamic "approval_stage" {
      for_each = var.role_policy_rules.activation_rules_require_approval ? ["this"] : []
        content{
          primary_approver {
          object_id = var.role_policy_rules.activation_rules_approver_object_id  # Primary approver for activation
          type = var.role_policy_rules.activation_rules_approver_type  # Type of the primary approver
          }
        }
    }
  }
  notification_rules {
    eligible_assignments {
      admin_notifications {
        notification_level    = var.role_policy_rules.notification_rules_eligible_assignments_admin_notifications_notification_level                     # Notification level for admin notifications
        default_recipients    = var.role_policy_rules.notification_rules_eligible_assignments_admin_notifications_default_recipients                          # Whether to use default recipients for admin notifications
        additional_recipients = var.role_policy_rules.notification_rules_eligible_assignments_admin_notifications_additional_recipients       # Additional recipients for admin notifications
      }
      approver_notifications {
        notification_level    = var.role_policy_rules.notification_rules_eligible_assignments_approver_notifications_notification_level                    # Notification level for approver notifications
        default_recipients    = var.role_policy_rules.notification_rules_eligible_assignments_approver_notifications_default_recipients                          # Whether to use default recipients for approver notifications
        additional_recipients = var.role_policy_rules.notification_rules_eligible_assignments_approver_notifications_additional_recipients       # Additional recipients for approver notifications
      }
      assignee_notifications {
        notification_level    = var.role_policy_rules.notification_rules_eligible_assignments_assignee_notifications_notification_level                     # Notification level for assignee notifications
        default_recipients    = var.role_policy_rules.notification_rules_eligible_assignments_assignee_notifications_default_recipients                         # Whether to use default recipients for assignee notifications
        additional_recipients = var.role_policy_rules.notification_rules_eligible_assignments_assignee_notifications_additional_recipients
      }
    }
    eligible_activations {
      admin_notifications {
        notification_level    = var.role_policy_rules.notification_rules_eligible_activations_admin_notifications_notification_level                     # Notification level for assignee notifications
        default_recipients    = var.role_policy_rules.notification_rules_eligible_activations_admin_notifications_default_recipients                         # Whether to use default recipients for assignee notifications
        additional_recipients = var.role_policy_rules.notification_rules_eligible_activations_admin_notifications_additional_recipients
      }
      assignee_notifications {
        notification_level    = var.role_policy_rules.notification_rules_eligible_activations_assignee_notifications_notification_level                     # Notification level for assignee notifications
        default_recipients    = var.role_policy_rules.notification_rules_eligible_activations_assignee_notifications_default_recipients                        # Whether to use default recipients for assignee notifications
        additional_recipients = var.role_policy_rules.notification_rules_eligible_activations_assignee_notifications_additional_recipients
      }
    }
    active_assignments {
      admin_notifications {
        notification_level    = var.role_policy_rules.notification_rules_active_assignments_admin_notifications_notification_level                     # Notification level for assignee notifications
        default_recipients    = var.role_policy_rules.notification_rules_active_assignments_admin_notifications_default_recipients                         # Whether to use default recipients for assignee notifications
        additional_recipients = var.role_policy_rules.notification_rules_active_assignments_admin_notifications_additional_recipients
      }
      approver_notifications {
        notification_level    = var.role_policy_rules.notification_rules_active_assignments_approver_notifications_notification_level                     # Notification level for assignee notifications
        default_recipients    = var.role_policy_rules.notification_rules_active_assignments_approver_notifications_default_recipients                          # Whether to use default recipients for assignee notifications
        additional_recipients = var.role_policy_rules.notification_rules_active_assignments_approver_notifications_additional_recipients
      }
      assignee_notifications {
        notification_level    = var.role_policy_rules.notification_rules_active_assignments_assignee_notifications_notification_level                     # Notification level for assignee notifications
        default_recipients    = var.role_policy_rules.notification_rules_active_assignments_assignee_notifications_default_recipients                          # Whether to use default recipients for assignee notifications
        additional_recipients = var.role_policy_rules.notification_rules_active_assignments_assignee_notifications_additional_recipients
      }
    }
  }
  timeouts {
    create = "10m"
    delete = "10m"
  }
}

Ниже приведена ошибка, которую я получаю, когда пытаюсь создать вышеуказанный ресурс.

Error: parsing "/subscriptions/XXXXX-1081-4bff-9256-9feda89161f1/resourceGroups/XXXX-static-rg/providers/Microsoft.KeyVault/vaults/XXXX-static-kv": parsing segment "providers": parsing the ManagementGroup ID: the segment at position 0 didn't match
│
│ Expected a ManagementGroup ID that matched:
│
│ > /providers/Microsoft.Management/managementGroups/groupIdValue
│
│ However this value was provided:
│
│ > /subscriptions/XXXXX-1081-4bff-9256-9feda89161f1/resourceGroups/XXXX-static-rg/providers/Microsoft.KeyVault/vaults/XXXX-static-kv
│
│ The parsed Resource ID was missing a value for the segment at position 0
│ (which should be the literal value "providers").
│
│
│
│   with module.pim-assignment-re.azurerm_role_management_policy.role_policy_resource["Contributor"],
│   on pim-assignment-re\role_policy_rule.tf line 6, in resource "azurerm_role_management_policy" "role_policy_resource":
│    6:   scope              = data.azurerm_key_vault.statickv.id           # Scope of the role management policy
│
╵
╷
│ Error: parsing "/subscriptions/XXXXX-1081-4bff-9256-9feda89161f1/resourceGroups/XXXX-static-rg/providers/Microsoft.KeyVault/vaults/XXXX-static-kv": unexpected segment "providers/Microsoft.KeyVault/vaults/XXXX-static-kv" present at the end of the URI (input "/subscriptions/XXXXX-1081-4bff-9256-9feda89161f1/resourceGroups/XXXX-static-rg/providers/Microsoft.KeyVault/vaults/XXXX-static-kv")
│
│   with module.pim-assignment-re.azurerm_role_management_policy.role_policy_resource["Contributor"],
│   on pim-assignment-re\role_policy_rule.tf line 6, in resource "azurerm_role_management_policy" "role_policy_resource":
│    6:   scope              = data.azurerm_key_vault.statickv.id           # Scope of the role management policy
│
╵
╷
│ Error: parsing "/subscriptions/XXXXX-1081-4bff-9256-9feda89161f1/resourceGroups/XXXX-static-rg/providers/Microsoft.KeyVault/vaults/XXXX-static-kv": unexpected segment "resourceGroups/XXXX-static-rg/providers/Microsoft.KeyVault/vaults/XXXX-static-kv" present at the end of the URI (input "/subscriptions/XXXXX-1081-4bff-9256-9feda89161f1/resourceGroups/XXXX-static-rg/providers/Microsoft.KeyVault/vaults/XXXX-static-kv")
│
│   with module.pim-assignment-re.azurerm_role_management_policy.role_policy_resource["Contributor"],
│   on pim-assignment-re\role_policy_rule.tf line 6, in resource "azurerm_role_management_policy" "role_policy_resource":
│    6:   scope              = data.azurerm_key_vault.statickv.id           # Scope of the role management policy

Это последняя часть для назначения на уровне Key Vault?

Venkat V 04.07.2024 13:45

Да, это для назначения области ресурсов хранилища ключей.

ankur kapoor 04.07.2024 19:27

Terraform поддерживает только группы управления, подписки или группы ресурсов, а не уровень ресурсов в блоке «Политика управления ролями». Вы можете обратиться к реестру Terraform здесь.

Venkat V 05.07.2024 06:32
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
3
199
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Как настроить azurerm_role_management_policy в области ресурса?

Ошибка, с которой вы столкнулись, связана с тем, что Terraform не поддерживает назначение уровня ресурсов для политик управления. Он поддерживает только management groups, subscriptions или resource groups, а не уровень ресурсов в блоке «Политика управления ролями». Более подробную информацию можно найти в реестре Terraformздесь.

Когда я пытаюсь назначить политику на уровне ресурса Key Vault, я сталкиваюсь с той же ошибкой.

    provider "azurerm" {
      features {}
    }
    
    data "azurerm_key_vault" "example" {
      name                = "venkatvault567"
      resource_group_name = "venkatesan-rg"
    }
    
    data "azurerm_role_definition" "mg_contributor" {
      name  = "Owner"
      scope = data.azurerm_key_vault.example.id
    }
    
    data "azuread_group" "example" {
      display_name     = "Venkatgroup"
      security_enabled = true
    }
    
    
    data "azurerm_role_management_policy" "example" {
      scope              = data.azurerm_key_vault.example.id
      role_definition_id = data.azurerm_role_definition.mg_contributor.id
    }
    
    resource "azurerm_role_management_policy" "example" {
      scope              =  data.azurerm_key_vault.example.id
      role_definition_id = data.azurerm_role_definition.mg_contributor.id
    
      active_assignment_rules {
        expire_after = "P365D"
      }
    
      eligible_assignment_rules {
        expiration_required = false
      }
    
      activation_rules {
        maximum_duration = "PT1H"
        require_approval = true
        approval_stage {
          primary_approver {
            object_id = data.azuread_group.example.object_id
            type      = "Group"
          }
        }
      }
    
      notification_rules {
        eligible_assignments {
          approver_notifications {
            notification_level    = "Critical"
            default_recipients    = false
            additional_recipients = ["[email protected]"]
          }
        }
        eligible_activations {
          assignee_notifications {
            notification_level    = "All"
            default_recipients    = true
            additional_recipients = ["[email protected]"]
          }
        }
      }
    }

Ответ:

Ссылка: Microsoft.Authorization roleManagementPolicyAssignments

Где я могу найти политики управления ролями? от VasimTamboli

Другие вопросы по теме