LoginSignup
1
4

More than 5 years have passed since last update.

さくらvpsの初期設定をコマンド1つで完成させる

Last updated at Posted at 2018-04-11

概要

現在さくらVPS借りていろいろ作業しているけど、環境が汚くなるとたびたびOSの再インストールしていた。
そのたびにユーザ作成してSSH設定してsudoers設定してとメモ帳を開きながら何回もやって疲れてきた。

もう自動化したいと思って対応した時のメモ書き。

【さくらのVPS】サーバの初期設定ガイド
→ Step2の2~4 + sudoersの設定まで実施してくれるイメージ

環境

  • CentOS 7(Gitは初期で入っているはず)

入力するコマンドはこれだけ

git clone https://github.com/haruto167/ansible-init.git && sh ./ansible-init/startup.sh {username} {password}

※ {username} {password}は、ログインするときの新しいユーザ名とSSHのパスワードを入力する

おしまい!サーバセットアップ完了。鍵のダウンロード忘れずに!

ディレクトリ/home/{username}/.sshに鍵(id_rsa)が作成される → 重要:Shell実行後、ダウンロードしておく

何をしたの?

上の処理はGitHubからダウンロードしてShellをたたいている。
Shellは具体的には以下のことをしている。
1.Ansibleのダウンロード
2.Playbookを使ってymlで定義したタスクを実行

init.yml

- hosts: localhost
# 変数を用意
  vars: 
# 作成するユーザ名を指定する
    user_name: user  
# パスワード指定
    password: superpass 

  tasks:
# ユーザ追加
    - name: add user.
      user: 
        name: "{{user_name}}"
        createhome: yes
        password: "{{ password | password_hash('sha512') }}"
        update_password: on_create
# ユーザ作成と共に鍵を作成
        generate_ssh_key: yes 
      become: yes
# sshディレクトリ作成
    - name: make .ssh directory
      file:
        path: /home/{{user_name}}/.ssh
        state: directory
        owner: "{{user_name}}"
        group: "{{user_name}}"
        mode:  0700

    - name: copy ssh key
      copy:
        src: /home/{{user_name}}/.ssh/id_rsa.pub
        dest: /home/{{user_name}}/.ssh/authorized_keys
        owner: "{{user_name}}"
        group: "{{user_name}}"
        mode: 0600

    - name: add sudoers.
      lineinfile:
# sudoersを書き換える前にバックアップも作成しておく
        backup: yes 
        path: /etc/sudoers
        state: present
        regexp: "^%{{user_name}} ALL="
        line: "%{{user_name}} ALL=(ALL) NOPASSWD: ALL"
        validate: '/usr/sbin/visudo -cf %s'

    - name: sshd conf1
      lineinfile:
         backup: yes
         path:  /etc/ssh/sshd_config
         regexp: '^\#Port 22'
         line: 'Port 22'
         backrefs: yes

    - name: sshd conf2
      lineinfile:
        path:  /etc/ssh/sshd_config
        regexp: '^\#PermitRootLogin yes'
        line: 'PermitRootLogin no'
        backrefs: yes

    - name: sshd conf3
      lineinfile:
        path:  /etc/ssh/sshd_config
        regexp: '^PasswordAuthentication yes'
        line: 'PasswordAuthentication no'
        backrefs: yes

    - name: restart service sshd
      systemd:
        name: sshd
        state: restarted

検討したこと

今までのコマンドをシェルに全部書き込んでして流そうかと思ったが、
せっかくなのでインフラ側のツールの勉強も兼ね今回はAnsible(構成管理ツール)を使ってみる

参考サイト

1
4
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
1
4