はじめに
新しくサーバを建てたとき、毎回行っている作業を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]"