정책 확인

시작하기 전에

Google Cloud CLI를 설치합니다.

gcloud beta terraform vet을 사용하려면 먼저 Google Cloud CLI를 설치해야 합니다.

  1. Google Cloud CLI를 설치하되 gcloud init 명령어는 건너뜁니다.

  2. 다음 명령어를 실행하여 terraform-tools 구성요소를 설치합니다.

    gcloud components update
    gcloud components install terraform-tools
    
  3. 다음 명령어를 실행하여 gcloud CLI가 설치되었는지 확인합니다.

    gcloud beta terraform vet --help
    

필요한 권한 가져오기

검사에 사용하는 Google Cloud 계정에 다음 권한이 있어야 합니다.

  • getIamPolicy: gcloud beta terraform vet은 검증할 정확한 종료 상태를 얻기 위해 전체 Identity and Access Management(IAM) 정책을 가져와 이를 구성원 및 바인딩과 병합해야 합니다.
  • resourcemanager.projects.get: gcloud beta terraform vet은 검사된 리소스가 연결된 모든 프로젝트에 대해 전체 CAI 애셋 이름을 정확하게 생성하기 위해 API에서 프로젝트 조상을 가져와야 합니다.
  • resourcemanager.folders.get: gcloud beta terraform vet은 검증된 리소스에 폴더 관련 리소스가 포함된 경우 전체 CAI 애셋 이름을 정확하게 생성하기 위해 API에서 폴더 상위 항목을 가져와야 합니다.

정책 라이브러리 설정

이 도구를 사용하려면 정책 라이브러리를 만들어야 합니다.

정책 확인

1. Terraform 계획 생성

gcloud beta terraform vet은 Terraform 0.12 이상과 호환됩니다. gcloud beta terraform vetterraform plan JSON을 입력으로 사용합니다. Terraform 디렉터리에서 다음 명령어를 실행하여 JSON 파일을 생성할 수 있습니다.

terraform plan -out=tfplan.tfplan
terraform show -json ./tfplan.tfplan > ./tfplan.json

2. gcloud beta terraform vet 실행

gcloud beta terraform vet을 사용하면 조직의 POLICY_LIBRARY_REPO에 대해 terraform plan JSON을 검증할 수 있습니다. 예를 들면 다음과 같습니다.

git clone POLICY_LIBRARY_REPO POLICY_LIBRARY_DIR
gcloud beta terraform vet tfplan.json --policy-library=POLICY_LIBRARY_DIR

이 명령어를 실행하면 gcloud beta terraform vet은 계획의 정확한 검증에 필요한 Google Cloud API를 사용하여 프로젝트 데이터를 검색합니다.

플래그

  • --policy-library=POLICY_LIBRARY_DIR - 정책 라이브러리가 포함된 디렉터리입니다.
  • --project=PROJECT_ID - gcloud beta terraform vet은 선택적 --project 플래그를 허용합니다. 이 플래그는 명시적인 프로젝트 집합이 없는 리소스에 대해 상위 항목을 빌드할 때(Google Cloud 리소스 계층 구조) 기본 프로젝트를 지정합니다.
  • --format=FORMAT - 기본값은 yaml입니다. 지원되는 형식은 default, json, none, text, yaml입니다. 자세한 내용을 보려면 $ gcloud topic formats를 실행하세요.

종료 코드 및 출력

  • 모든 제약조건이 검사되었으면 명령어가 종료 코드 0을 반환하고 위반을 표시하지 않습니다.
  • 위반이 발견되면 gcloud beta terraform vet은 종료 코드 2를 반환하고 위반 사항 목록을 표시합니다. 예를 들어 JSON 출력은 다음과 같습니다.
[
  {
    "constraint": "GCPIAMAllowedPolicyMemberDomainsConstraintV2.service_accounts_only",
    "constraint_config": {
      "api_version": "constraints.gatekeeper.sh/v1alpha1",
      "kind": "GCPIAMAllowedPolicyMemberDomainsConstraintV2",
      "metadata": {
        "annotations": {
          "description": "Checks that members that have been granted IAM roles belong to allowlisted domains.",
          "validation.gcp.forsetisecurity.org/originalName": "service_accounts_only",
          "validation.gcp.forsetisecurity.org/yamlpath": "policies/constraints/iam_service_accounts_only.yaml"
        },
        "name": "service-accounts-only"
      },
      "spec": {
        "match": {
          "target": [
            "organizations/**"
          ]
        },
        "parameters": {
          "domains": [
            "gserviceaccount.com"
          ]
        },
        "severity": "high"
      }
    },
    "message": "IAM policy for //cloudresourcemanager.googleapis.com/projects/PROJECT_ID contains member from unexpected domain: user:me@example.com",
    "metadata": {
      "ancestry_path": "organizations/ORG_ID/projects/PROJECT_ID",
      "constraint": {
        "annotations": {
          "description": "Checks that members that have been granted IAM roles belong to allowlisted domains.",
          "validation.gcp.forsetisecurity.org/originalName": "service_accounts_only",
          "validation.gcp.forsetisecurity.org/yamlpath": "policies/constraints/iam_service_accounts_only.yaml"
        },
        "labels": {},
        "parameters": {
          "domains": [
            "gserviceaccount.com"
          ]
        }
      },
      "details": {
        "member": "user:me@example.com",
        "resource": "//cloudresourcemanager.googleapis.com/projects/PROJECT_ID"
      }
    },
    "resource": "//cloudresourcemanager.googleapis.com/projects/PROJECT_ID",
    "severity": "high"
  }
]

CI/CD 예시

CI/CD 파이프라인에서 gcloud beta terraform vet를 사용하기 위한 bash 스크립트는 다음과 같습니다.

terraform plan -out=tfplan.tfplan
terraform show -json ./tfplan.tfplan > ./tfplan.json
git clone POLICY_LIBRARY_REPO POLICY_LIBRARY_DIR
VIOLATIONS=$(gcloud beta terraform vet tfplan.json --policy-library=POLICY_LIBRARY_DIR --format=json)
retVal=$?
if [ $retVal -eq 2 ]; then
  # Optional: parse the VIOLATIONS variable as json and check the severity level
  echo "$VIOLATIONS"
  echo "Violations found; not proceeding with terraform apply"
  exit 1
fi
if [ $retVal -ne 0]; then
  echo "Error during gcloud beta terraform vet; not proceeding with terraform apply"
  exit 1
fi

echo "No policy violations detected; proceeding with terraform apply"

terraform apply

개발자는 CI/CD 파이프라인을 실행하기 전에 로컬에서 gcloud beta terraform vet를 사용하여 Terraform 변경 사항을 테스트할 수도 있습니다.