본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Ansible로 Cloudflare Tunnel 구성하기

원문 보기 위키 갱신

Ansible과 Terraform을 함께 사용해 Cloudflare Tunnel 설정 과정을 자동화하는 방법을 알아봐요. Terraform으로 GCP에 SSH 서버를 배포하고 로컬 관리 터널을 만들며, Ansible 플레이북이 서버에 cloudflared를 설치하고 구성해요.

출처: 문서

본문

Ansible은 규모에 맞춰 인프라를 관리할 수 있게 해주는 소프트웨어 도구예요. Ansible은 에이전트 없이(agentless) 동작해요 — 동작하는 데 필요한 것은 대상에 SSH로 접속할 수 있는 능력과 대상에 Python이 설치되어 있을 것뿐이에요.

Ansible은 Terraform과 함께 작동해 Cloudflare Tunnel 설정 과정을 간소화해요. 이 가이드에서는 Terraform을 사용해 Google Cloud에 SSH 서버를 배포하고, 서버를 인터넷에서 사용할 수 있게 하는 로컬 관리 터널을 만들어요. Terraform은 서버에 cloudflared를 설치하고 구성하는 Ansible 플레이북을 자동으로 실행해요.

사전 준비(Prerequisites)

이 가이드의 단계를 완료하려면 다음이 필요해요:

1. Ansible 설치

Ansible 설치 가이드 ↗︎를 참고해요.

2. (선택 사항) SSH 키 페어 만들기

Terraform과 Ansible은 GCP 서버에 연결하기 위해 암호화되지 않은(unencrypted) SSH 키가 필요해요. 키가 아직 없다면 다음과 같이 생성할 수 있어요:

  1. 터미널을 열고 다음 명령을 입력해요:

    ssh-keygen -t rsa -f ~/.ssh/gcp_ssh -C <username in GCP>
    
  2. 암호(passphrase)를 묻는 프롬프트가 나오면 Enter 키를 두 번 눌러 비워 두어요. Terraform은 암호화된 프라이빗 키를 디코딩할 수 없어요.

프라이빗 키를 담은 gcp_ssh와 공개 키를 담은 gcp_ssh.pub 두 파일이 생성될 거예요.

3. 구성 디렉터리 만들기

  1. Terraform과 Ansible 구성 파일용 폴더를 만들어요:

    mkdir ansible-tunnel
    
  2. 새 디렉터리로 이동해요:

    cd ansible-tunnel
    

4. Terraform 구성 파일 만들기

입력 변수 정의하기

다음 변수는 GCP와 Cloudflare 구성에 전달돼요.

  1. 구성 디렉터리에 .tf 파일을 만들어요:

    touch variables.tf
    
  2. 파일을 텍스트 편집기로 열고 다음을 복사해 붙여 넣어요:

    # GCP variables
    variable "gcp_project_id" {
      description = "Google Cloud Platform (GCP) project ID"
      type        = string
    }
    
    variable "zone" {
      description = "Geographical zone for the GCP VM instance"
      type        = string
    }
    
    variable "machine_type" {
      description = "Machine type for the GCP VM instance"
      type        = string
    }
    
    # Cloudflare variables
    variable "cloudflare_zone" {
      description = "Domain used to expose the GCP VM instance to the Internet"
      type        = string
    }
    
    variable "cloudflare_zone_id" {
      description = "Zone ID for your domain"
      type        = string
    }
    
    variable "cloudflare_account_id" {
      description = "Account ID for your Cloudflare account"
      type        = string
      sensitive   = true
    }
    
    variable "cloudflare_email" {
      description = "Email address for your Cloudflare account"
      type        = string
      sensitive   = true
    }
    
    variable "cloudflare_token" {
      description = "Cloudflare API token"
      type        = string
      sensitive   = true
    }
    

변수에 값 할당하기

  1. 구성 디렉터리에 .tfvars 파일을 만들어요:

    touch terraform.tfvars
    

    파일 이름이 terraform.tfvars면 Terraform이 이 변수를 자동으로 사용해요. 그렇지 않으면 변수 파일을 수동으로 전달해야 해요.

  2. terraform.tfvars에 다음 변수를 추가해요. 예시를 반드시 여러분의 값으로 수정해요.

    cloudflare_zone           = "example.com"
    cloudflare_zone_id        = "023e105f4ecef8ad9ca31a8372d0c353"
    cloudflare_account_id     = "372e67954025e0ba6aaa6d586b9e0b59"
    cloudflare_email          = "user@example.com"
    cloudflare_token          = "y3AalHS_E7Vabk3c3lX950F90_Xl7YtjSlzyFn_X"
    gcp_project_id            = "testvm-123"
    zone                      = "us-central1-a"
    machine_type              = "e2-medium"
    

