LoginSignup
55
48

More than 3 years have passed since last update.

itamaeでConoHaのVPSの初期設定を自動化する

Last updated at Posted at 2014-11-16

目標

以下の作業をitamaeレシピにして自動化することを目標とする。

  • 一般ユーザーの作成
  • 鍵認証の設定
  • sudo有効化
  • sshとiptablesの設定

下準備

パスワード準備

レシピにはパスワードをSHA512で暗号化したものをいれなければならないが、例えば以下のように生成できる。

$ gem install unix-crypt
$ mkunixcrypt -s "salt"
Enter password:
Verify password:
$6$salt$...

rootでsshできるか確認

「サーバーリスト > コンソール」から秘密鍵をダウンロードし、パーミッションを600にしておく。
rootで「サーバーリスト > DNS逆引き設定」のIPアドレスにその鍵でsshできることを確かめておく。

秘密鍵を仮に~/.ssh/id_rsa.conohaにおいたとすると、以降、一般ユーザーでsshできるようにするまでは以下のようにレシピを実行する前提で書く。

$ gem install itamae
$ itamae ssh recipe.rb -h [IPアドレス] -u root -i ~/.ssh/id_rsa.conoha

最初は1つのレシピに全部書いて、後で分割すればいいと思う。

一般ユーザーの作成

templates/sudoers

元々/etc/sudoers にあるやつを以下のように変更したものを、templatesディレクトリとかを作って配置しておく

## Allows people in group wheel to run all commands
-# %wheel   ALL=(ALL)   ALL
+%wheel ALL=(ALL)   ALL

レシピ

USER_NAME = "k0kubun"     # 変更する
SSH_KEY   = "ssh-rsa ..." # 変更する
WHEEL_GID = 10

user USER_NAME do
  password "$6$...$..." # 前の節でmkunixcryptで生成したやつ
  gid WHEEL_GID
end

directory "/home/#{USER_NAME}/.ssh" do
  owner USER_NAME
  group USER_NAME
  mode  "700"
end

# 公開鍵でssh可能にする
file "/home/#{USER_NAME}/.ssh/authorized_keys" do
  content SSH_KEY
  owner USER_NAME
  group USER_NAME
  mode  "600"
end

# sudo可能にする
template "/etc/sudoers" do
  source "templates/sudoers"
  mode   "440"
  owner  "root"
  group  "root"
end

これで一般ユーザーに公開鍵でssh可能かつsudo可能になった。

sshとiptablesの設定

以下のような変更を加えたsshd_configとiptablesを用意しておく。

templates/sshd_config

  • rootログイン無効化
  • パスワードログイン無効化
  • ssh用ポートを22番から変更

templates/iplables

  • ssh用に開いている22番を別のポートに変更
  • HTTP 80番のポートを開ける
  • HTTPS 443番のポートを開ける

レシピ

template "sshd_config" do
  path   "/etc/ssh/sshd_config"
  source "templates/sshd_config"
  mode   "600"
end

# sshd_configに変更があったら再起動
service "sshd" do
  subscribes :restart, "template[sshd_config]"
end

template "iptables" do
  path   "/etc/sysconfig/iptables"
  source "templates/iptables"
  mode   "600"
end

# iptablesに変更があったら再起動
service "iptables" do
  subscribes :restart, "template[iptables]"
end

これで最低限のセキュリティ対策ができた。

おわり

このようにitamaeを使うと簡単にVPSの初期設定を自動化することができる。

55
48
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
55
48