RHCE8.2综合练习笔记

RHCE 8.2综合练习笔记分享

准备工作
Ansible环境准备

硬件要求:

  • 内存:16G
  • 固态硬盘:500G
  • CPU (目前普遍支持)
    链接获取练习环境,安装并运行
    练习环境说明:
    实验用到五台虚拟机,通过一台管理主机workstation(控制节点)对另外四台虚拟机server[a-d](受控节点)使用ssh的方式进行远程部署
    在这里插入图片描述
    foundation0为基础环境(包含rh200和rh294的内容),通过基础环境配置准备好的材料和调试用到的控制节点(workstation)和受控主机(servera,serverb,serverc,serverd)
    root@foundation0下初始化CE实验环境
       1.rht-vmctl set-course rh294 #选择课程编号
       2.rht-vmctl fullreset classroom #重置classroom环境
       3.rht-vmctl fullreset all #重置(初始化)所有环境
       4.环境已经配好devops用户(可直接拿来上手操作);如果以student用户或其他进行操作
    需要配置(控制主机和节点都需要配置以下操作)
  • 进visudo,更改student用户(有语法检错,配置sudo免密)
  • 进入vim /etc/group删除student用户(关于wheel组的)
    也可以通过命令:
    echo ‘student ALL=(ALL) NOPASSWD: ALL’ > /etc/sudoers.d/student进行写入
    用户免密配置:
  1. ssh-keyscan
  2. ssh-copy-id +指定节点

准备模拟环境用到的材料(以下准备工作都在root@foundation0内完成)

模拟环境 (第五题使用)
把haproxy.tar.gz 和 phpinfo.tar.gz 上传到 /content/courses/rh294/rhel8.0/materials/labs/role-system/roles/
[root@foundation0 roles]# ll
total 12
-rw-r–r–. 1 root root 2850 Sep 18 16:56 haproxy.tar.gz
-rw-r–r–. 1 root root 2336 Sep 18 16:56 phpinfo.tar.gz
-rw-r–r–. 1 root root 913 Jan 12 2019 requirements.yml
[root@foundation0 roles]# pwd
/content/courses/rh294/rhel8.0/materials/labs/role-system/roles/

环境模拟(第十二题使用)
把hwreport.empty上传到/content/courses/rh294/rhel8.0/materials/labs/role-system/roles/
[root@foundation0 ~]# cd /content/courses/rh294/rhel8.0/materials/labs/role-system/roles/
[root@foundation0 roles]# vim hwreport.empty
hostname=.*
memory=.*
bios_version=.*
vda_size=.*
vdb_size=.*

环境模拟 (第十四题使用)
把材料中的user_list.yml上传到/content/courses/rh294/rhel8.0/materials/labs/role-system/roles/
[root@foundation0 ~]# cd /content/courses/rh294/rhel8.0/materials/labs/role-system/roles/user_list.yml
总之把所有题目中会涉及到的文件都丢到指定录/content/courses/rh294/rhel8.0/materials/labs/role-system/roles/内

RHCE8.2练习环境链接(红帽综合练习环境及环境所需的文件):
https://pan.baidu.com/s/1tGchfEIGckKDQ5KOkpCK7w
提取码:tqpm

(注释:指定用户下进行操作,这里以student用户演示相关操作)

第一题:安装和配置ansible

1. Install and configure ansible

  • Install and configure ansible on the control node workstation.example.com as follows:
  • Install the required packages
  • Create a static inventory file called /home/student/ansible/inventory as follows:
    servera is member of the dev host group
    serverb is member of the test host group
    serverc and serverd are members of the prod host group
    serverb is a member of the balancers host group
    The prod group is a member of the webservers host group
  • Create a configuration file called /home/student/ansible/ansible.cfg as follows:
    The host inventory file /home/student/ansible/inventory is defined
    The location of roles userd in playbooks is defined as /home/student/ansible/roles

1.辅助准备(作用于编写剧本,格式调整),在 $HOME/.vimrc 添加以下内容

[student@workstation ~]$ vim .vimrc
autocmd FileType yaml setlocal ai ts=2 sw=2 et
[student@workstation ~]$ source .vimrc        #执行
参数说明:
set ai # 自动缩进
set ts=2 # tabstop,表示按一个tab之后,显示出来两个空格间隔,默认的是8个。
set sw=2 # shiftwidth,表示每一级缩进的长度,设置为2
set et #expandtab,将tab转成空格,缩进用空格来表示

2.安装ansible并校验

[student@workstation ~]$ sudo yum -y install ansible
[student@workstation ~]$ ansible --version #查看ansible工具的版本
ansible 2.8.0
config file = /etc/ansible/ansible.cfg #(默认配置文件)
configured module search path = [‘/home/student/.ansible/plugins/modules’, ‘/usr/share/ansible/plugins/modules’]
ansible python module location = /usr/lib/python3.6/site-packages/ansible
executable location = /usr/bin/ansible
python version = 3.6.8 (default, Apr 3 2019, 17:26:03) [GCC 8.2.1 20180905 (Red Hat 8.2.1-3)]

3.按要求创建主机清单和配置文件

[student@workstation ~]$ mkdir ansible/roles -p
[student@workstation ~]$ cd ansible/
[student@workstation ansible]$ vim inventory         #根据题意配置主机清单
[dev]
servera
[test]
serverb
[prod]
serverc
serverd
[balancers]
serverb
[webservers:children]
prod

[student@workstation ansible]$ vim ansible.cfg #参考man /etc/ansible/ansible.cfg复制需要的内容
[defaults]
inventory = /home/student/ansible/inventory     #根据题意配置Inventory目录路径
roles_path = /home/student/ansible/roles #根据题意配置role目录路径
[privilege_escalation]     #建议配置提权
become=True
become_method=sudo
become_user=root
become_ask_pass=False

注释(参数作用解释):