주의(Caution)

민감한 자격 증명이 실수로 노출되지 않도록 terraform.tfvars를 버전 관리 시스템에 저장하지 마세요. 예를 들어 버전 관리가 git이라면 .gitignore 파일에 terraform.tfvars를 추가하세요.

Terraform provider 설정하기

인프라를 프로비저닝하는 데 사용되는 provider ↗︎를 선언해야 해요.

  1. 구성 디렉터리에 .tf 파일을 만들어요:

    touch providers.tf
    
  2. providers.tf에 다음 provider를 추가해요. random provider는 터널 시크릿을 생성하는 데 사용돼요.

    terraform {
    	required_providers {
    		cloudflare = {
    			source = "cloudflare/cloudflare"
    			version = ">= 5.8.2"
    		}
    		google = {
    			source = "hashicorp/google"
    		}
    	}
    	required_version = ">= 1.2"
    }
    
    # Providers
    provider "cloudflare" {
    	api_token    = var.cloudflare_token
    }
    provider "google" {
    	project    = var.gcp_project_id
    }
    provider "random" {
    }
    

Cloudflare 리소스 구성하기

다음 구성은 Cloudflare 계정의 설정을 수정해요.

  1. 구성 디렉터리에 .tf 파일을 만들어요:

    touch Cloudflare-config.tf
    
  2. Cloudflare-config.tf에 다음 리소스를 추가해요:

    # Creates a new remotely-managed tunnel for the GCP VM.
    resource "cloudflare_zero_trust_tunnel_cloudflared" "gcp_tunnel" {
    	account_id    = var.cloudflare_account_id
    	name          = "Ansible GCP tunnel"
    	config_src    = "cloudflare"
    }
    
    # Reads the token used to run the tunnel on the server.
    data "cloudflare_zero_trust_tunnel_cloudflared_token" "gcp_tunnel_token" {
    	account_id 	= var.cloudflare_account_id
    	tunnel_id 	= cloudflare_zero_trust_tunnel_cloudflared.gcp_tunnel.id
    }
    
    # Creates the CNAME record that routes http_app.${var.cloudflare_zone} to the tunnel.
    resource "cloudflare_dns_record" "http_app" {
    	zone_id = var.cloudflare_zone_id
    	name    = "http_app"
    	content = "${cloudflare_zero_trust_tunnel_cloudflared.gcp_tunnel.id}.cfargotunnel.com"
    	type    = "CNAME"
    	ttl     = 1
    	proxied = true
    }
    
    # Configures tunnel with a published application for clientless access.
    resource "cloudflare_zero_trust_tunnel_cloudflared_config" "gcp_tunnel_config" {
    	tunnel_id  = cloudflare_zero_trust_tunnel_cloudflared.gcp_tunnel.id
    	account_id = var.cloudflare_account_id
    	config     = {
    		ingress 	= [
    			{
    				hostname = "http_app.${var.cloudflare_zone}"
    				service  = "http://localhost:80"
    			},
    			{
    				service  = "http_status:404"
    			}
    		]
    	}
    }
    

GCP 리소스 구성하기

다음 구성은 GCP 가상 머신의 사양을 정의하고 머신에 Python3를 설치해요. Python3 덕분에 Ansible이 부팅 시 시작 스크립트를 실행하는 대신 GCP 인스턴스를 구성할 수 있어요.

  1. 구성 디렉터리에 .tf 파일을 만들어요:

    touch GCP-config.tf
    
  2. 파일을 텍스트 편집기로 열고 다음 예시를 복사해 붙여 넣어요. 반드시 여러분의 GCP 사용자 이름과 SSH 키 페어를 입력해요.

    # Selects the OS for the GCP VM.
    data "google_compute_image" "image" {
    family  = "ubuntu-2204-lts"
    project = "ubuntu-os-cloud"
    }
    
    # Sets up a GCP VM instance.
    resource "google_compute_instance" "http_server" {
    name         = "ansible-inst"
    machine_type = var.machine_type
    zone         = var.zone
    tags         = []
    boot_disk {
        initialize_params {
        image = data.google_compute_image.image.self_link
        }
    }
    network_interface {
        network = "default"
        access_config {
        // Ephemeral IP
        }
    }
    scheduling {
        preemptible = true
        automatic_restart = false
    }
    
    // Installs Python3 on the VM.
    provisioner "remote-exec" {
        inline = [
        "sudo apt update", "sudo apt install python3 -y",  "echo Done!"
        ]
        connection {
        host = self.network_interface.0.access_config.0.nat_ip
        user = "<username in GCP>"
        type = "ssh"
        private_key= file("<path to private key>")
        }
    }
    provisioner "local-exec" {
        // If specifying an SSH key and user, add `--private-key <path to private key> -u var.name`
        command = "ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook -u <username in GCP> --private-key <path to private key> -i ${self.network_interface.0.access_config.0.nat_ip}, playbook.yml"
    }
    
    metadata = {
        cf-email     = var.cloudflare_email
        cf-zone      = var.cloudflare_zone
        ssh-keys     = "<username in GCP>:${file("<path to public key>")}"
    }
    depends_on = [
        local_file.tf_ansible_vars_file
    ]
    }
    

