LoginSignup
11
10

More than 5 years have passed since last update.

【ansible】 サーバの初期設定を自動化する

Last updated at Posted at 2017-11-19

はじめに

新しくサーバを建てたとき、毎回行っている作業をansibleを使って自動化していきます。
今回行う設定は【CentOS7】サーバの初期設定と同じ内容になっています。

実行環境

  • CentOS7

ansibleのインストール

# yum install epel-release
# yum install ansible

playbookを作成

init.yml
- hosts: localhost
  vars:
    user_name: user  # 作成するユーザ名を指定する
  tasks:
    - name: add user.
      user: 
        name: "{{user_name}}"
        createhome: yes

    - 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: /root/.ssh/authorized_keys
        dest: /home/{{user_name}}/.ssh/authorized_keys
        owner: "{{user_name}}"
        group: "{{user_name}}"
        mode: 0600

    - name: add sudoers.
      lineinfile:
        path: /etc/sudoers
        state: present
        regexp: "^%{{user_name}} ALL="
        line: "%{{user_name}} ALL=(ALL) NOPASSWD: ALL"
        validate: '/usr/sbin/visudo -cf %s'

    - name: comment out PermitRootLogin yes
      lineinfile:
        path: /etc/ssh/sshd_config
        state: present
        regexp: "^PermitRootLogin yes"
        regexp: "^#PermitRootLogin yes"
        line: "#PermitRootLogin yes"

    - name: add PermitRootLogin no
      lineinfile:
        path: /etc/ssh/sshd_config
        state: present
        regexp: "^PermitRootLogin no"
        insertafter: '^#PermitRootLogin yes'
        line: "PermitRootLogin no"

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

playbookの実行

直接playbookにユーザ名を指定するか、
--extra-varsオプションを使ってユーザ名の指定ができる

# ansible-playbook init-server.yml --extra-vars "user_name=[username]"
11
10
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
11
10