티스토리 뷰

Basic of Azure Policy with AKS cluster

VSCode를 이용한 policy 작성

VS CODE를 이용해서 좀더 쉽게 custom policy 작성이 가능하다.
먼저 아래 plugin 설치가 필요하다. (azure policy)

plugin 설치후 VSCode에서 직접 azure resource manager에 연결하여 현재 보유중인 policy definition 및 initiative 등을 확인 할 수 있다. (참고로 해당 단계에서는 read-only형태로만 읽혀진다.)

custom definition 생성

이제 custom policy를 만들어 definition으로 만들어보자.

이번에 생성할 custom policy는 다음과 같다.

jacob@laptop:~ $ cat constraint-template.yaml
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: podnamedeny
spec:
  crd:
    spec:
      names:
        kind: podnamedeny
      validation:
        openAPIV3Schema:
          properties:
            denyname:
              type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package podnamedeny

        violation[{"msg": msg}] {
          podname := input.review.object.metadata.name
          denyname := input.parameters.denyname
          startswith(podname, denyname)
          msg := sprintf("container <%v> uses not allowed podname : <%v>", [podname, denyname])
        }

Custom Policy인 constraint-template.yaml 파일을 VS code 상에서 open 하고 아래와 같은 command를 입력한다.
( 먼저 ">" 입력한후 "azure policy for kubernetes"를 입력하게 되면 아래와 같은 command가 확인된다. 참고로 이는 constrainttemplate.yaml 파일을 open 한 상태에서만 사용이 가능하다.)

위 command를 선택하게 되면

위와 같이 Base64Encoded 혹은 PublicURL을 선택할수 있게 나온다.
이는 Base64로 Encoded 된 값을 기반으로 azure policy로 생성가능한 template을 만들어주느냐
혹은 PublicURL을 기반으로 azure policy로 생성가능한 template을 만들어주느냐를 선택하는것이라 보면 된다,.
아래는 실제 VS code로 command를 사용하여 만들어진 template 의 일부이다.

VS code 로 만들어진 json 파일을 바로 적용하기 위해서는 armclient를 사용하는 가이드가 있기는 하나 개인적으로 좀더 친숙한 az cli를 통한 설정을 아래와 같이 진행하였다.

먼저 az cli의 경우 template 형태로 command에 의해 자동완성되어지는 json으로 바로 적용은 안되었다.
아래와 같은 parameter와 policyrule을 추출한후 이를 az cli로 생성할수 있었다.

아래 명령을 통해 customrule과 customparam json 파일들을 생성한다.
(여기서 custompolicy.json은 VS code에서 template 형태로 만들어진 json 파일이다.)

jacob@laptop:~ $ cat custompolicy.json | jq -r '.properties.policyRule' > customrule.json
jacob@laptop:~ $ cat custompolicy.json | jq -r '.properties.parameters' > customparam.json

이후 아래와 같은 명령을 사용하여 custom policy를 생성한다.

jacob@laptop:~ $ az policy definition create -n testazpolicybyjacob --rules=@customrule.json --params=@customparam.json --mode Microsoft.Kubernetes.Data
Mode                       Name                 PolicyType
-------------------------  -------------------  ------------
Microsoft.Kubernetes.Data  testazpolicybyjacob  Custom

위 명령중 mode까지 포함하여 적용해야 정상적으로 생성이 되어진다. Microsoft.Kubernetes.Data의 경우 details 항목이 포함되어지나 다른 mode는 사용이 안되어 parsing 에러가 날수 있다.

초기에 헷갈린것이 gatekeeper의 constraintteampltes 과 definition이 동일한 정보를 가지고 있을것이라 생각했었으나
아래와 같이 constraints 단계에서 선언하는 apiGroup 및 kinds, namespaces 등이 사전에 포함되어 있었다.

          "apiGroups": [
            "v1"
          ],
          "kinds": [
            "Pod"
          ],

이를 definition에 사전에 등록해 두고 추가할 parameter와 effect(ex. audit, deny 등) 지정하여 assign 하여 사용하게 되는것이다.

assign custom definition

아래와 같은 constraints를 만들고자 할 경우

jacob@laptop:~ $ cat constraint.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: podnamedeny
metadata:
  name: custompodnamedeny
spec:
  enforcementAction: warn # deny (default) https://open-policy-agent.github.io/gatekeeper/website/docs/violations
  match:
    excludedNamespaces:
    - kube-system
    - gatekeeper-system
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
  parameters:
    denyname: "testdeny"

아래와 같이 이름과 parameter(만약 존재할 경우)를 주게 되면 assignment가 생성된다.

jacob@laptop:~ $ az policy assignment create -n testazpolicybyjacobassign --policy testazpolicybyjacob -p "{\"denyname\": {\"value\": \"testdeny\"}}"
EnforcementMode    Name                       PolicyDefinitionId                                                                                                           Scope
-----------------  -------------------------  ---------------------------------------------------------------------------------------------------------------------------  ---------------------------------------------------
Default            testazpolicybyjacobassign  /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/providers/Microsoft.Authorization/policyDefinitions/testazpolicybyjacob  /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

개인적으로는 definition까지는 az cli를 사용해볼수 있으나 assignment는 portal을 이용하는것이 좀더 편리해보인다.

Keep to know

cluster 마다 assignement 동기화에 약 20분까지 걸릴수 있다.

References

Disclaim
Microsoft의 공식적인 문서가 아닌 개인의 경험을 바탕으로 작성된 내용임을 알립니다.
This is not official document published by Microsoft. Note that this document is based on personal experience.

'Cloud > Public Cloud' 카테고리의 다른 글

Bicep  (0) 2023.11.07
Logic Apps for Azure Resource  (0) 2023.04.17
Azure Kubernetes Service and Network Policy  (0) 2023.04.06
Kata Container on AKS  (0) 2023.03.09
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함