OS 정책 및 OS 정책 할당

OS 정책은 패키지, 저장소, 파일, 또는 스크립트로 정의된 커스텀 리소스 등 OS 리소스에 대한 선언적 구성이 포함된 파일입니다. 자세한 내용은 OSPolicy의 리소스 정의를 참조하세요.

OS 정책 할당은 VM Manager에서 OS 정책을 VM에 적용하는 데 사용하는 API 리소스입니다. 자세한 내용은 OSPolicyAssignment의 리소스 정의를 참조하세요.

OS 정책

OS 정책은 세 가지 섹션으로 된 JSON 또는 YAML 파일입니다.

  • 모드를 지정합니다. 정책 동작입니다. 사용 가능한 두 가지 모드는 다음과 같습니다.

    • Validation: 이 모드에서 정책은 선택한 상태에 있는지 확인하지만 아무 조치도 취하지 않습니다.
    • Enforcement: 이 모드에서 정책은 리소스가 선택한 상태인지 확인하고 그렇지 않은 경우 선택한 상태로 만들기 위해 필요한 작업을 수행합니다.

    두 모드 모두 VM Manager는 OS 정책 및 관련 리소스의 규정 준수를 보고합니다.

  • 리소스 그룹. 관련 리소스 사양이 적용되는 운영체제 이름 및 버전입니다. 예를 들어 단일 정책을 정의하여 여러 운영체제 배포 및 버전에 에이전트를 설치하거나 배포할 수 있습니다.

  • 리소스. VM이 선택한 구성을 달성하는 데 필요한 사양입니다. 리소스 그룹마다 리소스 ID를 최대 10개까지 지정할 수 있습니다. 지원되는 리소스 유형은 다음과 같습니다.

    • pkg: Linux 및 Windows 패키지를 설치하거나 제거하는 데 사용됩니다.
    • repository: 소프트웨어 패키지를 설치할 수 있는 저장소를 지정하는 데 사용됩니다.
    • exec: 임시 셸(/bin/sh) 또는 PowerShell 스크립트 실행을 사용 설정하는 데 사용됩니다.
    • file: 시스템의 파일을 관리하는 데 사용

OS 정책 예시

다음 예시에서는 OS 정책을 만드는 방법을 보여줍니다. OS 정책 할당을 만들 때 이러한 OS 정책을 Google Cloud 콘솔에 업로드할 수 있습니다.

  • 예시 1: 패키지 설치
  • 예시 2: 스크립트 실행
  • 예시 3: Cloud Storage 버킷에 저장된 스크립트를 실행하고 출력 파일을 Cloud Storage 버킷에 복사합니다.
  • 예시 4: 다운로드 저장소를 지정하고 해당 저장소에서 패키지를 설치합니다.
  • 예시 5: Container-Optimized OS(COS)를 실행하는 VM에서 CIS 벤치마크 스캔을 구성합니다. CIS 벤치마크 스캔에 OS 정책을 사용하는 방법에 대한 자세한 내용은 CIS 규정 준수 상태 사용 설정 및 확인 자동화를 참조하세요.

사용자 환경에서 적용할 수 있는 샘플 OS 정책의 전체 목록은 GoogleCloudPlatform/osconfig GitHub 저장소를 참조하세요.

예 1

Cloud Storage 버킷에서 다운로드한 Windows MSI를 설치하는 OS 정책을 만듭니다.

# An OS policy to install a Windows MSI downloaded from a Google Cloud Storage bucket.
id: install-msi-policy
mode: ENFORCEMENT
resourceGroups:
  - resources:
      - id: install-msi
        pkg:
          desiredState: INSTALLED
          msi:
            source:
              gcs:
                bucket: my-bucket
                object: my-app.msi
                generation: 1619136883923956

예 2

Apache 웹 서버가 Linux VM에서 실행 중인지 여부를 확인하는 OS 정책을 만듭니다.

# An OS policy that ensures Apache web server is running on Linux OSes.
id: apache-always-up-policy
mode: ENFORCEMENT
resourceGroups:
  - resources:
      id: ensure-apache-is-up
      exec:
        validate:
          interpreter: SHELL
          # If Apache web server is already running, return an exit code 100 to indicate
          # that exec resource is already in desired state. In this scenario,
          # the `enforce` step will not be run.
          # Otherwise return an exit code of 101 to indicate that exec resource is not in
          # desired state. In this scenario, the `enforce` step will be run.
          script: if systemctl is-active --quiet httpd; then exit 100; else exit 101; fi
        enforce:
          interpreter: SHELL
          # Start Apache web server and return an exit code of 100 to indicate that the
          # resource is now in its desired state.
          script: systemctl start httpd && exit 100

