AnsibleでCentOS8初期セットアップ用のプレイブック(Ver2)を作成してみました

AnsibleでCentOS8インストール後の初期セットアップ用のプレイブック(ver2)を作成してみました。
bondingの設定も実施します。

ググるとSSH公開鍵認証での使用例が多いですが、大量の初期セットアップを時間をかけずに実施したい目的なので、
SSHパスワード認証での使用方法を記載します。

yum updateやIPv6無効化、Firewalld無効化、NTP設定、追加パッケージ、リポジトリインストール、chrony設定
を追記しました。

1.環境
コントロールノード(指示を出すサーバ):CentOS8.2
ターゲットノード(指示を受けるサーバ):CentOS8.2 2台
ホスト:centos8-12
Playbook実行前
ens192:192.168.0.35
ens224:
ens256:

Playbook実行後
ens192:bond_slave
ens224:bond_slave
ens256:
bond0:192.168.0.35

ホスト:centos8-13
Playbook実行前
ens192:192.168.0.36
ens224:
ens256:

Playbook実行後
ens192:bond_slave
ens224:bond_slave
ens256:
bond0:192.168.0.36

ansibleバージョン:2.9.11

※注意点としては、nmcliモジュールでbond0を作成すると、BOOTPROTO=dhcpの設定が残ってしまいます。
対策として、
commandモジュールでnmcli connection modify コマンドを発行して、設定を上書きします。
さらに、ens192の元の設定が残っていて同じIPで2つIFがUPしてしまうので、
元のconnection設定”System ens192″を削除します。
冪等性(べきとうせい)を担保する為にwhen句でチェックもします。

2.Ansibleの導入
コントロールノードで実行

yum install epel-release -y
yum install ansible
ansible --version

3.プレイブックの処理の内容


/etc/hosts
/etc/NetworkManager/NetworkManager.conf
/etc/resolv.conf
/etc/selinux/config
/etc/yum.conf
のバックアップファイルを確認し、無ければバックアップを取得する。
②.ホスト名の変更
③.NetworkManagerのDNSオプション無効化
④.resolv.confの設定
⑤.hostsファイルの設定
⑥.NTPサービスの再起動
⑦.SELinuxの無効化
⑧.Firewalldの無効化
⑨.IPv6の無効化
⑩.NetworkManagerの起動
⑪.bondigモジュールの有効化
⑫.bonding接続プロファイルの作成
⑬.bonding接続プロファイル編集
⑭.bonding接続プロファイル編集2
⑮.”System ens192″の確認
⑯.”System ens192″の削除
⑰.bonding Slave接続プロファイル作成
⑱.yum.confにてカーネル、リリースアップデートの除外設定
⑲.yum update
⑳.追加パッケージ(chronyd)、追加リポジトリ(epel,remi)のインストール
㉑.chrony設定
㉒.chronyd再起動
㉓.サーバ再起動
㉔.サーバ再起動後の疎通確認

4.インベントリファイルとプレイブック配置用ディレクトリ作成

mkdir /etc/ansible/setup_centos8
mkdir /etc/ansible/setup_centos8/inventory
mkdir /etc/ansible/setup_centos8/group_vars
mkdir /etc/ansible/setup_centos8/host_vars
mkdir /etc/ansible/setup_centos8/roles
mkdir /etc/ansible/setup_centos8/roles/common
mkdir /etc/ansible/setup_centos8/roles/common/resolver
mkdir /etc/ansible/setup_centos8/roles/common/resolver/tasks
mkdir /etc/ansible/setup_centos8/roles/common/resolver/files
mkdir /etc/ansible/setup_centos8/roles/common/resolver/templates
mkdir /etc/ansible/setup_centos8/roles/common/networks
mkdir /etc/ansible/setup_centos8/roles/common/networks/tasks
mkdir /etc/ansible/setup_centos8/roles/common/packages
mkdir /etc/ansible/setup_centos8/roles/common/packages/tasks
mkdir /etc/ansible/setup_centos8/roles/common/packages/vars
mkdir /etc/ansible/setup_centos8/roles/common/chronyset
mkdir /etc/ansible/setup_centos8/roles/common/chronyset/tasks
mkdir /etc/ansible/setup_centos8/roles/common/reboot
mkdir /etc/ansible/setup_centos8/roles/common/reboot/tasks