[defaults] # 设置ansible操作的默认值
inventory = 指定清单文件的路径
remote_user = 在受管主机上登录用户的名称(未指定则使用当前用户名称)
ask_pass = 是否提示输入SSH密码(默认false)
[privilege_escalation] #配置ansible如何在受管主机上执行特权升级
become = true #连接后是否在受管主机上切换用户,是否启用特权升级
become_method = sudo #如何切换用户,通常为sudo,将特权升级设置为sudo命令
become_user = root #将用户权限提升为root
become_ask_pass = false #是否需要为become_method切换用户;true(需要输入密码进行提权)false(不需要密码进行提取)
注意点
1.remote_user 用法:若要指定不同远程用户,请将参数设置为该用户名
2.实现ask_pass=false的前提,确保配置SSH密钥对
ssh-keygen
ssh-copy-id
通过借鉴ansible默认配置文件,复制主要参数在指定用户下创建新的ansible配置文件

4.验证

[student@workstation ansible]$ ansible --version
ansible 2.8.0
config file = /home/student/ansible/ansible.cfg
…………
[student@workstation ansible]$ ansible all --list-hosts
hosts (4):
serverc
serverd
servera
serverb

[student@workstation ansible]$ansible all -m ping #测试网络

提示:Ansible 只使用最高优先级配置文件中的设置,即使存在其他优先级较低的文件,它们的设置也将被忽略,并且不会与所选配置文件中的设置相结合。Ansible配置文件优先级为:
$ANSIBLE_CONFIG环境变量指定配置文件 > 运行ansible命令的当前目录下的ansible.cfg配置文件>用户的主目录.ansible.cfg配置文件 > 全局/etc/ansible/ansible.cfg配置文件。

第二题:ad-hoc命令,临时执行,节点创建yum源

2. Create and run an ansible ad-hoc command
As a system administrator ,you will need to install software on the managed nodes。
Create a shell scripts called /home/student/ansible/adhoc.sh that runs an ansible adhoc command to create a yum repository on each of the managed nodes as follows:
repository 1:

  • The name of the repository is EX294_BASE;
  • The description is EX294 base software;
  • The base URL is http://content.example.com/rhel8.2/x86_64/dvd/BaseOS;
  • GPG signature checking is enabled;
  • The GPG key URL is http://content.example.com/rhel8.2/x86_64/dvd/RPM-GPG-KEY-redhat-release;
  • The repository is enabled。
    repository 2:
  • The name of the repository is EX294_STREAM;
  • The description is EX294 stream software;
  • The base URL is http://content.example.com/rhel8.2/x86_64/dvd/AppStream;
  • GPG signature checking is enabled;
  • The GPG key URL is http://content.example.com/rhel8.2/x86_64/dvd/RPM-GPG-KEY-redhat-release;
  • The repository is enabled。

1.查看模块辅助处理