예시 3

Apache 웹 서버가 Linux VM에서 실행 중인지 여부를 확인하는 OS 정책을 만듭니다. 이 예시에서는 apache-validate.sh 스크립트가 Cloud Storage 버킷에 저장됩니다. 출력을 Cloud Storage 버킷에 복사하려면 apache-enforce.sh 스크립트에 다음과 유사한 명령어가 포함되어야 합니다.

      gcsutil cp my-exec-output-file gs://my-gcs-bucket
      

# An OS policy that ensures Apache web server is running on Linux OSes.
id: gcs-test-apache-always-up-policy
mode: ENFORCEMENT
resourceGroups:
  - resources:
      id: ensure-apache-is-up
      exec:
        validate:
          interpreter: SHELL
          # If Apache web server is already running, return an exit code 100 to indicate
          # that exec resource is already in desired state. In this scenario,
          # the enforce step will not be run.
          # Otherwise return an exit code of 101 to indicate that exec resource is not in
          # desired state. In this scenario, the enforce step will be run.
          file:
            gcs:
              bucket: my-gcs-bucket
              object: apache-validate.sh
              generation: 1726747503303299
        enforce:
          interpreter: SHELL
          # Start Apache web server and return an exit code of 100 to indicate that the
          # resource is now in its desired state.
          file:
            gcs:
              bucket: my-gcs-bucket
              object: apache-enforce.sh
              generation: 1726747503250884

예시 4

CentOS VM에 Google Cloud Observability 에이전트를 설치하는 OS 정책을 만듭니다.