5.インベントリファイルの作成
グループ毎にパスワードが異なる前提で記述してみました。

vi /etc/ansible/setup_centos8/inventory/inventory.ini

[webservers]
centos8-12 ansible_host=192.168.0.35

[dbservers]
centos8-13.test.local ansible_host=192.168.0.36

[linux_servers:children]
webservers
dbservers



[webservers:vars]
ansible_ssh_port=22
ansible_ssh_user=root
ansible_ssh_pass=password1
ansible_sudo_pass=password1

[dbservers:vars]
ansible_ssh_port=22
ansible_ssh_user=root
ansible_ssh_pass=password2
ansible_sudo_pass=password2

6.pingによる疎通確認
インベントリファイルを作成したら、まずは対象ノードと疎通できるか確認してみましょう。

事前キー登録
ssh 192.168.0.35
ssh 192.168.0.36

でyesを応答する。

cd /etc/ansible/setup_centos8
ansible all -i ./inventory/inventory.ini -m ping

7.プレイブックの作成

#起点になるymlファイルの作成
vi /etc/ansible/setup_centos8/linux_initialsetup.yml

- hosts: all
  become: true
#  become_method: su
  roles:
   - name: common/resolver
     tags: resolver
   - name: common/networks
     tags: networks
   - name: common/packages
     tags: packages
   - name: common/chronyset
     tags: chronyset
   - name: common/reboot
     tags: reboot

#設定変更処理の記述
vi /etc/ansible/setup_centos8/roles/common/resolver/tasks/main.yml

#バックアップの確認1(/etc/hosts)
- name: main / backup_check(/etc/hosts)
  stat:
    path: /etc/hosts_org
  register: hosts_org

#バックアップの取得1(/etc/hosts)
- name: main / backup(/etc/hosts)
  copy:
    src: /etc/hosts
    dest: /etc/hosts_org
    remote_src: yes
  when: not hosts_org.stat.exists


#バックアップの確認2(/etc/NetworkManager/NetworkManager.conf)
- name: main / backup_check(/etc/NetworkManager/NetworkManager.conf)
  stat:
    path: /etc/NetworkManager/NetworkManager.conf_org
  register: NetworkManager_conf_org

#バックアップの取得2(/etc/NetworkManager/NetworkManager.conf)
- name: main / backup(/etc/NetworkManager/NetworkManager.conf)
  copy:
    src: /etc/NetworkManager/NetworkManager.conf
    dest: /etc/NetworkManager/NetworkManager.conf_org
    remote_src: yes
  when: not NetworkManager_conf_org.stat.exists

#バックアップの確認3(/etc/resolv.conf)
- name: main / backup_check(/etc/resolv.conf)
  stat:
    path: /etc/resolv.conf_org
  register: resolv_conf_org

#バックアップの取得3(/etc/resolv.conf)
- name: main / backup(/etc/resolv.conf)
  copy:
    src: /etc/resolv.conf
    dest: /etc/resolv.conf_org
    remote_src: yes
  when: not resolv_conf_org.stat.exists

#バックアップの確認4(/etc/selinux/config)
- name: main / backup_check(/etc/selinux/config)
  stat:
    path: /etc/selinux/config_org
  register: selinux_config_org

#バックアップの取得4(/etc/selinux/config)
- name: main / backup(/etc/selinux/config)
  copy:
    src: /etc/selinux/config
    dest: /etc/selinux/config_org
    remote_src: yes
  when: not selinux_config_org.stat.exists

#バックアップの確認5(/etc/yum.conf)
- name: main / backup_check(/etc/yum.conf)
  stat:
    path: /etc/yum.conf_org
  register: yum_conf_org

