0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【OCI】インスタンス作成時にcloud-initからsystemdのカスタムサービスを設定する【リソースマネージャ】

Posted at

systemdのカスタムサービス

Linuxで特定のタスクを自動的に実行するためのユーザー定義のサービスです。これにより、アプリケーションやスクリプトをシステム起動時や特定の条件下で自動的に開始・停止できます。

要するに、systemctl start nginxなどのコマンドでNginxを操作できるのと同じように、任意のサービスを追加して利用できるということです。

Terraformでcloud-initを設定

コンピュートインスタンスのmetadataブロックでスクリプトファイルを指定します。

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"))
  }
}

カスタムサービスを作成するスクリプト

シェルスクリプトでは、カスタムサービスの設定ファイル(startup.service)と、そのカスタムサービスが実行するシェルスクリプト(startup.sh)を作成しています。

こうしておけば、インスタンスが(再)起動した際に、startup.shが自動で実行されます。

(なお、カスタムサービスの設定ファイルに関する詳細は、各自で調べてみてください。)

setStartup.sh
#!/bin/bash

echo "[Unit]
Description=Startup Script
After=network-online.target

[Service]
ExecStart=/usr/local/bin/startup.sh
Restart=always
RestartSec=5 

[Install]
WantedBy=multi-user.target" > /etc/systemd/system/startup.service

echo "#!/bin/bash

dnf update  

dnf install nginx -y 
systemctl enable nginx
systemctl start nginx

firewall-offline-cmd --add-port=80/tcp
firewall-cmd --reload" > /usr/local/bin/startup.sh

sudo chmod +x /usr/local/bin/startup.sh
sudo systemctl daemon-reload
sudo systemctl enable startup.service
sudo systemctl start startup.service
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?