id: cloudops-policy
mode: ENFORCEMENT
resourceGroups:
  - resources:
      - id: add-repo
        repository:
          yum:
            id: google-cloud-ops-agent
            displayName: Google Cloud Ops Agent Repository
            baseUrl: https://packages.cloud.google.com/yum/repos/google-cloud-ops-agent-el7-x86_64-all
            gpgKeys:
              - https://packages.cloud.google.com/yum/doc/yum-key.gpg
              - https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
      - id: install-pkg
        pkg:
          desiredState: INSTALLED
          yum:
            name: google-cloud-ops-agent
      - id: exec-script
        exec:
          validate:
            script: |-
              if [[ $(rpm --query --queryformat '%{VERSION}
              ' google-cloud-ops-agent) == '1.0.2' ]]; then exit 100; else exit 101; fi
            interpreter: SHELL
          enforce:
            script:
              sudo yum remove -y google-cloud-ops-agent || true; sudo yum install
              -y 'google-cloud-ops-agent-1.0.2*' && exit 100
            interpreter: SHELL
      - id: ensure-agent-running
        exec:
          validate:
            script:
              if (ps aux | grep 'opt[/].*google-cloud-ops-agent.*bin/'); then exit
              100; else exit 101; fi
            interpreter: SHELL
          enforce:
            script: sudo systemctl start google-cloud-ops-agent.target && exit 100
            interpreter: SHELL

예시 5

기본 기간을 하루에 한 번으로 주기적 CIS 수준 1 스캔을 구성합니다.

# An OS policy to check CIS level 1 compliance once a day.
id: ensure-cis-level1-compliance-once-a-day-policy
mode: ENFORCEMENT
resourceGroups:
  - resources:
      id: ensure-cis-level1-compliance-once-a-day
      exec:
        validate:
          interpreter: SHELL
          # If cis-compliance-scanner.service is active, return an exit code
          # 100 to indicate that the instance is in compliant state.
          # Otherwise, return an exit code of 101 to run `enforce` step.
          script: |-
            is_active=$(systemctl is-active cis-compliance-scanner.timer)
            result=$(systemctl show -p Result --value cis-compliance-scanner.service)

            if [ "$is_active" == "active" ] && [ "$result" == "success" ]; then
              exit 100;
            else
              exit 101;
            fi
        enforce:
          interpreter: SHELL
          # COS 97 images are by-default CIS Level 1 compliant and there is no
          # additional configuration needed. However, if certain changes
          # cause non-compliance because of the workload on the instance, this
          # section can be used to automate to make fixes. For example, the
          # workload might generate a file that does not comply with the
          # recommended file permissions.
          # Return an exit code of 100 to indicate that the desired changes
          # successfully applied.
          script: |-
            # optional <your code>
            # Check the compliance of the instance once a day.
            systemctl start cis-compliance-scanner.timer && exit 100

OS 정책 할당

OS 정책 할당에는 다음 섹션이 포함됩니다.

  • OS 정책. VM에 적용할 하나 이상의 OS 정책입니다. 정책을 다운로드하거나 만들려면 OS 정책을 참조하세요.

  • 대상 VM. 정책을 적용할 단일 영역 내의 VM 집합입니다. 영역 내에서 OS 이름과 포함 또는 제외 라벨을 지정하여 VM을 제한할 수 있습니다. 다음 옵션 조합을 선택할 수 있습니다.

    • 영역: OS 정책 할당을 출시할 Google Cloud 영역을 지정합니다.
    • OS 이름 및 버전: OS 정책이 적용되는 대상 운영체제의 약어와 버전을 지정합니다. 여러 운영체제를 타겟팅하는 방법의 예시는 예 4를 참조하세요.

    운영체제를 기반으로 VM을 필터링하려면 OS 정책 YAML 파일에서 다음 약식 이름 중 하나를 사용하세요.

    이름 별칭
    CentOS centos
    Container-Optimized OS(COS) cos
    Debian debian
    openSUSE Leap opensuse-leap
    Oracle Linux ol
    RHEL(Red Hat Enterprise Linux) rhel
    Rocky Linux rocky
    SLES(SUSE Linux Enterprise Server) sles
    Ubuntu ubuntu
    Windows Server windows

    OS 정책을 지원하는 운영체제와 버전의 전체 목록은 운영체제 세부정보를 참조하세요.

    • 포함 집합: VM 또는 시스템 라벨을 기준으로 OS 정책이 적용되는 VM을 지정합니다.
    • 제외 집합: OS 정책에서 VM 또는 시스템 라벨을 기준으로 무시해야 하는 VM을 지정합니다.

    포함 라벨 집합과 제외 라벨 집합 모두 시스템에서 사용하는 명명 규칙과 일치하면 단일 문자열 라벨이 허용됩니다. 그러나 대부분의 라벨은 key:value 쌍으로 지정됩니다. 라벨에 대한 자세한 내용은 리소스 라벨 지정을 참조하세요.

    예를 들어 테스트 환경에서 모든 Ubuntu VM을 선택하고, 다음을 지정하여 Google Kubernetes Engine을 실행 중인 VM을 제외할 수 있습니다.

    • OS 짧은 이름: ubuntu
    • 포함: env:test, env:staging
    • 제외: goog-gke-node
  • 출시 속도. OS 정책을 VM에 적용할 속도를 지정합니다. OS 정책이 점진적으로 출시되어 업데이트로 인해 사용자 환경에서 회귀가 발생할 때 시스템 상태를 추적하고 이를 수정할 수 있습니다. 출시 계획에는 다음 구성요소가 포함됩니다.

    • 웨이브 크기(중단 예산): 한 번에 출시될 수 있는 VM의 고정 숫자 또는 백분율입니다. 즉, 출시 시점에는 지정된 수의 VM만 대상으로 합니다.
    • 대기 시간: 서비스가 VM에 정책을 적용하는 시점과 VM이 중단 임곗값에서 삭제된 시점 사이의 시간입니다. 예를 들어 대기 시간이 15분인 경우 VM이 정책을 적용한 후 중단 프로세스에서 15분간 기다려야 VM이 중단 임곗값에서 VM을 삭제하고 출시를 진행할 수 있습니다. 대시 시간은 출시 속도를 제어하는 데 도움이 되며 잠재적인 출시 문제를 조기에 포착하고 해결할 수도 있습니다. 출시 상태를 모니터링하기에 충분한 시간을 선택하세요.

    예를 들어 VM 대상을 10개로 설정하고, 중단 임곗값을 20%로, 베이킹 시간을 15분으로 설정하면 언제든지 VM 2개만 업데이트되도록 예약됩니다. 각 VM이 업데이트된 후 15분이 경과해야 VM이 중단 임곗값에서 삭제되고 다른 VM이 출시에 추가됩니다.

    출시에 대한 상세 내용은 출시를 참조하세요.

OS 정책 할당 예시

다음 예시에서는 OS 정책 할당을 만드는 방법을 보여줍니다. 이 예시를 사용하여 Google Cloud CLI 또는 OS Config API에서 OS 정책 할당을 만들 수 있습니다.

  • 예시 1: 패키지 설치
  • 예시 2: 스크립트 실행
  • 예시 3: 다운로드 저장소를 지정하고 해당 저장소에서 패키지를 설치합니다.
  • 예시 4: 여러 운영체제에 적용되는 OS 정책 할당

사용자 환경에서 적용할 수 있는 샘플 OS 정책 할당의 전체 목록은 GoogleCloudPlatform/osconfig GitHub 저장소를 참조하세요.

예 1

Cloud Storage 버킷에서 다운로드한 Windows MSI를 설치하는 OS 정책 할당을 만듭니다.

# An OS policy assignment to install a Windows MSI downloaded from a Google Cloud Storage bucket
# on all VMs running Windows Server OS.
osPolicies:
  - id: install-msi-policy
    mode: ENFORCEMENT
    resourceGroups:
      - resources:
          - id: install-msi
            pkg:
              desiredState: INSTALLED
              msi:
                source:
                  gcs:
                    bucket: my-bucket
                    object: my-app.msi
                    generation: 1619136883923956
instanceFilter:
  inventories:
    - osShortName: windows
rollout:
  disruptionBudget:
    fixed: 10
  minWaitDuration: 300s

예 2

Apache 웹 서버가 모든 Linux VM에서 실행 중인지 여부를 확인하는 OS 정책 할당을 만듭니다.

# An OS policy assignment that ensures Apache web server is running on Linux OSes.
# The assignment is applied only to those VMs that have the label `type:webserver` assigned to them.
osPolicies:
  - id: apache-always-up-policy
    mode: ENFORCEMENT
    resourceGroups:
      - resources:
          id: ensure-apache-is-up
          exec:
            validate:
              interpreter: SHELL
              # If Apache web server is already running, return an exit code 100 to indicate
              # that exec resource is already in desired state. In this scenario,
              # the `enforce` step will not be run.
              # Otherwise return an exit code of 101 to indicate that exec resource is not in
              # desired state. In this scenario, the `enforce` step will be run.
              script: if systemctl is-active --quiet httpd; then exit 100; else exit 101; fi
            enforce:
              interpreter: SHELL
              # Start Apache web server and return an exit code of 100 to indicate that the
              # resource is now in its desired state.
              script: systemctl start httpd && exit 100
instanceFilter:
  inclusionLabels:
    - labels:
        type: webserver
rollout:
  disruptionBudget:
    fixed: 10
  minWaitDuration: 300s

예시 3

CentOS VM에 Google Cloud Observability 에이전트를 설치하는 OS 정책 할당을 만듭니다.

# An OS policy assignment that ensures google-cloud-ops-agent is running on all Centos VMs in the project
osPolicies:
  - id: cloudops-policy
    mode: ENFORCEMENT
    resourceGroups:
        resources:
          - id: add-repo
            repository:
              yum:
                id: google-cloud-ops-agent
                displayName: Google Cloud Ops Agent Repository
                baseUrl: https://packages.cloud.google.com/yum/repos/google-cloud-ops-agent-el7-x86_64-all
                gpgKeys:
                  - https://packages.cloud.google.com/yum/doc/yum-key.gpg
                  - https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
          - id: install-pkg
            pkg:
              desiredState: INSTALLED
              yum:
                name: google-cloud-ops-agent
          - id: exec-script
            exec:
              validate:
                script: |-
                  if [[ $(rpm --query --queryformat '%{VERSION}
                  ' google-cloud-ops-agent) == '1.0.2' ]]; then exit 100; else exit 101; fi
                interpreter: SHELL
              enforce:
                script:
                  sudo yum remove -y google-cloud-ops-agent || true; sudo yum install
                  -y 'google-cloud-ops-agent-1.0.2*' && exit 100
                interpreter: SHELL
          - id: ensure-agent-running
            exec:
              validate:
                script:
                  if (ps aux | grep 'opt[/].*google-cloud-ops-agent.*bin/'); then exit
                  100; else exit 101; fi
                interpreter: SHELL
              enforce:
                script: sudo systemctl start google-cloud-ops-agent.target && exit 100
                interpreter: SHELL
instanceFilter:
  inventories:
    - osShortName: centos
rollout:
  disruptionBudget:
    fixed: 10
  minWaitDuration: 300s

예시 4

여러 Linux 및 Windows 운영체제에 적용되는 OS 정책 할당을 만듭니다.

# An OS policy assignment that applies to multiple Linux and Windows operating systems.
id: multi-os
mode: VALIDATION
resourceGroups:
  - inventoryFilters:
      - osShortName: debian
      - osShortName: centos
      - osShortName: ubuntu
      - osShortName: rhel
      - osShortName: rocky
      - osShortName: cos
      - osShortName: opensuse-leap
      - osShortName: ol
      - osShortName: sles
    resources:
      - id: linux
        exec:
          validate:
            interpreter: SHELL
            # Linux-specific script.
            # Exit code of 100 = resource is in the desired state
            script: |
              exit 100
  - inventoryFilters:
      - osShortName: windows
    resources:
      - id: windows
        exec:
          validate:
            interpreter: POWERSHELL
            # Windows-specific script.
            # Exit code of 100 = resource is in the desired state
            script: |
              exit 100

다음 단계