#バックアップの取得5(/etc/yum.conf)
- name: main / backup(/etc/yum.conf)
  copy:
    src: /etc/yum.conf
    dest: /etc/yum.conf_org
    remote_src: yes
  when: not yum_conf_org.stat.exists

#ホスト名の設定
- name: main / Set_hostname
#      become: true
  hostname: name="{{ inventory_hostname_short }}"

#NetworkManagerのリゾルバ設定
- name: main / Set resolver setting
  ini_file:
        dest: /etc/NetworkManager/NetworkManager.conf
        section: main
        option: dns
        value: none

#resolv.confの設定
- name: main / Deploy resolv.conf
  copy:
        src: resolv.conf
        dest: /etc/resolv.conf
        owner: root
        group: root
        mode: 0644

#hostsファイルの設定
- name: main / Deploy hosts file
  template:
        src: hosts.j2
        dest: /etc/hosts
        owner: root
        group: root
        mode: 0644

#NTPサービスの再起動
#- name: main / restart NTP sevice
#  systemd:
#        name: ntpd
#        state: restarted
#        enabled: yes

#SELinuxの無効化
- name: main / Disable SELinux
  selinux:
         state: disabled

#firewalldの無効化
- name: main / Disable firewalld
  systemd:
        name: firewalld
        state: stopped
        enabled: no

#IPv6の無効化
- name: main / Disable IPv6
  sysctl:
        name: '{{ item }}'
        value: '1'
  with_items:
        - net.ipv6.conf.all.disable_ipv6
        - net.ipv6.conf.default.disable_ipv6



#配布用ファイルの準備

vi /etc/ansible/setup_centos8/roles/common/resolver/files/resolv.conf
# Generated by NetworkManager
nameserver 192.168.0.1


#hostsファイル作成用処理
vi /etc/ansible/setup_centos8/roles/common/resolver/templates/hosts.j2
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4 {{ inventory_hostname }}

{% for item in play_hosts %}
{% set short_name = item.split('.') %}
{{ hostvars[item]['ansible_default_ipv4']['address'] }}  {{ item }} {{ short_name[0] }}
{% endfor %}


#リブート処理
vi /etc/ansible/setup_centos8/roles/common/reboot/tasks/main.yml

- name: main / do sync             # sync実行
  shell: sync
- name: main / reboot              # 再起動
  shell: reboot
  async: 1                  # 非同期実行(一旦sshのコネクションが切れるが、それをエラーとしない為の対処)
  poll: 0                   # 非同期実行時にshellモジュールの戻りを待たない(同上)
- name: main / wait for reboot     # 再起動後のssh再接続待ち
  wait_for_connection:
   delay: 20               # reboot後20秒後から確認実施
   timeout: 300            # 確認タイムアウトは5分
- name: main / check connection    # 導通チェック
  ping:

8.グループ変数の設定

vi /etc/ansible/setup_centos8/group_vars/linux_servers.yml
---
operation_gw: "192.168.0.1"

network_bond:
    - {conn_name: 'bond0', ip4: "{{ operation_ip }}", gw4: "{{ operation_gw }}"}
network_bond_slave:
    - {conn_name: 'ens192' , master: 'bond0'}
    - {conn_name: 'ens224' , master: 'bond0'}

9.host変数の設定

vi /etc/ansible/setup_centos8/host_vars/centos8-12.yml
---
operation_ip: "{{ ansible_host }}/24"

vi /etc/ansible/setup_centos8/host_vars/centos8-13.yml
---
operation_ip: "{{ ansible_host }}/24"

10.ネットワーク設定変更処理の記述

vi /etc/ansible/setup_centos8/roles/common/networks/tasks/main.yml

#NetworkManagerの起動
- name: main / Start NetworkManager
  systemd:
    name: NetworkManager
    state: started
    enabled: yes

#bondigモジュールの有効化
- name: main / Load bonding module
  modprobe:
    name: bonding
    state: present

#bonding接続プロファイルの作成
- name: main / Add bonding connection
  nmcli:
    type: bond
    conn_name: "{{ item.conn_name }}"
    mode: "balance-rr"
    state: present
  with_items:
    - "{{ network_bond }}"
  when: ansible_bond0 is not defined

