🤖 테라폼으로 오라클 클라우드 A1 VM 자동 생성 봇 만들기
📚 소개
안녕하세요! 오늘은 테라폼(Terraform)과 Node.js를 활용하여 오라클 클라우드의 Always Free Tier인 ARM 기반 A1 VM을 자동으로 생성하는 봇을 만드는 과정을 공유하려고 합니다. 이 프로젝트는 무료 VM 리소스를 최대한 활용하고 싶은 분들에게 유용할 거예요! 😊
🛠️ 준비물
- 오라클 클라우드 계정
- 리눅스 환경 (Ubuntu 기준)
- 기본적인 터미널 및 코드 편집 지식
🔑 환경 설정하기
1️⃣ 시스템 업데이트 및 필수 도구 설치
먼저 시스템을 최신 상태로 업데이트하고 필요한 도구를 설치합니다:
sudo apt update && apt upgrade -y
sudo apt install -y vim
2️⃣ OCI CLI 설치
오라클 클라우드 인프라(OCI) CLI를 설치하여 명령줄에서 오라클 클라우드에 접근할 수 있게 합니다:
bash -c "$(curl -L https://raw.githubusercontent.com/oracle/oci-cli/master/scripts/install/install.sh)"
exec -l $SHELL
필요한 경우 쉘 경로 설정을 추가할 수 있습니다:
vi ~/.bashrc
# 마지막줄에 추가
export PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]$(pwd)\[\033[00m\]$ '
source ~/.bashrc
3️⃣ OCI 설정 구성
CLI 설정을 구성합니다:
oci setup config
📝 중요: API 키 생성 과정에서 비밀번호 입력 요청이 있을 때 “N/A”를 입력하여 비밀번호 없이 설정할 수 있습니다.
4️⃣ API 키 업로드
생성된 API 키(oci_api_key.pem)를 오라클 클라우드 콘솔에 업로드합니다:
- 오라클 클라우드 콘솔 로그인
- 프로필 > 사용자 설정 > API 키 메뉴 접속
oci_api_key.pem.pub
파일 업로드
🏗️ 테라폼 설정하기
1️⃣ 테라폼 설치
테라폼을 다운로드하고 설치합니다:
mkdir temp
cd temp
wget https://releases.hashicorp.com/terraform/1.7.5/terraform_1.7.5_linux_amd64.zip
unzip terraform_1.7.5_linux_amd64.zip
sudo mv terraform /usr/local/bin/
terraform -v # 설치 확인
2️⃣ 테라폼 프로바이더 설정
기본 프로바이더 설정을 위한 디렉토리를 생성합니다:
mkdir ~/tf-provider
cd ~/tf-provider
프로바이더 설정 파일(provider.tf)을 생성합니다:
vi provider.tf
provider "oci" {
tenancy_ocid = "your_tenancy_ocid"
user_ocid = "your_user_ocid"
private_key_path = "/home/username/.oci/oci_api_key.pem"
fingerprint = "your_api_key_fingerprint"
region = "your_region"
}
버전 정보 파일(versions.tf)을 생성합니다:
vi versions.tf
terraform {
required_providers {
oci = {
source = "oracle/oci"
version = ">=4.67.3"
}
}
required_version = ">= 1.0.0"
}
3️⃣ 가용성 도메인 설정
가용성 도메인 정보를 확인하기 위한 파일을 생성합니다:
vi availability-domains.tf
data "oci_identity_availability_domains" "ads" {
compartment_id = var.tenancy_ocid
}
variable "tenancy_ocid" {
type = string
default = "your_tenancy_ocid"
}
🖥️ VM 생성 설정
1️⃣ VM 생성용 디렉토리 설정
mkdir ~/tf-compute
cd ~/tf-compute
cp ../tf-provider/provider.tf .
cp ../tf-provider/versions.tf .
cp ../tf-provider/availability-domains.tf .
2️⃣ 가용성 도메인 출력 설정
vi outputs.tf
# The "name" of the availability domain to be used for the compute instance.
output "name-of-first-availability-domain" {
value = data.oci_identity_availability_domains.ads.availability_domains[0].name
}
테라폼 초기화 및 적용:
terraform init
terraform plan
terraform apply
✅ 성공적으로 실행되면 name-of-first-availability-domain = "your-region-AD-1"
같은 출력을 확인할 수 있습니다.
3️⃣ VM 생성 설정
VM 생성 설정 파일(main.tf)을 작성합니다:
vi main.tf
resource "oci_core_instance" "generated_oci_core_instance" {
agent_config {
is_management_disabled = "false"
is_monitoring_disabled = "false"
plugins_config {
desired_state = "ENABLED"
name = "Compute Instance Monitoring"
}
// 기타 플러그인 설정...
}
availability_config {
is_live_migration_preferred = "true"
recovery_action = "RESTORE_INSTANCE"
}
availability_domain = "your-region-AD-1"
compartment_id = "your_compartment_id"
create_vnic_details {
assign_ipv6ip = "false"
assign_private_dns_record = "true"
assign_public_ip = "true"
subnet_id = "your_subnet_id"
}
display_name = "your-vm-name"
instance_options {
are_legacy_imds_endpoints_disabled = "false"
}
metadata = {
"ssh_authorized_keys" = "your_ssh_public_key"
}
shape = "VM.Standard.A1.Flex"
shape_config {
memory_in_gbs = "24"
ocpus = "4"
}
source_details {
boot_volume_size_in_gbs = "99"
boot_volume_vpus_per_gb = "10"
source_id = "your_os_image_id"
source_type = "image"
}
}
🚀 Node.js 자동화 봇 구축
1️⃣ Node.js 설치
# NodeSource 저장소 추가 (최신 LTS 버전인 20.x 기준)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
# Node.js 설치
sudo apt install -y nodejs
# 설치 확인
node --version
npm --version
2️⃣ VM 생성 스크립트 작성
cd ~/tf-compute/
vi create-a1-vm.js
스크립트 내용 예시 (여러분의 필요에 맞게 수정하세요):
const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
// VM 생성 함수
function createVM() {
console.log('🔄 테라폼 초기화 중...');
exec('terraform init', (error, stdout, stderr) => {
if (error) {
console.error(`❌ 초기화 오류: ${error.message}`);
return;
}
console.log('✅ 초기화 완료');
console.log('🚀 VM 생성 시작...');
exec('terraform apply -auto-approve', (error, stdout, stderr) => {
if (error) {
console.error(`❌ VM 생성 오류: ${error.message}`);
return;
}
console.log('✅ VM 생성 완료!');
// VM 정보 출력
console.log(stdout);
// 생성 시간 기록
const timestamp = new Date().toISOString();
fs.appendFileSync(
path.join(__dirname, 'vm-creation-log.txt'),
`${timestamp}: VM 생성 성공\n`
);
});
});
}
// 주기적으로 실행 (예: 24시간마다)
console.log('🤖 A1 VM 자동 생성 봇이 시작되었습니다');
createVM();
// 24시간마다 실행 (밀리초 단위)
setInterval(createVM, 24 * 60 * 60 * 1000);
3️⃣ PM2로 백그라운드 실행
PM2를 사용하여 스크립트를 백그라운드에서 지속적으로 실행합니다:
# PM2 전역 설치
sudo npm install -g pm2
# 스크립트 시작
pm2 start create-a1-vm.js --name "vm-creator"
# 상태 확인
pm2 status
# 로그 확인
pm2 logs vm-creator
🎉 완성!
이제 자동화된 A1 VM 생성 봇이 완성되었습니다! 이 봇은 설정한 주기에 따라 자동으로 VM을 생성하고 관리합니다.
💡 유용한 팁
- 리소스 모니터링: 오라클 클라우드 콘솔에서 생성된 VM과 리소스 사용량을 정기적으로 확인하세요.
- 비용 관리: A1 VM은 Always Free Tier이지만, 다른 관련 리소스(대역폭, 추가 스토리지 등)는 비용이 발생할 수 있으니 주의하세요.
- 보안: 프로덕션 환경에서는 API 키와 민감한 정보를 안전하게 관리하고, 적절한 보안 조치를 취하세요.
- 자동 복구: PM2의
--restart-delay
옵션을 사용하여 스크립트 실행 실패 시 자동으로 재시작되도록 설정할 수 있습니다.
⚠️ 주의사항
- 이 블로그 포스트의 내용은 교육 목적으로만 사용해주세요.
- 오라클 클라우드의 서비스 약관을 준수하세요.
- 실제 사용 시 개인 정보와 API 키를 보호하고, 이 코드에서는 중요 정보를 가렸습니다.
🙋♂️ 질문이나 의견이 있으신가요?
댓글로 남겨주시면 답변해 드리겠습니다. 행복한 클라우드 여정이 되시길 바랍니다! 🚀✨
🤖 Creating an Automated Oracle Cloud A1 VM Bot with Terraform
📚 Introduction
Hello there! Today I’m going to share how to create an automated bot using Terraform and Node.js that creates ARM-based A1 VMs on Oracle Cloud’s Always Free Tier. This project will be particularly useful for those who want to maximize their free VM resources! 😊
🛠️ Prerequisites
- Oracle Cloud account
- Linux environment (Ubuntu-based instructions)
- Basic knowledge of terminal commands and code editing
🔑 Environment Setup
1️⃣ System Update and Essential Tools
First, let’s update our system and install necessary tools:
sudo apt update && apt upgrade -y
sudo apt install -y vim
2️⃣ Install OCI CLI
Install the Oracle Cloud Infrastructure (OCI) CLI to access Oracle Cloud from the command line:
bash -c "$(curl -L https://raw.githubusercontent.com/oracle/oci-cli/master/scripts/install/install.sh)"
exec -l $SHELL
If needed, you can add path settings to your shell:
vi ~/.bashrc
# Add to the last line
export PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]$(pwd)\[\033[00m\]$ '
source ~/.bashrc
3️⃣ Configure OCI Settings
Configure the CLI settings:
oci setup config
📝 Important: When prompted for a passphrase during API key generation, you can enter “N/A” to set it up without a password.
4️⃣ Upload API Keys
Upload the generated API key (oci_api_key.pem) to the Oracle Cloud console:
- Log in to the Oracle Cloud console
- Navigate to Profile > User Settings > API Keys
- Upload the
oci_api_key.pem.pub
file
🏗️ Setting Up Terraform
1️⃣ Install Terraform
Download and install Terraform:
mkdir temp
cd temp
wget https://releases.hashicorp.com/terraform/1.7.5/terraform_1.7.5_linux_amd64.zip
unzip terraform_1.7.5_linux_amd64.zip
sudo mv terraform /usr/local/bin/
terraform -v # Verify installation
2️⃣ Configure Terraform Provider
Create a directory for basic provider settings:
mkdir ~/tf-provider
cd ~/tf-provider
Create a provider configuration file (provider.tf):
vi provider.tf
provider "oci" {
tenancy_ocid = "your_tenancy_ocid"
user_ocid = "your_user_ocid"
private_key_path = "/home/username/.oci/oci_api_key.pem"
fingerprint = "your_api_key_fingerprint"
region = "your_region"
}
Create a version information file (versions.tf):
vi versions.tf
terraform {
required_providers {
oci = {
source = "oracle/oci"
version = ">=4.67.3"
}
}
required_version = ">= 1.0.0"
}
3️⃣ Availability Domain Setup
Create a file to check availability domain information:
vi availability-domains.tf
data "oci_identity_availability_domains" "ads" {
compartment_id = var.tenancy_ocid
}
variable "tenancy_ocid" {
type = string
default = "your_tenancy_ocid"
}
🖥️ VM Creation Setup
1️⃣ Setup VM Creation Directory
mkdir ~/tf-compute
cd ~/tf-compute
cp ../tf-provider/provider.tf .
cp ../tf-provider/versions.tf .
cp ../tf-provider/availability-domains.tf .
2️⃣ Configure Availability Domain Output
vi outputs.tf
# The "name" of the availability domain to be used for the compute instance.
output "name-of-first-availability-domain" {
value = data.oci_identity_availability_domains.ads.availability_domains[0].name
}
Initialize and apply Terraform:
terraform init
terraform plan
terraform apply
✅ If successful, you’ll see output like name-of-first-availability-domain = "your-region-AD-1"
.
3️⃣ VM Creation Configuration
Create a VM configuration file (main.tf):
vi main.tf
resource "oci_core_instance" "generated_oci_core_instance" {
agent_config {
is_management_disabled = "false"
is_monitoring_disabled = "false"
plugins_config {
desired_state = "ENABLED"
name = "Compute Instance Monitoring"
}
// Other plugin configurations...
}
availability_config {
is_live_migration_preferred = "true"
recovery_action = "RESTORE_INSTANCE"
}
availability_domain = "your-region-AD-1"
compartment_id = "your_compartment_id"
create_vnic_details {
assign_ipv6ip = "false"
assign_private_dns_record = "true"
assign_public_ip = "true"
subnet_id = "your_subnet_id"
}
display_name = "your-vm-name"
instance_options {
are_legacy_imds_endpoints_disabled = "false"
}
metadata = {
"ssh_authorized_keys" = "your_ssh_public_key"
}
shape = "VM.Standard.A1.Flex"
shape_config {
memory_in_gbs = "24"
ocpus = "4"
}
source_details {
boot_volume_size_in_gbs = "99"
boot_volume_vpus_per_gb = "10"
source_id = "your_os_image_id"
source_type = "image"
}
}
🚀 Building the Node.js Automation Bot
1️⃣ Install Node.js
# Add NodeSource repository (for latest LTS version 20.x)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
# Install Node.js
sudo apt install -y nodejs
# Verify installation
node --version
npm --version
2️⃣ Create VM Creation Script
cd ~/tf-compute/
vi create-a1-vm.js
Example script content (modify according to your needs):
const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
// VM creation function
function createVM() {
console.log('🔄 Initializing Terraform...');
exec('terraform init', (error, stdout, stderr) => {
if (error) {
console.error(`❌ Initialization error: ${error.message}`);
return;
}
console.log('✅ Initialization complete');
console.log('🚀 Starting VM creation...');
exec('terraform apply -auto-approve', (error, stdout, stderr) => {
if (error) {
console.error(`❌ VM creation error: ${error.message}`);
return;
}
console.log('✅ VM creation complete!');
// Output VM information
console.log(stdout);
// Record creation time
const timestamp = new Date().toISOString();
fs.appendFileSync(
path.join(__dirname, 'vm-creation-log.txt'),
`${timestamp}: VM creation successful\n`
);
});
});
}
// Run periodically (e.g., every 24 hours)
console.log('🤖 A1 VM Automatic Creation Bot has started');
createVM();
// Run every 24 hours (in milliseconds)
setInterval(createVM, 24 * 60 * 60 * 1000);
3️⃣ Run in Background Using PM2
Use PM2 to run the script continuously in the background:
# Install PM2 globally
sudo npm install -g pm2
# Start the script
pm2 start create-a1-vm.js --name "vm-creator"
# Check status
pm2 status
# View logs
pm2 logs vm-creator
🎉 Completion!
Your automated A1 VM creation bot is now complete! This bot will automatically create and manage VMs according to your configured schedule.
💡 Useful Tips
- Resource Monitoring: Regularly check your created VMs and resource usage in the Oracle Cloud console.
- Cost Management: While A1 VMs are part of the Always Free Tier, other related resources (bandwidth, additional storage, etc.) may incur costs, so be careful.
- Security: In a production environment, securely manage your API keys and sensitive information, and implement appropriate security measures.
- Automatic Recovery: Use PM2’s
--restart-delay
option to automatically restart the script in case of execution failure.
⚠️ Cautions
- Use the content of this blog post for educational purposes only.
- Comply with Oracle Cloud’s terms of service.
- When using this in practice, protect your personal information and API keys – sensitive information has been redacted in this code.
🙋♂️ Questions or Comments?
Feel free to leave them in the comments section below, and I’ll be happy to respond. Wishing you a happy cloud journey! 🚀✨