Ansible class #4

  • Post author:
  • 帖子最後修改:2023 年 1 月 24 日

1.Ansible 模擬考第一題,環境配置

請在 Workstation 上安裝 ansible 及組態 ansible.cfg、inventory , 其要求如下:

1. 安裝 ansible 及其必要之套件
2. 執行ansible目錄為 /home/student/web
3. 建立 /home/student/web/inventory
4. inventory 分別為:
servera.lab.example.com 為 dev 組
serverb.lab.example.com 及 serverc.lab.example.com 為 prod 組
serverd.lab.example.com 為 balancer組
prod 為 webservers 子組
5. 建立 /home/student/web/ansible.cfg,remote_user 為 devops

				
					vim .vimrc
set ts=2 sw=2 et
set cursorcolumn cursorline
hi CursorColumn cterm=none ctermbg=236 term=bold guibg=none guifg=none
hi cursorline cterm=none ctermbg=236 term=bold guibg=none guifg=none

mkdir ~/web
cd ~/web
vim inventory

[dev]
servera.lab.example.com

[prod]
serverb.lab.example.com
serverc.lab.example.com
[balancer]
serverd.lab.example.com

[webservers:children]
prod

#參考設定
vim /etc/ansible/ansible.cfg

vim ansible.cfg
[defaults]
inventory     = /home/student/web/inventory
sudo_user     = root
ask_sudo_pass = false
ask_pass      = fales
remote_user = devops
[privilege_escalation]
become=True
become_method=sudo
become_user=root
become_ask_pass=False

ansible all -m ping
serverb.lab.example.com | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
...









				
			

2.Ansible 模擬考第二題,配置 Yum 倉庫

請以ad-hoc command的方式建立YUM Repository的設定檔(CentOS-Stream-BaseOS 及 CentOS-Stream-AppStream YUM Repository 的參數),並將其腳本寫於 /home/student/web/repo.sh 內,及賦予執行權限,詳細內容如下:

CentOS-Stream-BaseOS: https://ftp.yz.yamagata-u.ac.jp/pub/linux/centos-stream/9-stream/BaseOS/x86_64/os/
CentOS-Stream-AppStream: https://ftp.yz.yamagata-u.ac.jp/pub/linux/centos-stream/9-stream/AppStream/x86_64/os/

GPGKEY:  https://ftp.iij.ad.jp/pub/linux/centos/RPM-GPG-KEY-CentOS-Official

* Repository name 請指定為 CentOS-Stream-BaseOS 及 CentOS-Stream-AppStream
* Repository Description 請指定為 CentOS-Stream-BaseOS 及 CentOS-Stream-BaseOS
* Repository GPG Check 設定為 True
* Repository Enable 設定為 True

				
					刪除已知厙
ansible all -i inventory -u devops -b -m file -a 'path=/etc/yum.repos.d/CentOS-Stream-BaseOS.repo state=absent'
ansible all -i inventory -u devops -b -m file -a 'path=/etc/yum.repos.d/CentOS-Stream-AppStream.repo state=absent'
				
			
				
					查尋文件列表並從列表篩尋yum_repository
ansible-doc -l |grep yum_repository
ansible-doc yum_repository
複製到筆記本
name=
description=
baseurl=
gpgcheck=
gpgkey=

寫上答案
ansible all -i inventory -u devops -m yum_repository -a \
' name=CentOS-Stream-BaseOS \
description=CentOS-Stream-BaseOS \
baseurl=https://ftp.iij.ad.jp/pub/linux/centos-stream/9-stream/BaseOS/x86_64/os/ \
enabled=true \
gpgcheck=true \
gpgkey=https://ftp.iij.ad.jp/pub/linux/centos/RPM-GPG-KEY-CentOS-Official'

ansible all -i inventory -u devops -m yum_repository -a \
' name=CentOS-Stream-BaseOS \
description=CentOS-Stream-BaseOS \
baseurl=https://ftp.iij.ad.jp/pub/linux/centos-stream/9-stream/AppStream/x86_64/os/ \
enabled=true \
gpgcheck=true \
gpgkey=https://ftp.iij.ad.jp/pub/linux/centos/RPM-GPG-KEY-CentOS-Official'

vim repo.sh
ansible all -m yum_repository -a \
'name=CentOS-Stream-BaseOS \
description=CentOS-Stream-BaseOS \
baseurl=https://ftp.iij.ad.jp/pub/linux/centos-stream/9-stream/BaseOS/x86_64/os/ \
enabled=true \
gpgcheck=true \
gpgkey=https://ftp.iij.ad.jp/pub/linux/centos/RPM-GPG-KEY-CentOS-Official \
mode=644'

ansible all -m yum_repository -a \
'name=CentOS-Stream-AppStream \
description=CentOS-Stream-AppStream \
baseurl=https://ftp.iij.ad.jp/pub/linux/centos-stream/9-stream/AppStream/x86_64/os/ \
enabled=true \
gpgcheck=true \
gpgkey=https://ftp.iij.ad.jp/pub/linux/centos/RPM-GPG-KEY-CentOS-Official \
mode=644'