#bonding接続プロファイル編集
- name: main / Modify bonding connection
  nmcli:
    type: bond
    conn_name: "{{ item.conn_name }}"
    ip4: "{{ item.ip4 }}"
    gw4: "{{ item.gw4 }}"
    state: present
  with_items:
    - "{{ network_bond }}"

#bonding接続プロファイル編集2
- name: main / Modify bonding connection2
  command: nmcli connection modify {{ item.conn_name }} ipv4.method manual ipv4.addresses {{ item.ip4 }} ipv4.gateway {{ item.gw4 }}
  with_items:
    - "{{ network_bond }}"

#"System ens192"の確認
- name: main / Check connection "System ens192"
  command: nmcli connection
  register: con_sys_ens192

#"System ens192"の削除
- name: main / Delete connection "System ens192"
  command: nmcli connection delete "System ens192"
  when: "'System ens192' in con_sys_ens192.stdout"

#bonding Slave接続プロファイル作成
- name: main / Add bonding slave connection
  nmcli:
    type: bond-slave
    conn_name: "{{ item.conn_name }}"
    master: "{{ item.master }}"
    state: present
  with_items:
    - "{{ network_bond_slave }}"

11.パッケージタスク処理の記述

vi /etc/ansible/setup_centos8/roles/common/packages/tasks/main.yml

#変数読み込み
- name: mail / Add packages var
  include_vars: "packages.yml"

#yum.conf設定
- name: main / yum.conf setting
  lineinfile:
    dest=/etc/yum.conf
    line={{ item }}
  with_items:
        - 'exclude=kernel* centos-release*'

#yum update
- name: main / Update yum packages
  yum:
    name: "{{ item }}"
    state: latest
    update_cache: yes
  with_items:
    - "*"

#yum install
- name: main / Install the required packages
  yum:
    name: "{{ item }}"
    state: present
  with_items: "{{ required_packages }}"

vi /etc/ansible/setup_centos8/roles/common/packages/vars/packages.yml
---
required_packages:
 - "chrony"
#追加リポジトリ
 - "epel-release"
 - "https://rpms.remirepo.net/enterprise/remi-release-8.rpm"

12.NTP設定処理の記述

vi /etc/ansible/setup_centos8/roles/common/chronyset/tasks/main.yml

#バックアップの確認(/etc/chrony.conf)
- name: main / backup_check(/etc/chrony.conf)
  stat:
    path: /etc/chrony.conf_org
  register: chrony_conf_org

#バックアップの取得(/etc/chrony.conf)
- name: main / backup(/etc/chrony.conf)
  copy:
    src: /etc/chrony.conf
    dest: /etc/chrony.conf_org
    remote_src: yes
  when: not chrony_conf_org.stat.exists

#chrony.conf設定変更
- name: main / chrony.conf setting
  replace:
    dest=/etc/chrony.conf
    regexp='^pool 2.centos.pool.ntp.org iburst' 
    replace='pool 192.168.0.1 iburst'

#chronydの再起動
- name: Restart chronyd
  systemd:
        name: chronyd
        state: restarted
        enabled: yes

13.プレイブックの処理の実行

cd /etc/ansible/setup_centos8
ansible-playbook -i ./inventory/inventory.ini ./linux_initialsetup.yml

実行結果

PLAY [all] *********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [centos8-12]
ok: [centos8-13.test.local]

TASK [common/resolver : main / backup_check(/etc/hosts)] ***********************
ok: [centos8-12]
ok: [centos8-13.test.local]

TASK [common/resolver : main / backup(/etc/hosts)] *****************************
skipping: [centos8-12]
skipping: [centos8-13.test.local]

TASK [common/resolver : main / backup_check(/etc/NetworkManager/NetworkManager.conf)] ***
ok: [centos8-12]
ok: [centos8-13.test.local]

TASK [common/resolver : main / backup(/etc/NetworkManager/NetworkManager.conf)] ***
skipping: [centos8-12]
skipping: [centos8-13.test.local]