[student@workstation ansible]$ ansible-doc --list | grep yum # 查看和yum相关的模块
yum                         Manages packages with the `yum’ package manag…
yum_repository       Add or remove YUM repositories

[student@workstation ansible]$ ansible-doc yum_repository * #查看帮助,配置脚本内容*

2.编写题目要求的脚步

[student@workstation ansible]$ vim adhoc.sh #创建脚本
#!/bin/bash
ansible all -m yum_repository -a ‘name=EX294_BASE description=“EX294 base software” baseurl=http://content.example.com/rhel8.2/x86_64/dvd/BaseOS gpgcheck=yes
gpgkey=http://content.example.com/rhel8.2/x86_64/dvd/RPM-GPG-KEY-redhat-release enabled=yes’
ansible all -m yum_repository -a ‘name=EX294_STREAM description=“EX294 stream software” baseurl=http://content.example.com/rhel8.2/x86_64/dvd/AppStream gpgcheck=yes gpgkey=http://content.example.com/rhel8.2/x86_64/dvd/RPM-GPG-KEY-redhat-release enabled=yes’
[student@workstation ansible]$ chmod +x adhoc.sh           #赋予脚本执行权限
[student@workstation ansible]$ ./adhoc.sh           #执行脚本

3.验证:

[student@workstation ansible]$ ansible all -m shell -a ’ ls /etc/yum.repos.d/ ’
servera | CHANGED | rc=0 >>
EX294_BASE.repo
EX294_STREAM.repo
redhat.repo
rhel_dvd.repo

第三题:安装包(写剧本playbook)

3. Install packages
Create a playbook called /home/student/ansible/packages.yml that:

  • Installs the php and mariadb packeages on hosts in the dev,test,and prod hosts groups;
  • Installs the development tools package group on hosts in the dev host group;
  • Updates all packages to the latest version on hosts in the dev host group。

1.根据题意写剧本

方法一:多剧本
---
- name: install packages     #描述
  hosts: dev,test,prod       #主机清单
  become: true              #提权
  tasks:                    #任务
     - name:installs the php and mariadb packages
       yum:
         name:               #分列显示
           - php
           - mariadb
         state:latest        #安装最新版本
- name: install packages
  host: dev
  become: true
  tasks:
    - name:install the development package
      yum:
        name: "@Development Tools" #查看帮助,ansible-doc yum
        state:latest
    - name: Updates all packages
      yum:
        name: "*"
          state: latest
          update_only: yes                   #查看ansible-doc yum        
 方法二:设置自定义变量和魔法变量
---
- name: Install packages
  hosts: dev,test,prod
  become: true
  vars:
    pkgs:
      - php
      - mariadb
  tasks:
    - name: Install the php and mariadb packages on hosts
      yum:
        name: "{{ pkgs }}" 
        state: latest
    - name: Install the Development Tools packages on hosts
      yum:
        name: "@Development tools"
        state: latest
      when: ansible_hostname in groups.dev
    - name: Update all packages to the latest version on hosts
      yum:
        name: "*"
        state: latest
        update_only: true  #仅更新软件包中还不是最新的软件,缩短剧本执行时间
      when: ansible_hostname in groups.dev

拓展: 除了通过"ansible-doc yum" 来获取“Development Tools”,另外可以通过命令“sudo yum grouplist”可以查询

常见魔法变量
1.hostvars: 包含受管主机的变量,可以用于获取另外一台受管主机的变量的值
2.group_names: 列出当前受管主机所属的所有组
3.groups: 列出清单中所有组和主机
4.inventory_hostname: 包含清单中配置的当前受管主机的主机名称

2.语法检查并执行

[student@workstation ansible]$ ansible-playbook --syntax-check packages.yml #检测语法,注意代码格式问题容易出错
[student@workstation ansible]$ ansible-playbook packages.yml     #运行剧本

3.验证

[student@workstation ansible]$ ansible dev,test,prod -m shell -a 'rpm -qa | grep php'
serverc | CHANGED | rc=0 >>
php-cli-5.4.16-46.el7.x86_64
php-common-5.4.16-46.el7.x86_64
php-5.4.16-46.el7.x86_64
…………
[student@workstation ansible]$ ansible dev,test,prod -m shell -a 'rpm -qa | grep mariadb'
serverc | CHANGED | rc=0 >>
mariadb-5.5.60-1.el7_5.x86_64
mariadb-libs-5.5.60-1.el7_5.x86_64
…………
第四题:安装RHEL系统软件包,并创建符合条件的剧本

有两个题型:
题型一:安装并使用timesync角色

4. Use a RHEL system role
Install the RHEL system roles package and create a playbook called
/home/student/ansible/timesync.yml that :
*Runs on all managed hosts
*Uses the timesync role
*Configures the role to use the time server 172.25.254.254
*Configures the role to set the ibrust parameter as enabled

  1. 安装系统角色工具包
[student@workstation ansible]$ rpm -qa | grep rhel-system-roles
[student@workstation ansible]$ sudo yum -y install rhel-system-roles
  1. 按模版形式编写题目剧本
[student@workstation ansible]$ rpm -ql rhel-system-roles # 查看安装目录
[student@workstation ansible]$ cp -rf /usr/share/ansible/roles/rhel-system-roles.timesync/  roles/
[student@workstation ansible]$ cd roles/
[student@workstation roles]$ mv rhel-system-roles.timesync timesync #修改角色名称 
[student@workstation roles]$ cat roles/timesync/README.md #参考示例说明,复制需要的模板

[student@workstation ansible]$ vim timesync.yml
--- 
- name: Use a RHEL system role
  hosts: all
  become: yes
  vars:
    timesync_ntp_servers:
      - hostname: 172.25.254.254 
        iburst: yes
    roles:
      - timesync     
[student@workstation ansible]$ ansible-playbook --syntax-check timesync.yml
[student@workstation ansible]$ ansible-playbook timesync.yml
[student@workstation ansible]$ ansible all -m shell -a 'chronyc sources -v' #检验剧本

题型二:安装并使用selinux角色

使用rhel system role
安装rhel-system-roles包,并且创建一个playbook: /home/student/ansible/selinux.yml ,要求
如下:
1: 作用于所有管理节点上
2: 使用selinux 这个role
3: 配置selinux状态为: enforcing
4: 配置selinux,允许http监听82 端口
5: 配置selinux,允许http访问/var/www/html
注意看README.md

前面步骤与题型一类似
到/usr/share/ansible/roles下获取关于selinux角色文件
查看READMD.md,了解selinux的相关用法
vim selinux.yml
- name: set selinux
  hosts: all
  vars:
    - selinux_policy: targeted
    - selinux_state: enforcing
    - selinux_fcontexts:
      - { target: '/var/www/html(/.*)?', setype: 'httpd_sys_content_t', ftype:
'd', state: 'present' }   
    - selinux_ports:
      - { ports: '82', proto: 'tcp', setype: 'http_port_t', state: 'present' }
    - selinux_restore_dirs:
    - /var/www/html
  roles:
    - role: selinux
验证剧本执行结果
ansible all -m shell -a 'ls -lZ /var/www/html'
ansible all -m shell -a 'ls -ldZ /var/www/html'
ansible all -m shell -a 'grep "^SELINUX=" /etc/selinux/config'
ansible all -m shell -a 'semanage port -l |grep "^http_port"'

注释:
变量- selinux_fcontexts中的setype(设置文件类型)参数可以查命令man semanage-fcontext; 变量- selinux_ports中的setype参数可以查命令man semanage-port

第五题:使用galaxy工具安装角色

5. Install roles using ansible galaxy
Use ansible galaxy with a requirements file called /home/student/ansible/roles/requirments.yml to download and install roles to /home/student/ansible/roles from the following URL:

  • http://materials.example.com/labs/role-system/roles/haproxy.tar.gz
  • The name of this role should be balancer
  • http://materials.example.com/labs/role-system/roles/phpinfo.tar.gz
  • The name of this role should be phpinfo
[student@workstation ansible]$vim roles/requirments.yml
---  #注意这三个短横杆,剧本的必要格式,不要忘记,否则后面操作执行出问题
- src: http://materials.example.com/labs/role-system/roles/haproxy.tar.gz
  name: balancer
- src: http://materials.example.com/labs/role-system/roles/phpinfo.tar.gz
  name: phpinfo
[student@workstation ansible]$ansible-galaxy install -r roles/requirment.yml -p roles/  #使用ansible-galaxy工具安装角色到指定目录
- downloading role from http://materials.example.com/labs/role-system/roles/haproxy.tar.gz
- extracting balancer to /home/student/ansible/roles/balancer
- balancer was installed successfully
- downloading role from http://materials.example.com/labs/role-system/roles/phpinfo.tar.gz
- extracting phpinfo to /home/student/ansible/roles/phpinfo
- phpinfo was installed successfull
[student@workstation ansible]$ ll roles/    #验证一下
total 4
drwxrwxr-x. 9 student student 122 Mar 8 20:37 balancer
drwxrwxr-x. 9 student student 122 Mar 8 20:37 phpinfo
-rw-rw-r--. 1 student student 204 Mar 8 20:36 requirements.yml
drwxr-xr-x. 10 student student 188 Mar 8 20:09 timesync

使用ansible-galaxy --hlep 获取用法帮助

第六题:创建和使用角色

6. Create and use a role
Create a role called apache in /home/student/ansible/roles with the following requirments:
 The httpd package is installed,enbaled on boot,and started
 The filewall is enabled and running with a rule to allow access to the web server
 A template file index.html.j2 exists and is used to create the file /var/www/html/index.html with the following output:
Welcome to HOSTNAME on IPADDRESS
Where HOSTNAME is the fully qualified domain name of the managed node and IPADDRESS is the ip address of the managed node.
Create a playbook called /home/student/ansible/newrole.yml that uses this role as follows:
 The playbook runs on hosts in the webservers host group

1.指定目录下创建apache角色

[student@workstation roles]$ansible-galaxy init apache #初始化apache角色,参数:--offline(当前局域网内)  --init-path(作用对象,哪个目录下)
[student@workstation roles]$tree apache  #树状结构列出文件信息
apache/
├── defaults
│ └── main.yml
├── files
├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── README.md
├── tasks
│ └── main.yml
├── templates
├── tests
│ ├── inventory
│ └── test.yml
└── vars
└── main.yml

2.编写角色任务,在tasks目录下的main.yml中进行编辑角色任务

[student@workstation roles]$vim apache/tasts/main.yml
---
- name: Install httpd
  yum:
    name: "{{ pkgs }}"       #设置变量
    state: latest
- name: Start httpd and firewalld
  service:
    name: "{{ item }}"    #将变量循环写入
    state: started
    enabled: yes
  loop: "{{ pkgs }}"     #调用循环变量
- name: firewall permits http service                         
  firewalld:                        #调用防火墙模块
    service: http                 #放通服务
    state: enabled              #状态启用
    permanent: yes            #保存为永久
    immediate: yes             #立刻启用
- name: create /var/www/html/index.html      # 传输网页文件到指定位置
  template:
    src: index.html.j2
    dest: /var/www/html/index.html
    owner: apache
    group: apache
    mode: '0640'
    setype: httpd_sys_content_t

3.编写角色默认变量

[student@workstation roles]$vim apache/defaults/main.yml
---
pkgs:
  - httpd
  - firewalld

4.编写j2模板

[student@workstation roles]$ cat apache/template/index.html.j2
Welcome to HOSTNAME on IPADDRESS
[student@workstation roles]$ansible localhost -m setup -a 'filter=*fqdn*' #过滤出需要的信息
localhost | SUCCESS => {
"ansible_facts": {
	"ansible_fqdn": "workstation.lab.example.com"
},
"changed": false
}
[student@workstation roles]$ansible localhost -m setup -a 'filter=*ipv4*'
localhost | SUCCESS => {
"ansible_facts": {
	"ansible_all_ipv4_addresses": [
		"172.25.250.254",
		"172.25.252.250",
		"192.168.122.1"
	],
	"ansible_default_ipv4": {
		"address": "172.25.252.250",
		"alias": "eth1",
		"broadcast": "172.25.252.255",
		"gateway": "172.25.252.254",
		"interface": "eth1",
		"macaddress": "52:54:00:01:fc:00",
		"mtu": 1500,
		"netmask": "255.255.255.0",
		"network": "172.25.252.0",
		"type": "ether"
		}
	},
	"changed": false
}
[student@workstation roles]$vim apache/template/index.html.j2
Welcome to {{ansible_fqdn}} on {{ansible_default_ipv4.address}}

5.编写主剧本调用角色

[student@workstation ansible]$vim newrole.yml
---
- name: Create and use a role
  hosts: webservers     #作用对象webservers
  become: yes

  roles:             #调用apache角色
    - apache

6.执行和验证

[student@workstation ansible]$ansible-playbook --syntax-check newrole.yml
[student@workstation ansible]$ansible-playbook newrole.yml
[student@workstation ansible]$curl http://serverc
 Welcome to serverc.lab.example.com on 172.25.250.12
[student@workstation ansible]$curl http://serverd
 Welcome to serverc.lab.example.com on 172.25.250.12
第七题:使用角色

(使用第五题获取的角色)

7. Use roles from ansible galaxy
Create a playbook called /home/student/ansible/roles.yml as follows:
The playbook contains a play that runs on hosts in the balancers host group and uses the balancer role.
This role configures a service to load balance web server requests between hosts in the webservers host group.
When implemented browsing to hosts in the balancers host group (for example http://serverb.lab.example.com/)should produce the following output:
Welcome to serverc.lab.example.com on 172.25.250.12
Reloading the browser should return output form the altermate web server:
Welcome to serverd.lab.example.com on 172.25.250.13
The playbook contains a play that runs on hosts in the webservers host group and uses the phpinfo role.
When implemented,browsing to hosts in the webservers host group with the URL /hello.php should produce the following output:
Hello PHP world from FQDN
Where FQDN is the fully qualified domain name of the host
For example,browsing to http://serverc.lab.example.com/hello.php, should produce the following output:
Hello PHP World form serverc.lab.example.com
along with various details of the PHP configuration including the version of PHP that is installed
Similarly ,browsing to http://serverd.lab.example.com/hello.php should produce the following output:
Hello PHP World form serverd.lab.example.com
along with various details of the PHP configuration including the version of PHP that is installed

1.按需求编写剧本

[student@workstation ansible]$ vim roles.yml
---
- name: Use balancer roles from ansible galaxy
  hosts: balancers
  roles:
    - balancer
---
- name: Use phpinfo roles from ansible galaxy
  hosts: webservers
  roles: 
    - phpinfo

2.语法检查与执行

[student@workstation ansible]$ ansible-playbook --syntax-check roles.yml
[student@workstation ansible]$ ansible-playbook roles.yml

3.验证

[student@workstation ansible]$ curl http://serverb
Welcome to serverd on 172.25.250.13
[student@workstation ansible]$ curl http://serverb
Welcome to serverc on 172.25.250.12
[student@workstation ansible]$ curl http://serverc/hello.php
Hello PHP World form serverc.lab.example.com
[student@workstation ansible]$ curl http://serverd/hello.php
Hello PHP World form serverd.lab.example.com
第八题:创建剧本,给节点创建分区(题型一)

8. Create and use a partition
Create a playbook called /home/student/ansible/partition.yml that runs on all managed nodes that does the following:
 Creates a single primary partition number 1 of size 6500iMB on device vdb
 Formats the partition with the ext4 filesystem
 Mounts the filesystem persistently at /newpart
 If the requested partition size cannot be created the error message:
Could not create partition of that size
Should be displayed and the size 800MiB should be use instead
 If the device vdb dose not exist the error message:
Disk does not exist
Should be displayed

  1. 按要求编写分区剧本
vim ~/ansible/partition.yml
---
- name: create a new primary partition
  hosts: dev
  tasks:
	- name: print the error message if /dev/vdb does not exit
	  debug:
	    msg: Disk does not exist
	  when: ansible_devices.vdb is undefined
	- name: create a partition of size 6500Mib
	  block:
    	- name: Create a new primary partition with a size of 6500MiB
      	  parted:
  	 		device: /dev/vdb
			number: 1
			state: present
			part_end: 6500MiB
	  	  when: ansible_devices.vdb is defined
	  rescue:
		- name: print the error message if /dev/vdb has insuficient disk space
		  debug:
		  	msg: Could not create partition of that size
		- name: Create a new primary partition with a size of 800MiB
		  parted:
		    device: /dev/vdb
			number: 1
			state: present
			part_end: 800MiB
	- name: Create a ext4 filesystem on /dev/vdb1 and check disk blocks
	  filesystem:
		fstype: ext4
		dev: /dev/vdb1
	  when: ansible_devices.vdb.partitions.vdb1 is defined
	- name: Mount up device
	  mount:
		path: /newpart
		src: /dev/vdb1
		fstype: ext4
		opts: noatime
		state: mounted
	  when: ansible_devices.vdb.partitions.vdb1 is defined

一般通过“ ansible-doc + 模块” 查询模块用法和参数信息
常用模块注释:
debug模块的使用
常用参数:
* msg:调试输出的消息
* var:将某个任务执行的输出作为变量传递给debug模块,debug会直接将其打印输出
block rescue always三者之间的关系
playbook中的block块里的任务在执行的时候,如果有任何错误,将执行rescue中的任务;无论在block和rescue中发生或没有发生错误,always部分都运行
block块中的内容一旦出现问题,rescue(救援)做出补救。

filesystem模块
常用参数:
* dev:目标块设备
* force:在一个已有文件系统的设备上强制创建
* fstype:文件系统的类型
* opts:传递给mkfs命令的选项
file模块
常用参数
* force:需要在两种情况下强制创建软连接,一种是源文件不存在但之后会建立的情况,另一种是目标软连接已存在,需要先取消之前的软连接,然后在创建软连接,两种选项yes|no
* group: 定义文件目录属性
* mode:定义文件目录的权限
* owner:定义文件目录的属性
* path:必选项,定义文件目录的路径
* recurse: 递归的设置文件的属性,只对目录有效
* src:要被软连接的源文件的路径,只适用于state=link的情况
* dest:被连接到的路径,,只适用于state=link的情况
* state:directory:如果目录不存在,创建目录
* file:即使文件不存在,也不会被创建
* link:创建软连接
* hard:创建硬链接
* touch:如果文件不存在时候,则则会创建一个新文件,如存在文件目录,则更新最后修改时间
* absent:删除目录文件或者取消连接文件
mount模块
功能:管理被控端设备挂载
常用参数:
在这里插入图片描述
注释:mount模块下的state参数:在为mounted状态时,设备将被主动挂载并在fstab中进行适当配置。如果挂载点不存在则会创建挂载点

  1. 语法检查并执行
[student@workstation ansible]$ ansible-playbook --syntax-check partition.yml
[student@workstation ansible]$ ansible-playbook partition.yml
  1. 验证
[student@workstation ansible]$ ansible dev -m shell -a 'lsblk'
servera | CHANGED | rc=0 >>
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
vda 252:0 0 10G 0 disk
└─vda1 252:1 0 10G 0 part /
vdb 252:16 0 5G 0 disk
└─vdb1 252:17 0 800M 0 part /newpart
第八题(题型二):创建和使用逻辑卷

创建一个名为 /home/student/ansible/lv.yml 的 playbook ,它将在所有受管节点上运行以执行下列任务:
创建符合以下要求的逻辑卷:

  • 逻辑卷创建在 research 卷组中
  • 逻辑卷名称为 data
  • 逻辑卷大小为 6000 MiB
  • 使用 ext4 文件系统格式化逻辑卷
    如果无法创建请求的逻辑卷大小,应显示错误信息 Could not create logical volume of that size,并且应改为使用大小 800 MiB
    如果卷组 research 不存在,应显示错误信息 Volume group done not exist
    不要以任何方式挂载逻辑卷

练习环境的节点中不存在research这个卷组,为了验证执行效果,在某个节点主机或主机组上创建research卷组 ,自行在节点创建卷组模拟

1.按要求编写剧本

---
- name: create lv
  hosts: test
  become: yes
  tasks:
    - name: research is not exit
      debug:
        msg: "Volume group done not exist"
      when: ansible_lvm.vgs.research is not defined
    - name: create a lv
      block:
      	- name: create lv 6000
       	  lvol:
            vg: research
            lv: data
            size: 6000m
      rescue:
        - name: error 6000
          debug:
            msg: "Could not create logical volume of that size"
        - name: create lv 800
          lvol:
            vg: research
            lv: data
            size: 800m
      always:
        - name: format fs
          filesystem:
            dev: /dev/mapper/research-data
            fstype: ext4
      	  when: ansible_lvm.lvs.data is defined

2.执行剧本

[student@workstation ansible]$ ansible-playbook --syntax-check lv.yml
[student@workstation ansible]$ ansible-playbook lv.yml

3.验证

ansible all -m shell -a 'lsblk -f |grep research-data'
第九题:产生一个hosts文件

9. Generate a hosts file

  • Download an initial template file called hosts.j2 from http://materials.example.com/jinja2/ to /home/student/ansible
  • Complete the template so that it can be used generate a file with a line for each inventory host in the same format as /etc/hosts
  • Create a playbook called /home/student/ansible/hosts.yml that uses this template to generate the file /etc/myhosts on hosts in the dev host group
    When completed the file /etc/myhosts on hosts in the dev host group should have a line for each managed host:
    127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
    ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
    172.25.250.10 servera.lab.example.com servera
    172.25.250.11 serverb.lab.example.com serverb
    172.25.250.12 serverc.lab.example.com serverc
    172.25.250.13 serverd.lab.example.com serverd
  1. 编写J2模版文件(考试的时候直接wget获取)
[student@workstation ansible]$vim hosts.j2
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6

{% for hosts in groups.all %}
{{ hostvars[hosts]['ansible_facts']['default_ipv4']['address'] }} {{ hostvars[hosts]['ansible_facts']['fqdn'] }} {{ hostvars[hosts]['ansible_facts']['hostname'] }}
{% endfor %} 

注释:ansible all -m setup -a ‘filter=fqdn | hostname | ipv4’ 查看需要的信息
ip地址、域名、主机名并排写,注意空格
ansible host -m setup -a “filter=xxx”, 此filter可以筛选关键词。

  1. 按要求编写剧本
[student@workstation ansible]$vim hosts.yml
---
- name: generate a hosts file
  hosts: all
  become: true
  gather_facts: yes    ##决定是否开启收集功能,默认是true
  tasks:
    - name: create myhosts
      template:
        src: /home/student/ansible/hosts.j2     
        dest: /etc/myhosts
      when: inventory_hostname in groups.dev

ansible *template模块
常用参数
* src: 本地Jinjia2模版的template文件位置
* dest: 远程节点上的绝对路径,用于放置template文件
* owner: 设置远程节点上的template文件所属用户
* group:设置远程节点上的的template文件的所属用户组
* mode: 设置远程节点上的template文件权限。类似Linux中chmod的用法
* backup: 建立个包括timestamp在内的文件备份,以备不时之需

  1. 执行剧本
[student@workstation ansible]$ ansible-playbook --syntax-check hosts.yml
[student@workstation ansible]$ ansible-playbook hosts.yml

4.验证

[student@workstation ansible]$ ansible dev -a 'cat /etc/myhosts'
servera | CHANGED | rc=0 >>
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
172.25.250.10 servera.lab.example.com servera
172.25.250.11 serverb.lab.example.com serverb
172.25.250.12 serverc.lab.example.com serverc
172.25.250.13 serverd.lab.example.com serverd
第十题:修改文件内容

10. Modify file content
Create a playbook called /home/student/ansible/issue.yml as follows:
The playbook runs on all inventory hosts
The playbook replaces the contents of /etc/issue with a single line of text as follows:

  • On hosts in the dev host group. The line reads:Development
  • On hosts in the test host group. the line reads:Test
  • On hosts in the prod host group. The line reads:Production

1.按要求编写剧本

---
- name: Modify file content
  hosts: all
  become: yes
  tasks:
	- name: issue information for dev group
  	  copy:
        dest: /etc/issue
        content: 'Development'
        force: yes
      when: inventory_hostname in groups.dev
	- name: issue information for test group
 	  copy:
        dest: /etc/issue
        content: 'Test'
        force: yes
      when: inventory_hostname in groups.test
	- name: issue information for prod group
      copy:
        dest: /etc/issue
        content: 'Production'
        force: yes
      when: inventory_hostname in groups.prod

ansible copy模块
常用参数:
* src参数 :用于指定需要copy的文件或目录。
* dest参数 :用于指定文件将被拷贝到远程主机的哪个目录中,dest为必须参数。
* content参数 :当不使用src指定拷贝的文件时,可以使用content直接指定文件内容,src与content两个参数必有其一,否则会报错。
* force参数 : 当远程主机的目标路径中已经存在同名文件,并且与ansible主机中的文件内容不同时,是否强制覆盖,可选值有yes和no,默认值为yes,表示覆盖,如果设置为no,则不会执行覆盖拷贝操作,远程主机中的文件保持不变。
* backup参数 : 当远程主机的目标路径中已经存在同名文件,并且与ansible主机中的文件内容不同时,是否对远程主机的文件进行备份,可选值有yes和no,当设置为yes时,会先备份远程主机中的文件,然后再将ansible主机中的文件拷贝到远程主机。
* owner参数 : 指定文件拷贝到远程主机后的属主,但是远程主机上必须有对应的用户,否则会报错。
* group参数 : 指定文件拷贝到远程主机后的属组,但是远程主机上必须有对应的组,否则会报错。
* mode参数 : 指定文件拷贝到远程主机后的权限,如果你想将权限设置为”rw-r–r–“,则可以使用mode=0644表示,如果你想要在user对应的权限位上添加执行权限,则可以使用mode=u+x表示。

2.执行验证

[student@workstation ansible]$ ansible-playbook --syntax-check issue.yml
[student@workstation ansible]$ ansible-playbook issue.yml
[student@workstation ansible]$ ansible all -a 'cat /etc/issue'
servera | CHANGED | rc=0 >>
Development
serverb | CHANGED | rc=0 >>
Test
serverc | CHANGED | rc=0 >>
Production
serverd | CHANGED | rc=0 >>
Production
第十一题:创建一个web内容的目录

11. Create a web content directory
Create a playbook called /home/student/ansible/webcontent.yml as follows:
The playbook runs on managed nodes in the dev host group
Create the directory /webdev with the following requirements
- Membership in the webdev group
- Regular permissions:ower=read+write+execute,group=read+write+execute,
- other=read+execute
- Special permissions: set group ID
Symbolically link /var/www/html/webdev to /webdev
Create the file /webdev/index.html with a single line of text that reads:Development

注意点:web文件涉及http和firewall服务在编写剧本时最好带上这个条件(http、firewall服务软件安装和启动、防火墙放行http)

  1. 按要求编写剧本
[student@workstation ansible]$vim webcontent.yml
---
- name: Create a web content directory
  hosts: dev
  become: yes
  vars:
    pkgs:
      - httpd
      - firewalld
  tasks:
    - name: Install httpd and firewalld
      yum:
        name: "{{ pkgs }}"
        state: present
    - name: Start and enable firewalld and httpd
      service: 
        name: "{{ item }}"
        state: started
        enabled: yes
      loop: "{{ pkgs }}"
    - name: Create webdev group    
      group: 
        name: webdev
        state: present
    - name: Create webdev directory
      file:
        path: /webdev
        group: webdev
        state: directory
        mode: 2775
        setype: httpd_sys_content_t
        force: yes
    - name: Create a symbolicly link
      file:
        src: /webdev
        dest: /var/www/html/webdev
        state: link
        force: yes
    - name: Create file /webdev/index.html
      lineinfile: 
        path: /webdev/index.html
        state: present
        line: 'Development'
        create: yes
        setypes: httpd_sys_content_t
  1. 语法检查和执行剧本
[student@workstation ansible]$ ansible-playbook --syntax-check webcontent.yml
[student@workstation ansible]$ ansible-playbook webcontent.yml
  1. 验证
[student@workstation ansible]$ curl http://servera/webdev/index.html
Development
第十二题:生成一个硬件报告

12. Generate a hardware report
Create a playbook called /home/student/ansible/hwreport.yml that produces an output file called /root/hwreport.txt on all managed nodes with the following information :
 Inventory host name
 Total memory in MB
 BIOS version
 Size of disk device vda
 Sze of disk device vdb
 Each line of the output file contains a single key=value pair.
Your playbook should:
 Download the file hwreport.empty form the URL http://materials.example.com/labs/role-system/roles/hwreport.empty and save it as /root/hwreport.txt
 Modify /root/hwreport.txt with the correct values
 If a hardware item does not exist, the associated value should be set to NONE

过滤想要的事实

[student@workstation ansible]$ ansible localhost -m setup -a 'filter=*bios_version*'
[student@workstation ansible]$ ansible localhost -m setup -a 'filter=*memory*'
[student@workstation ansible]$ ansible localhost -m setup -a 'filter=*device*'
  1. 按要求编写剧本
[student@workstation ansible]$ cat hwreport.yml
---
- name: create a playbook to display host information
  hosts: all
  become: yes
  tasks: 
    - name: download hwreport.empty
      get_url:
        url: http://materials.example.com/labs/role-system/roles/hwreport.empty
        dest: /root/hwreport.txt
        force: yes
    - name: modify total hostname
      replace: 
        path: /root/hwreport.txt
        regexp: "^hostname=.*"
        replace: "hostname={{ inventory_hostname }}"
    - name: modify total memory
      replace:
        path: /root/hwreport.txt
        regexp: "^memory=.*"
        replace: "memory={{ ansible_memory_mb.real.total }}"
    - name: modify BIOS version
      replace:
        path: /root/hwreport.txt
        regexp: "^bios_version=.*"
        replace: "bios_version={{ ansible_bios_version }}"
    - name: modify vda size
      replace:
        path: /root/hwreport.txt
        regexp: "^vda_size=.*"
        replace: "vda_size={{ ansible_devices.vda.size }}"
      when: ansible_devices.vda is defined
    - name: modify vdb size
      replace:
        path: /root/hwreport.txt
        regexp: "^vdb_size=.*"    
        replace: "vdb_size={{ ansible_devices.vdb.size }}"
      when: ansible_devices.vdb is defined
    - name: modify vda message
      replace:
        path: /root/hwreport.txt
        regexp: "^vda_size=.*"
        replace: "vda_size=NONE"
      when: ansible_devices.vda is not defined
    - name: modify vdb message
      replace:
        path: /root/hwreport.txt
        regexp: "^vdb_size=.*"
        replace: "vdb_size=NONE"
      when: ansible_devices.vdb is not defined
  1. 语法检查和执行并验证
[student@workstation ansible]$ ansible-playbook --syntax-check hwreport.yml
[student@workstation ansible]$ ansible-playbook hwreport.yml
[student@workstation ansible]$ ansible all -a 'cat /root/hwreport.txt'
第十三题:创建一个密码文件

13. Create a password vault
Create an ansible vault to store user passwords as follows:
The name of the vault is /home/student/ansible/locker.yml
The value contains two variables as follows:
       pw_developer with value Imadev
       pw_manager with value Imamgr
The password to encrypt and decrypt the vault is whenyouwishuponastar
The password is stored in the file /home/student/ansible/secret.txt

创建一个locker.yml任务,包含两个变量值;
locker.yml又使用了ansible-vault encrypt的方式引用外部文件secret.txt进行加密。

1.创建密码文件

[student@workstation ansible]$ echo 'whenyouwishuponastar' > secret.txt

2.创建加密剧本并按要求编辑变量

[student@workstation ansible]$ ansible-vault create locker.yml --vault-password-file=secret.txt
pw_developer: Imadev
pw_manager: Imamgr

3.验证

[student@workstation ansible]$ ansible-vault view locker.yml
Vault password: whenyouwishuponastar #这里输入加密时用到的密码
pw_developer: Imadev
pw_manager: Imamgr

注释:ansible-vault --hlep 查看相关用法
ansible-vault
常用参数
[create(创建新)|decrypt(解密) edit(编辑加密文件 encrypt(加密) rekey(修改口令) view(查看)]
用法:ansible-vault [options(选项)] [vaultfile.yml]
–vault-password-file指定加密锁引用的外部文件

第十四题:创建用户账户

14. Create user accounts
A list of user be created can be found in the file called user_list.yml which you should download form http://materials.example.com/labs/role-system/roles/ and save to /home/student/ansible
Using the password vault /home/student/ansible/locker.yml created elsewhere in this exam,create a playbook called /home/student/ansible/users.yml that creates user accounts as following:
User with a job description of developer should be :
       Create on managed nodes in the dev and test host groups
       Assigned the password form the pw_developer variable
       A member of supplementary group devops
User with a job description of manager should be:
       Create on managed nodes in the prod host group
       Assigned the password from the pw_manager variable
       A member of supplementary group opsmgr
Password should use the SHA512 hash format.
Your playbook should work using the vault password file created elsewhere in this exam

获取题目要求文件

[student@workstation ansible]$ wget http://materials.example.com/labs/role-system/roles/user_list.yml
  1. 按要求编写剧本
[student@workstation ansible]$ vim users.yml
---
- name: create user accounts
  hosts: all
  become: yes
  vars_files:
    - user_list.yml  #包含用户信息
    - locker.yml     #包含密码信息
  tasks:
    - name: create a list group for dev and test
      group:
        name: devops
        state: present
      when: inventory_hostname in groups.dev or inventory_hostname in groups.test
    - name: create a list group for dev and test
      group:
        name: devops
        state: present
      when: inventory_hostname in groups.dev or inventory_hostname in groups.test
    - name: create a list group for prod
      group: 
        name: opsmgr
        state: present
      when: inventory_hostname in groups.prod
    - name: create first list user
      user:
        name: "{{ item.name }}"
        state: present
        groups: devops
        password: "{{ pw_developer | password_hash('sha512') }}"
      loop: "{{ users }}"
      when: (inventory_hostname in groups.dev and item.job == "developer") or (inventory_hostname in groups.test and item.job == "developer")
     - name: create second list user
       user:
         name: "{{ item.name }}"
         state: present
         groups: opsmgr
         password: "{{ pw_manager | password_hash('sha512') }}"
       loop: "{{ users }}"
       when: inventory_hostname in groups.prod and item.job == "manager"

2.语法检测和执行

[student@workstation ansible]$ ansible-playbook --syntax-check users.yml
ERROR! Attempting to decrypt but no vault secrets found   #报错,错误! 试图解密,但没有发现保险库秘密
[student@workstation ansible]$ ansible-playbook --syntax-check users.yml  --vault-password-file=secret.txt     #检测语法并指定加密所需的密码文件(外部密码)
再执行一遍上述操作
[student@workstation ansible]$ ansible-playbook users.yml  #同样不加密码也执行不成功
ERROR! Attempting to decrypt but no vault secrets found
[student@workstation ansible]$ ansible-playbook users.yml --vault-password-file=secret.txt

3.验证

[student@workstation ansible]$ansible all -m shell -a 'grep node /etc/passwd'
serverd | CHANGED | rc=0 >>
node3:x:1002:1002::/home/node3:/bin/bash
node4:x:1003:1002::/home/node4:/bin/bash
serverc | CHANGED | rc=0 >>
node3:x:1002:1002::/home/node3:/bin/bash
node4:x:1003:1002::/home/node4:/bin/bash
serverb | CHANGED | rc=0 >>
node1:x:1002:1002::/home/node1:/bin/bash
node2:x:1003:1002::/home/node2:/bin/bash
servera | CHANGED | rc=0 >>
node1:x:1002:1002::/home/node1:/bin/bash
node2:x:1003:1002::/home/node2:/bin/bash
第十五题.修改加密文件
  1. Rekey an ansible vault
    Rekey an existing ansible vault as follows:
  • Download the ansible vault from http://workstation.example.com/salaries.yml and save it as /home/student/ansible/salaries.yml
  • The current vault password is insecure4sure
    *The new vault password is bbe2de98389b
    *The vault remains in an encrypted state with the new password

1.按要求下载文件

[student@workstation ansible]$ wget xxxxx # 按题目要求即可,此处自建文件来模拟实验

创建模拟文件

[root@workstation ansible]# ansible-vault create salaries.yml
New Vault password: insecure4sure
Confirm New Vault password: insecure4sure
[root@workstation ansible]# chmod +x salaries.yml

2.重置文件密码

[student@workstation ansible]$ ansible-vault rekey salaries.yml
Vault password: insecure4sure
New Vault password: bbe2de98389b
Confirm New Vault password: bbe2de98389b
Rekey successful

3.验证

[student@workstation ansible]$ ansible-vault view salaries.yml
Vault password: bbe2de98389b
第十六题、配置计划任务

创建一个playbook /home/student/ansible/cron.yml ,要求如下:
在dev组内所有主机,每隔两分钟执行一次命令: logger -p cron.info “test log 1”

vim cron.yml
---
- name: create a contab job
  hosts: all
  tasks:
    - name: Ensure a job that runs at 2 minute
      cron:
      name: "logger"
      minute: "*/2"
      job: 'logger -p cron.info "test log 1"'
查看
ansible dev -m shell -a 'crontab -l' 
总结

常见错误:
1.排版格式(层级缩进问题、字典格式、单位问题、标点符号问题)
2.单词错误
3.模板参数调用选择出错
4.作用对象(hosts对象、调用模板时的作用对象)
5.事实信息采集关键字的选择
6.J2 等文件固定格式问题
帮助文档的利用
ansible-doc、man、–help
熟悉常用模块的使用
剧本的编写方法可以根据个人喜好来,只要能达到题目想要的效果

2022/9/23已过RHCE,记录并分享个人经验

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值