AnsibleでCentOSの初期設定

Tag:

CentOSの初期設定として、作業ユーザーの登録、SSHの設定、言語設定などをansibleでまとめて実行してみます。

作業環境

今回は実験としてvagrant環境で作業を行います。
ansible_common2

ホストマシン(windows)上にゲストマシンを2台立ち上げて、片方をansible実行サーバー、もう片方をansible操作対象サーバーとした環境で作業を行います。

master|ansible実行サーバー
下記Vagrantfileをホストマシン上の「C:/master」上で実行します。

Vagrant.configure(2) do |config|
  config.vm.box = "bento/centos-7.2"

  config.vm.provider "virtualbox" do |vm|
    vm.memory = 2048
  end

  config.vm.define :master do |server|
    server.vm.synced_folder "C:/master/syncCode", "/home/vagrant/Code"
    server.vm.hostname = "master"
    server.vm.network "private_network", ip: "192.168.33.10"
  end
end

仮想マシン立ち上げ後、ログインして、ansibleをインストールしてください。

app|ansible操作対象サーバー
下記Vagrantfileをホストマシン上の「C:/app」上で実行します。

Vagrant.configure(2) do |config|
  config.vm.box = "bento/centos-7.2"

  config.vm.provider "virtualbox" do |vm|
    vm.memory = 2048
  end

  config.vm.define :app do |server|
    server.vm.synced_folder "C:/app/syncCode", "/vagrant/syncCode"
    server.vm.hostname = "app"
    server.vm.network "private_network", ip: "192.168.33.20"
  end
end

こちらのマシンが今回のansibleで初期設定を行うマシンになります。

構成ファイル

ここでは、masterに「/home/vagrant/Code/ansible」フォルダを作成し、下記ansible構成ファイルを用意します。

group_vars/
  all.yml
roles/
  common/
    files/
      authorized_keys    # 公開鍵
      sudoers            # sudo設定ファイル
    handlers/
      main.yml
    tasks/
      main.yml
    templates/
      sshd_config        # ssh設定ファイル
ansible.cfg
hosts
server_init.yml
group_vars/all.yml
変数を設定します。

---
ssh_user: ユーザ名
ssh_password: 暗号化したパスワード
ssh_groups: wheel 
ssh_port: 22
base_locale: LANG=ja_JP.UTF-8
base_timezone: Asia/Tokyo

パスワードは「openssl passwd -1 パスワード」で暗号化した値を設定します。

ssh_portは22以外にすべきですが、vagrantでポート変更すると、ホストマシンからゲストマシンへSSH接続できなくなるので22のままにしてます。

roles/common/files/sudoers
sudo設定ファイルでは、wheelでパスワード入力なしにsudoできるように設定しています。

## Sudoers allows particular users to run various commands as
## the root user, without needing the root password.
##
## Examples are provided at the bottom of the file for collections
## of related commands, which can then be delegated out to particular
## users or groups.
## 
## This file must be edited with the 'visudo' command.

## Host Aliases
## Groups of machines. You may prefer to use hostnames (perhaps using 
## wildcards for entire domains) or IP addresses instead.
# Host_Alias     FILESERVERS = fs1, fs2
# Host_Alias     MAILSERVERS = smtp, smtp2

## User Aliases
## These aren't often necessary, as you can use regular groups
## (ie, from files, LDAP, NIS, etc) in this file - just use %groupname 
## rather than USERALIAS
# User_Alias ADMINS = jsmith, mikem


## Command Aliases
## These are groups of related commands...

## Networking
# Cmnd_Alias NETWORKING = /sbin/route, /sbin/ifconfig, /bin/ping, /sbin/dhclient, /usr/bin/net, /sbin/iptables, /usr/bin/rfcomm, /usr/bin/wvdial, /sbin/iwconfig, /sbin/mii-tool

## Installation and management of software
# Cmnd_Alias SOFTWARE = /bin/rpm, /usr/bin/up2date, /usr/bin/yum

## Services
# Cmnd_Alias SERVICES = /sbin/service, /sbin/chkconfig

## Updating the locate database
# Cmnd_Alias LOCATE = /usr/bin/updatedb

## Storage
# Cmnd_Alias STORAGE = /sbin/fdisk, /sbin/sfdisk, /sbin/parted, /sbin/partprobe, /bin/mount, /bin/umount

## Delegating permissions
# Cmnd_Alias DELEGATING = /usr/sbin/visudo, /bin/chown, /bin/chmod, /bin/chgrp 

## Processes
# Cmnd_Alias PROCESSES = /bin/nice, /bin/kill, /usr/bin/kill, /usr/bin/killall

## Drivers
# Cmnd_Alias DRIVERS = /sbin/modprobe

# Defaults specification

#
# Disable "ssh hostname sudo <cmd>", because it will show the password in clear. 
#         You have to run "ssh -t hostname sudo <cmd>".
#
#Defaults requiretty

#
# Refuse to run if unable to disable echo on the tty. This setting should also be
# changed in order to be able to use sudo without a tty. See requiretty above.
#
Defaults   !visiblepw

#
# Preserving HOME has security implications since many programs
# use it when searching for configuration files. Note that HOME
# is already set when the the env_reset option is enabled, so
# this option is only effective for configurations where either
# env_reset is disabled or HOME is present in the env_keep list.
#
Defaults    always_set_home

Defaults    env_reset
Defaults    env_keep =  "COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORS"
Defaults    env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
Defaults    env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
Defaults    env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
Defaults    env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"

#
# Adding HOME to env_keep may enable a user to run unrestricted
# commands via sudo.
#
# Defaults   env_keep += "HOME"

Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin

## Next comes the main part: which users can run what software on 
## which machines (the sudoers file can be shared between multiple
## systems).
## Syntax:
##
## 	user	MACHINE=COMMANDS
##
## The COMMANDS section may have other options added to it.
##
## Allow root to run any commands anywhere 
root	ALL=(ALL) 	ALL

## Allows members of the 'sys' group to run networking, software, 
## service management apps and more.
# %sys ALL = NETWORKING, SOFTWARE, SERVICES, STORAGE, DELEGATING, PROCESSES, LOCATE, DRIVERS

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

## Same thing without a password
%wheel	ALL=(ALL)	NOPASSWD: ALL

## Allows members of the users group to mount and unmount the 
## cdrom as root
# %users  ALL=/sbin/mount /mnt/cdrom, /sbin/umount /mnt/cdrom

## Allows members of the users group to shutdown this system
# %users  localhost=/sbin/shutdown -h now

## Read drop-in files from /etc/sudoers.d (the # here does not mean a comment)
#includedir /etc/sudoers.d
roles/common/handlers/main.yml
notifyで呼ばれるタスクです。

---
- name: restart sshd
  service: name=sshd state=restarted
roles/common/templates/sshd_config
ssh設定ファイルでは、ポート変更、rootログイン拒否、公開鍵認証設定、パスワード認証拒否をしています。

#	$OpenBSD: sshd_config,v 1.93 2014/01/10 05:59:19 djm Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/bin:/usr/bin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#
Port {{ ssh_port }}
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

# The default requires explicit activation of protocol 1
#Protocol 2

# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 1024

# Ciphers and keying
#RekeyLimit default none

# Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
PermitRootLogin no
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#RSAAuthentication yes
PubkeyAuthentication yes

# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile	.ssh/authorized_keys

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
PasswordAuthentication no

# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes

# GSSAPI options
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no
#GSSAPIEnablek5users no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
# WARNING: 'UsePAM no' is not supported in Red Hat Enterprise Linux and may cause several
# problems.
UsePAM no

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
UsePrivilegeSeparation sandbox		# Default for new installations.
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

# override default of no subsystems
Subsystem	sftp	/usr/libexec/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#	X11Forwarding no
#	AllowTcpForwarding no
#	PermitTTY no
#	ForceCommand cvs server
UseDNS no
GSSAPIAuthentication no
hosts
Ansible操作対象ホストのIPアドレスを登録してます。

[app]
192.168.33.20
server_init.yml
ansible-playbookコマンドで指定するPLAYBOOKです。

---
- hosts: app
  roles:
    - common

roles/common/tasks/main.yml

メインとなるタスクを記述します。

---
# 作業ユーザー設定
- name: 作業ユーザー登録
  user: 
    name={{ssh_user}} 
    state=present 
    password={{ssh_password}} 
    groups={{ssh_groups}}
  tags: users

- name: ~/.sshディレクトリの権限変更
  file: path="/home/{{ssh_user}}/.ssh" state=directory owner={{ssh_user}} group={{ssh_user}} mode=0700
  tags: users

- name: 公開鍵設置
  copy: src="authorized_keys" dest="/home/{{ssh_user}}/.ssh/authorized_keys" owner={{ssh_user}} group={{ssh_user}} mode=0600
  tags: users

- name: sudoers設定ファイルをアップロード
  copy: src="sudoers" dest="/etc/sudoers" owner=root group=root mode=0440

# 基本設定
- name: システムアップデート
  command: yum -y update

- name: ロケール設定
  command: localectl set-locale {{ base_locale }}

- name: タイムゾーン設定
  command: timedatectl set-timezone {{ base_timezone }}

- name: 基本パッケージをインストール
  yum: name={{ item }} state=present
  with_items:
    - vim
    - git
    - ntp
    - sysstat

- name: ntpdを起動、自動起動の有効化
  service: name=ntpd state=started enabled=yes
  
# SELinux
- name: SELinuxの動作状況表示
  shell: getenforce
  tags: selinux

- name: permissiveモード(ポリシー違反のアクセスをログに書き出して許可)に変更
  selinux: policy=targeted state=permissive
  tags: selinux

# SSH設定
- name: ssh設定ファイルアップロード(ポート変更、rootログイン拒否、公開鍵認証設定、パスワード認証拒否)
  notify:
    - restart sshd
  template: src="sshd_config" dest="/etc/ssh/sshd_config" owner=root group=root mode=0600
  tags: sshd

- name: sshdの起動、マシン起動時の自動起動化
  service: name=sshd state=running enabled=yes
  tags: sshd

# ファイアウォール
- name: Start Services
  service: name=firewalld enabled=Yes state=started
  tags: firewalld

- name: 変更したsshポートを許可する。[permanent=true(永続設定) immediate=yes(即時反映)]
  firewalld: port={{ ssh_port }}/tcp permanent=true state=enabled immediate=yes zone=public
  tags: firewalld
  
- name: デフォルトのsshポートを拒否する。
  firewalld: service=ssh permanent=true state=disabled immediate=yes
  tags: firewalld

54行目でnotifyを記述しています。56行目のタスクが実行された場合、handlersフォルダ内の指定タスクが実行されます。なおhandlersフォルダ内のタスクは、すべてのタスクが終了後に実行されます。また、もし複数回notifyで指定されても1度だけの実行になります。

実行

masterの「/home/vagrant/Code/ansible」配下で下記コマンドを実行します。

ansible-playbook -i hosts server_init.yml -u root -k

コマンド実行後、パスワードが聞かれます。vagrant上に起動した仮想マシンのrootユーザーのパスワードは「vagrant」です。

実行完了後、masterからappに今回作成した作業ユーザーでSSH接続できるか確認してみて下さい。

スポンサーリンク