Ansible로 변수 내보내기

다음 Terraform 리소스는 터널 토큰과 기타 변수를 tf_ansible_vars_file.yml로 내보내요. Ansible은 이 터널 토큰을 사용해 서버에서 cloudflared를 구성하고 실행해요.

  1. 구성 디렉터리에 새 tf 파일을 만들어요:

    touch export.tf
    
  2. 다음 내용을 export.tf에 복사해 붙여 넣어요:

    resource "local_file" "tf_ansible_vars_file" {
    	content = <<-DOC
    		# Ansible vars_file containing variable values from Terraform.
    		tunnel_id: ${cloudflare_zero_trust_tunnel_cloudflared.gcp_tunnel.id}
    		tunnel_name: ${cloudflare_zero_trust_tunnel_cloudflared.gcp_tunnel.name}
    		tunnel_token: ${data.cloudflare_zero_trust_tunnel_cloudflared_token.gcp_tunnel_token.token}
    		DOC
    
    	filename = "./tf_ansible_vars_file.yml"
    }
    

5. Ansible 플레이북 만들기

Ansible 플레이북은 Ansible이 배포할 구성을 선언하는 YAML 파일이에요.

  1. 새 .yml 파일을 만들어요:

    touch playbook.yml
    
  2. 파일을 텍스트 편집기로 열고 다음 내용을 복사해 붙여 넣어요:

---
- hosts: all
  become: yes
  # Import tunnel variables into the VM.
  vars_files:
    - ./tf_ansible_vars_file.yml
  # Execute the following commands on the VM.
  tasks:
    - name: Download the cloudflared Linux package.
      shell: wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb
    - name: Depackage cloudflared.
      shell: sudo dpkg -i cloudflared-linux-amd64.deb
    - name: Install the tunnel as a systemd service.
      shell: "cloudflared service install {{ tunnel_token }}"
    - name: Start the tunnel.
      systemd:
        name: cloudflared
        state: started
        enabled: true
        masked: no
    - name: Deploy an example Apache web server on port 80.
      shell: apt update && apt -y install apache2
    - name: Edit the default Apache index file.
      copy:
        dest: /var/www/html/index.html
        content: |
          <!DOCTYPE html>
          <html>
          <body>
            <h1>Hello Cloudflare!</h1>
            <p>This page was created for a Cloudflare demo.</p>
          </body>
          </html>

키워드 ↗︎는 Ansible이 구성을 어떻게 실행할지 정의해요. 위 예시에서 vars_files 키워드는 변수 정의가 저장된 위치를 지정하고, tasks 키워드는 Ansible이 수행할 작업을 지정해요.

모듈 ↗︎은 어떤 작업을 완료할지 지정해요. 이 예시에서 copy 모듈은 파일을 만들고 내용을 채워요.

6. 구성 배포하기

구성 파일을 만들고 나면 Terraform을 통해 배포할 수 있어요. Ansible 배포는 ansible-playbook 명령이 실행될 때 Terraform 배포 안에서 이루어져요.

  1. 구성 디렉터리를 초기화해요:

    terraform init
    
  2. (선택 사항) 만들어질 모든 것을 미리 확인해요:

    terraform plan
    
  3. 구성을 배포해요:

    terraform apply
    

GCP 인스턴스와 터널이 온라인 상태가 되는 데 몇 분이 걸릴 수 있어요. Cloudflare 대시보드의 Networking > Tunnels에서 새 터널을 볼 수 있어요.

7. 연결 테스트하기

테스트하려면 브라우저를 열고 http://http_app.<CLOUDFLARE_ZONE>.com으로 이동해요 (예: http_app.example.com). Hello Cloudflare! 테스트 페이지가 보일 거예요.

더 알아보기 (Learn more)

Ansible은 에이전트 없는 구조 덕분에 SSH만으로 원격 서버를 일괄 관리할 수 있어요. Terraform 가이드와 함께 보면 클라우드 인프라와 터널을 완전히 코드로 관리하는 패턴을 익힐 수 있어요.