ansible all -m rpm_key -a 'key=https://ftp.iij.ad.jp/pub/linux/centos/RPM-GPG-KEY-CentOS-Official '

chmod +x repo.sh
./repo.sh








				
			

3.安裝軟件包

創建一個名為 /home/setudent/web/packages.yml 的 playbook :
將 php 和 mariadb 軟件包安裝到 dev、balancer 和 prod 主機組中的主機上
將 RPM Development Tools 軟件包組安裝到 dev 主機組中的主機上
將 dev 主機組中主機上的所有軟件包更新為最新版本

				
					#搜尋ansible-doc yum
ansible-doc -l | grep yum
#答案都在ansible-doc yum
ansible-doc yum
# vimrc設定
echo set nu ts=2 sw=2 et > ~/.vimrc
...
vim packages.yml
...
---
- name: 安装软件包1
  hosts: dev,balancer,prod
  tasks:
  - name: ensure a list of packages installed
    yum:
      name: "{{ packages }}"
    vars:
      packages:
      - php
      - mariadb

- name: 安装软件包2
  hosts: dev
  tasks:
  - name: install the package group
    yum:
      name: "@RPM Development Tools"
      state: present
  - name: upgrade all packages
    yum:
      name: '*'
      state: latest
...
ansible-playbook -C packages.yml
ansible-playbook packages.yml
#查看主機安裝狀態
ansible prod -a 'rpm -q php mariadb'

				
			

4.A 使用 RHEL 系統角色 selinux

安裝 RHEL 系統角色軟件包,並創建符合以下條件的 playbook /home/greg/ansible/selinux.yml :

在所有受管節點上運行

使用 selinux 角色

配置該角色,配置被管理節點的 selinux 為enforcing

				
					#搜尋yum roles
yum search role
#安裝rhel-system-roles
sudo yum install -y rhel-system-roles.noarch

#搜尋selinux被安裝位址
rpm -ql rhel-system-roles | grep selinux

#ansible.cfg roles_path 記得寫入
cp -r /usr/share/ansible/roles/rhel-system-roles.selinux/ roles/selinux/
vim ansible.cfg
...
roles_path    = /home/student/ansible/roles
...
#ansible-galaxy 清單
ansible-galaxy list

# /home/student/ansible/roles
# /usr/share/ansible/roles
...
#.yml檔 README.md 有說收尋example
rpm -ql rhel-system-roles | grep example
...
/usr/share/doc/rhel-system-roles/selinux/example-selinux-playbook.yml
...
複製範例檔到當前目錄的selinux.yml
cp /usr/share/doc/rhel-system-roles/ssh/example-simple-playbook.yml ./selinux.yml
修改 selinux.yml
vim selinux.yml

---
- hosts: all 
  vars:
    selinux_policy: targeted
    selinux_state: enforcing

  # prepare prerequisites which are used in this playbook
  tasks:
    - name: execute the role and catch errors
    #注意include_role目錄名
      block:
        - include_role:
            name: rhel-system-roles.selinux
      rescue:
        # Fail if failed for a different reason than selinux_reboot_required.
        - name: handle errors
          fail:
            msg: "role failed"
          when: not selinux_reboot_required
        #注意
        - name: restart managed host
          shell: sleep 2 && shutdown -r now "Ansible updates triggered"
          async: 1
          poll: 0
          ignore_errors: true

        - name: wait for managed host to come back
          wait_for_connection:
            delay: 10
            timeout: 300 
        #注意include_role目錄名
        - name: reapply the role
          include_role:
            name: rhel-system-roles.selinux
...
ansible-playbook -C selinux.yml
ansible-playbook selinux.yml
...
驗證
ansible all -m shell -a 'grep ^SELINUX= /etc/selinux/config; getenforce'
				
			

4.使用 RHEL 系统角色-02 timesync

 安裝 RHEL 系統角色軟件包,並創建符合以下條件的 playbook

/home/student/web/timesync.yml :
在所有受管節點上運行
使用 timesync角色
實現客戶端時間同步,timesync服務器地址為time.cloudflare.com

				
					yum install rhel-system-roles
rpm -ql rhel-system-roles
cd roles
cp -r /usr/share/ansible/roles/rhel-system-roles.timesync/ .
cd rhel-system-roles.timesync/
less README.md
---
List of NTP servers
timesync_ntp_servers:
  - hostname: foo.example.com   # Hostname or address of the server
    minpoll: 4                  # Minimum polling interval (default 6)
    maxpoll: 8                  # Maximum polling interval (default 10)
    iburst: yes                 # Flag enabling fast initial synchronization
                                # (default no)
    pool: no                    # Flag indicating that each resolved address
                                # of the hostname is a separate NTP server
                                # (default no)
    nts: no                     # Flag enabling Network Time Security (NTS)
                                # authentication mechanism (default no,
                                # supported only with chrony >= 4.0)
    prefer: no                  # Flag marking the source to be preferred for