TASK [common/resolver : main / backup_check(/etc/resolv.conf)] *****************
ok: [centos8-12]
ok: [centos8-13.test.local]

TASK [common/resolver : main / backup(/etc/resolv.conf)] ***********************
skipping: [centos8-12]
skipping: [centos8-13.test.local]

TASK [common/resolver : main / backup_check(/etc/selinux/config)] **************
ok: [centos8-13.test.local]
ok: [centos8-12]

TASK [common/resolver : main / backup(/etc/selinux/config)] ********************
skipping: [centos8-12]
skipping: [centos8-13.test.local]

TASK [common/resolver : main / backup_check(/etc/yum.conf)] ********************
ok: [centos8-12]
ok: [centos8-13.test.local]

TASK [common/resolver : main / backup(/etc/yum.conf)] **************************
skipping: [centos8-12]
skipping: [centos8-13.test.local]

TASK [common/resolver : main / Set_hostname] ***********************************
ok: [centos8-12]
ok: [centos8-13.test.local]

TASK [common/resolver : main / Set resolver setting] ***************************
ok: [centos8-13.test.local]
ok: [centos8-12]

TASK [common/resolver : main / Deploy resolv.conf] *****************************
ok: [centos8-13.test.local]
ok: [centos8-12]

TASK [common/resolver : main / Deploy hosts file] ******************************
ok: [centos8-13.test.local]
ok: [centos8-12]

TASK [common/resolver : main / Disable SELinux] ********************************
ok: [centos8-13.test.local]
ok: [centos8-12]

TASK [common/resolver : main / Disable firewalld] ******************************
ok: [centos8-13.test.local]
ok: [centos8-12]

TASK [common/resolver : main / Disable IPv6] ***********************************
ok: [centos8-12] => (item=net.ipv6.conf.all.disable_ipv6)
ok: [centos8-13.test.local] => (item=net.ipv6.conf.all.disable_ipv6)
ok: [centos8-12] => (item=net.ipv6.conf.default.disable_ipv6)
ok: [centos8-13.test.local] => (item=net.ipv6.conf.default.disable_ipv6)

TASK [common/networks : main / Start NetworkManager] ***************************
ok: [centos8-13.test.local]
ok: [centos8-12]

TASK [common/networks : main / Load bonding module] ****************************
ok: [centos8-13.test.local]
ok: [centos8-12]

TASK [common/networks : main / Add bonding connection] *************************
skipping: [centos8-12] => (item={'conn_name': 'bond0', 'ip4': '192.168.0.35/24', 'gw4': '192.168.0.1'})
skipping: [centos8-13.test.local] => (item={'conn_name': 'bond0', 'ip4': '192.168.0.36/24', 'gw4': '192.168.0.1'})

TASK [common/networks : main / Modify bonding connection] **********************
changed: [centos8-13.test.local] => (item={'conn_name': 'bond0', 'ip4': '192.168.0.36/24', 'gw4': '192.168.0.1'})
changed: [centos8-12] => (item={'conn_name': 'bond0', 'ip4': '192.168.0.35/24', 'gw4': '192.168.0.1'})

TASK [common/networks : main / Modify bonding connection2] *********************
changed: [centos8-13.test.local] => (item={'conn_name': 'bond0', 'ip4': '192.168.0.36/24', 'gw4': '192.168.0.1'})
changed: [centos8-12] => (item={'conn_name': 'bond0', 'ip4': '192.168.0.35/24', 'gw4': '192.168.0.1'})

TASK [common/networks : main / Check connection "System ens192"] ***************
changed: [centos8-12]
changed: [centos8-13.test.local]

TASK [common/networks : main / Delete connection "System ens192"] **************
skipping: [centos8-12]
skipping: [centos8-13.test.local]

TASK [common/networks : main / Add bonding slave connection] *******************
changed: [centos8-12] => (item={'conn_name': 'ens192', 'master': 'bond0'})
changed: [centos8-13.test.local] => (item={'conn_name': 'ens192', 'master': 'bond0'})
changed: [centos8-12] => (item={'conn_name': 'ens224', 'master': 'bond0'})
changed: [centos8-13.test.local] => (item={'conn_name': 'ens224', 'master': 'bond0'})

