在 Kubernetes RBAC Role/ClusterRole 规则中使用通配符 *

在编写 Kubernetes RBAC Role/ClusterRole 中 rules 字段中定义的规则时,我们可以通过通配符 * 来实现规则中匹配任意字符的需求。

不过通配符 * 也不是可以任意使用的,下面是 rules 字段使用的 PolicyRule 的定义:

// PolicyRule holds information that describes a policy rule, but does not contain information
// about who the rule applies to or which namespace the rule applies to.
type PolicyRule struct {
        // Verbs is a list of Verbs that apply to ALL the ResourceKinds and AttributeRestrictions contained in this rule. '*' represents all verbs.
        Verbs []string `json:"verbs" protobuf:"bytes,1,rep,name=verbs"`

        // APIGroups is the name of the APIGroup that contains the resources.  If multiple API groups are specified, any action requested against one of
        // the enumerated resources in any API group will be allowed.
        // +optional
        APIGroups []string `json:"apiGroups,omitempty" protobuf:"bytes,2,rep,name=apiGroups"`
        // Resources is a list of resources this rule applies to. '*' represents all resources.
        // +optional
        Resources []string `json:"resources,omitempty" protobuf:"bytes,3,rep,name=resources"`
        // ResourceNames is an optional white list of names that the rule applies to.  An empty set means that everything is allowed.
        // +optional
        ResourceNames []string `json:"resourceNames,omitempty" protobuf:"bytes,4,rep,name=resourceNames"`

        // NonResourceURLs is a set of partial urls that a user should have access to.  *s are allowed, but only as the full, final step in the path
        // Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding.
        // Rules can either apply to API resources (such as "pods" or "secrets") or non-resource URL paths (such as "/api"),  but not both.
        // +optional
        NonResourceURLs []string `json:"nonResourceURLs,omitempty" protobuf:"bytes,5,rep,name=nonResourceURLs"`
}

通过阅读 kubernetes 中 PolicyRule 匹配逻辑的源代码 可以知道 PolicyRule 中各个字段使用通配符 * 时有如下限制:

  • verbs 字段只支持通过使用 * 匹配所有 Verb,不支持使用 * 跟其他字符实现组合匹配:
    • *有效 ,匹配所有 Verb
    • de*: 无效
    • de*te: 无效
    • *te: 无效
  • apiGroups 字段只支持通过使用 * 匹配所有 APIGroup ,不支持使用 * 跟其他字符实现组合匹配:
    • *有效 ,匹配所有 APIGroup
    • co*: 无效
    • c*e: 无效
    • *re: 无效
  • resources 字段只支持通过使用 * 匹配所有 resource,以及通过 * 匹配所有 resource 的特定 subresource
    • *有效 ,匹配所有 resource
    • po*: 无效
    • po*s: 无效
    • *ts: 无效
    • */<subresource>: 有效 ,匹配所有 resource 的特定 <subresource> ,比如 */status*/scale
    • *<subresource>: 无效
  • resourceNames 字段不支持通配符 * ,当 resourceNames 字段的值为空时匹配所有 resource name
  • nonResourceURLs 字段只支持通过 * 匹配所有 nonResourceURL、以及通过字符串末尾的 * 匹配以特定字符串开头的任意 nonResourceURL:
    • *有效 ,匹配所有 nonResourceURL
    • /health*: 有效 ,匹配以 /health 开头的任意 nonResourceURL,比如 /health/healthy/health/foo/bar
    • *foo: 无效
    • /*foo: 无效

Comments

comments powered by Disqus