- hosts: targets
  vars:
    timesync_ntp_servers:
      - hostname: foo.example.com
        iburst: yes
      - hostname: bar.example.com
        iburst: yes
      - hostname: baz.example.com
        iburst: yes
  roles:
    - rhel-system-roles.timesync
---
vim timesync.yml
---
- name: ntp time sync
  hosts: all
  vars:
    timesync_ntp_servers:
      - hostname: time.cloudflare.com
        iburst: yes
  roles:
    - rhel-system-roles.timesync

ansible-playbook -C timesync.yml
ansible-playbook timesync.yml

確認roles
ansible-galaxy list

測試是否成功
ansible all -a 'chronyc sources'
				
			

5. 使用 Ansible Galaxy 安裝角色

使用 Ansible Galaxy 和要求文件 /home/greg/ansible/roles/requirements.yml 。從以下 URL 下載角色並安裝到 /home/greg/ansible/roles :
haproxy.tar 此角色的名稱應當為 balancer
phpinfo.tar.gz此角色的名稱應當為 phpinfo

				
					vim requirements.yml
---
- src: https://www.leojsp.mywire.org/wp-content/uploads/2023/01/haproxy.tar.gz
  name: balancer
- src: https://www.leojsp.mywire.org/wp-content/uploads/2023/01/phpinfo.tar.gz
  name: phpinfo
ansible-galaxy install -r /home/student/ansible/roles/requirements.yml

ansible-galaxy list
				
			

6.創建和使用角色

根據下列要求,在 /home/greg/ansible/roles 中創建名為 apache 的角色:

。httpd 軟件包已安裝,設為在系統啟動時啟用並啟動
。防火牆已啟用並正在運行,並使用允許訪問 Web 服務器的規則
。模板文件 index.html.j2 已存在,用於創建具有以下輸出的文件
/var/www/html/index.html :
Welcome to HOSTNAME on IPADDRESS
其中,HOSTNAME 是受管節點的完全限定域名, IPADDRESS 則是受管節點的 IP 地址。
創建一個名為 /home/greg/ansible/apache.yml 的 playbook:
該 play 在 webservers 主機組中的主機上運行並將使用 apache 角色

				
					#創建 apache 角色
ansible-galaxy init /home/greg/ansible/roles/apache
- Role /home/greg/ansible/roles/apache was created successfully
#配置 roles/apache/tasks/main.yml
# install http service firewalld
#ansible-doc http
#ansible-doc service
#ansible-doc firewalld
vim /home/greg/ansible/roles/apache/tasks/main.yml

---
# tasks file for apachea
- name: install httpd
  yum:
    name: httpd
- name: config firewalld
  firewalld:
    service: http
    permanent: yes
    state: enabled
    immediate: yes
- name: template index.html
  template:  
    src: index.html.j2
    dest: /var/www/html/index.html
    setype: httpd_sys_content_t
- name: start httpd service
  service:
    name: httpd
    state: started
    enabled: yes
    
#配置模板文件
vim /home/greg/ansible/roles/apache/template/index.html.j2

Welcome to {{ ansible_fqdn }} on {{ ansible_default_ipv4.address }}

#配置apache.yml
vim /home/greg/ansible/apache.yml

---
- hosts: webserver
  roles:
    - apache

#執行apache.yml

ansible-playbook /home/greg/ansible/apache.yml
				
			

8.A 創建和使用分區(NEW)

創建和使用分區

創建一個名為 /home/student/web/parted.yml 的 playbook ,它將在所有受管節點上創建分區:

在sdv創建一個1500M主分區,分區號1,並格式化ext4

prod組將分區永久掛載到/data(???)

如果磁盤空間不夠,

給出提示信息Could not create partition of that size

創建800MiB分區

如果 vdb不存在,則給出提示信息this disk is not exist

				
					ansible-doc parted
ansible-doc file
ansible-doc filesystem
ansible-doc mount
vim parted.yml
---
- name: create new primary
  hosts: dev
  tasks:
    - name: create part1
      block:
        - name: create part 6GiB on /dev/sdb
          parted:
            device: /dev/sdb
            number: 1
            part_type: primary
            part_start: 10MiB
            part_end: 6GiB
            state: present
      rescue:
        - name: output fail message
          debug:
            msg: could not create partition os that size
       
        - name: create part 800 on /dev/sdb
          parted:
            device: /dev/sdb
            number: 1
            part_type: primary
            part_start: 10MiB
            part_end: 810MiB
            state: present
      always:
        - name: format part
          filesystem:
            fstype: ext4
            dev: /dev/sdb1
            opts: -cc
 
        - name: Create a directory
          file:
            path: /data
            state: directory
            mode: '0755'
     
        - name: mount
          mount:
            path: /data
            src: /dev/sdb1
            fstype: ext4
            state: mounted
      when: ansible_devices.sdb is defined
 
    - name: sdb not exist
      debug:
        msg: disk does not exist
      when: ansible_devices.sdb is not defined