TASK [common/packages : mail / Add packages var] *******************************
ok: [centos8-12]
ok: [centos8-13.test.local]

TASK [common/packages : main / yum.conf setting] *******************************
ok: [centos8-13.test.local] => (item=exclude=kernel* centos-release*)
ok: [centos8-12] => (item=exclude=kernel* centos-release*)

TASK [common/packages : main / Update yum packages] ****************************
[DEPRECATION WARNING]: Invoking "yum" only once while using a loop via
squash_actions is deprecated. Instead of using a loop to supply multiple items
and specifying `name: "{{ item }}"`, please use `name: ['*']` and remove the
loop. This feature will be removed in version 2.11. Deprecation warnings can be
 disabled by setting deprecation_warnings=False in ansible.cfg.
[DEPRECATION WARNING]: Invoking "yum" only once while using a loop via
squash_actions is deprecated. Instead of using a loop to supply multiple items
and specifying `name: "{{ item }}"`, please use `name: ['*']` and remove the
loop. This feature will be removed in version 2.11. Deprecation warnings can be
 disabled by setting deprecation_warnings=False in ansible.cfg.
ok: [centos8-12] => (item=['*'])
ok: [centos8-13.test.local] => (item=['*'])

TASK [common/packages : main / Install the required packages] ******************
[DEPRECATION WARNING]: Invoking "yum" only once while using a loop via
squash_actions is deprecated. Instead of using a loop to supply multiple items
and specifying `name: "{{ item }}"`, please use `name: '{{ required_packages
}}'` and remove the loop. This feature will be removed in version 2.11.
Deprecation warnings can be disabled by setting deprecation_warnings=False in
ansible.cfg.
[DEPRECATION WARNING]: Invoking "yum" only once while using a loop via
squash_actions is deprecated. Instead of using a loop to supply multiple items
and specifying `name: "{{ item }}"`, please use `name: '{{ required_packages
}}'` and remove the loop. This feature will be removed in version 2.11.
Deprecation warnings can be disabled by setting deprecation_warnings=False in
ansible.cfg.
ok: [centos8-12] => (item=['chrony', 'epel-release', 'https://rpms.remirepo.net/enterprise/remi-release-8.rpm'])
ok: [centos8-13.test.local] => (item=['chrony', 'epel-release', 'https://rpms.remirepo.net/enterprise/remi-release-8.rpm'])

TASK [common/chronyset : main / backup_check(/etc/chrony.conf)] ****************
ok: [centos8-12]
ok: [centos8-13.test.local]

TASK [common/chronyset : main / backup(/etc/chrony.conf)] **********************
skipping: [centos8-12]
skipping: [centos8-13.test.local]

TASK [common/chronyset : main / chrony.conf setting] ***************************
ok: [centos8-12]
ok: [centos8-13.test.local]

TASK [common/chronyset : Restart chronyd] **************************************
changed: [centos8-12]
changed: [centos8-13.test.local]

TASK [common/reboot : main / do sync] ******************************************
changed: [centos8-12]
changed: [centos8-13.test.local]

TASK [common/reboot : main / reboot] *******************************************
changed: [centos8-13.test.local]
changed: [centos8-12]

TASK [common/reboot : main / wait for reboot] **********************************
ok: [centos8-12]
ok: [centos8-13.test.local]

TASK [common/reboot : main / check connection] *********************************
ok: [centos8-13.test.local]
ok: [centos8-12]

PLAY RECAP *********************************************************************
centos8-12                 : ok=30   changed=7    unreachable=0    failed=0    skipped=8    rescued=0    ignored=0
centos8-13.test.local      : ok=30   changed=7    unreachable=0    failed=0    skipped=8    rescued=0    ignored=0

14.あとがき

初期セットアップの処理内容がだいぶ網羅できてきたと思います。
あとは、SNMP設定とsyslog転送設定くらいでしょうか。

Comments are closed.