cloud-initとは?
インスタンスの初期設定を自動化するツールです。
インスタンス起動時に、パッケージのインストールやユーザー作成、設定ファイルの変更などを自動で実行できます。AWSやOCIなど主要なクラウドサービスでサポートされています。
metadataブロックでスクリプトファイルを指定
TerraformでOCIのインスタンスを作成する場合、user_dataとしてbase64でエンコードしたファイルを指定することでcloud-initを利用できます。
main:tf
resource "oci_core_instance" "this" {
count = var.env == "develop" ? 1 : 2
availability_domain = var.availability_domain
compartment_id = var.compartment_id_sub
display_name = "${var.name}-${count.index}"
shape = var.shape
shape_config {
ocpus = var.ocpu
memory_in_gbs = var.memory
}
source_details {
source_id = var.source_id
source_type = var.source_type
}
create_vnic_details {
nsg_ids = [
var.security_group
]
subnet_id = var.subnet_id
}
metadata = {
ssh_authorized_keys = var.ssh_keys
user_data = base64encode(file("${path.module}/userdata/setStartup.sh"))
}
}
スクリプトファイルのサンプル
Nginxをインストールして起動する場合のサンプルです。
setStartup.sh
#!/bin/bash
dnf update -y
dnf install emacs -y
dnf install nginx -y
systemctl enable nginx
systemctl start nginx
firewall-offline-cmd --permanent --add-port=80/tcp
firewall-cmd --reload