1、细心细心
2、主机1的第一题和第二题千万不能错,错了就百分百过不了上午的,主机2的vdo磁盘一定不能出错,出错或没有开机运行vdo机子就重启不来,题目全做完一定要全先重启电脑,起来后再全部检测一遍每道题,时间很充足,不要急。
第1-2题比较重要一定不能出错,考试上面的重要信息要仔细看,先不要着记做题,至少看2遍,下午题的精髓就是把ansible里的变量、判断、循环和一些架构搞清楚,必须要理解,只要理解了,不管怎么出都能做的出来。
判断磁盘大小没有就给默认值
alue: “{{ ansible_facts.devices.vdb.size | default(‘NONE’) }}”
判断vgs在不在用:
when: “‘research’ in ansible_lvm.vgs” //或 not in 不存在
when: ansible_lvm.vgs.research is undefined //这样也可以
判断磁盘在不在用:
when: ansible_facts.devices.vdd is defined //或undefined
选择变量里面的key=value进行判断:
when: item.name == ‘jack’
判断单个主机是否在这个主机组里
when: inventory_hostname in groups[‘prod’] //或 not in
得到当前主机的名称node1(放在剧本中用自动会循环获取gether_facts得到的所有主机)
ansible dev -m debug -a “msg={{ inventory_hostname }}”
ansible dev -m debug -a “msg={{ hostvars.node1.ansible_password }}”
拿到dev主机组中的所有主机的密码
ansible dev -m debug -a “msg={{ hostvars.node1 }}”
拿到dev主机组中的所有主机的详细信息
ansible dev -m debug -a “msg={{ groups }}”
拿到清单中所有主机组和各组中的主机
welcome to {{ansible_hostname }} on {{ansible_default_ipv4.address }}
jinjia2.j2文件中放入这些变量,复制过去受控机自动替换变量
groups[‘all’] //得到清所有的主机列表
inventory_hostname in groups[‘var’] //循环var主机组中的所有主机
找fqdn和ip
Welcome to {{ ansible_fqdn }} on {{ ansible_default_ipv4.address }}
判断磁盘大小如果不在给默认值:
value: “{{ ansible_facts.devices.vdb.size | default(‘NONE’) }}”
判读文件在不在
ansible dev -m stat -a "path=/etc/ddddd"输出下面查看可以组合成stat.exists
node1 | SUCCESS => {
“ansible_facts”: {
“discovered_interpreter_python”: “/usr/bin/python”
},
“changed”: false,
“stat”: {
“exists”: false
}
}
用stat模块输出再注册一下再调用判断
tasks:
- name: file-not-yes
stat:
path: /etc/dx
register: file_status
…
…
when: file_status.stat.exists==False 在就是True
判断系统信息
先查寻一下:ansible dev -m setup |grep ansible_distribution
再写剧本 (可以加and和or)
- name:
debug:
msg: centos
when: ansible_distribution==“CentOS”
“ansible_distribution”: “CentOS”,
“ansible_distribution_file_parsed”: true,
“ansible_distribution_file_path”: “/etc/redhat-release”,
“ansible_distribution_file_variety”: “RedHat”,
“ansible_distribution_major_version”: “7”,
“ansible_distribution_release”: “Core”,
“ansible_distribution_version”: “7.9”,
-------------------开始每一题----------------------------------------
yum install ansible 直接安装,虚拟机考试里面已有ansible yum 源,考试时我看了
---------------------------------------------------------------------------
[kiosk@foundation0 ~]$ ssh greg@control /现场考试每个人的账号和密码不同一定要看清楚
greg@control's password: flectrag
[greg@control ~]$ sudo yum -y install ansible
[greg@control ~]$ mkdir -p /home/greg/ansible/roles
配置ansible需要管理的主机
[greg@control ~]$ cd ansible
[greg@control ansible]$ vim /home/greg/ansible/inventory
cp /etc/ansible/ansible.cfg /home/greg/ansible //主配置文件考过来当模板修改,他放在哪,当前执行就要在哪个路径下
[dev]
node1
[test]
node2
[prod]
node3
node4
[balancers]
node5
[webservers:children]
prod
[all:vars]
ansible_password=flectrag //保险期间加上,考试看情况受控机密码是不是一样的
[greg@control ansible]$ vim ansible.cfg
[defaults] /必须要放在第一行这个
inventory = /home/greg/ansible/inventory
roles_path = /home/greg/ansible/roles
取消ssh验证,也就是第一次ssh机器时不需要按yes更新密钥
host_key_checking = False
remote_user = greg
[privilege_escalation]
become=True
become_method=sudo //sudo方式操作
become_user=root //以root权限使用
become_ask_pass=False
测试:
[greg@control ansible]$ ansible all --list-hosts
-----------------------------------------------------------------------------------------------
[greg@control ansible]$ ansible all -m ping -o #ping下受控主机是否在线
[greg@control ansible]$ vim adhoc.sh
#!/bin/bash
ansible all -m yum_repository -a 'name=EX294_BASE description="EX294 base software" baseurl=http://content/rhel8.0/x86_64/dvd/BaseOS gpgcheck=yes gpgkey=http://content/rhel8.0/x86_64/dvd/RPM-GPG-KEY-redhat-release '
ansible all -m yum_repository -a 'name=EX294_STREAM description="EX294 stream software" baseurl=http://content/rhel8.0/x86_64/dvd/AppStream gpgcheck=yes gpgkey=http://content/rhel8.0/x86_64/dvd/RPM-GPG-KEY-redhat-release enabled=yes'
:wq
[greg@control ansible]$ chmod 755 adhoc.sh #给与执行权限
[greg@control ansible]$ ./adhoc.sh
ansible all -m shell -a "yum repolist" //查看yum仓库,会有waring不用管他
---------------------------------------------------------------------------------------------------
[greg@control ansible]$ vim packages.yml //这题没啥难度,
---
- name: install php and mariadb
hosts: dev,test,prod
vars:
packs:
- php
- mariadb
tasks:
- name: install php and mariadb
yum:
name: "{{ item }}"
state: present
loop: "{{ packs }}"
- name: install groups
hosts: dev
tasks:
- name: install dev tools
yum:
name: "@RPM Development Tools"
state: present
- name: update all
yum:
name: '*'
state: latest
:wq
[greg@control ansible]$ ansible-playbook packages.yml
验证直接看执行过程,一目了然
-----------------------------------------------------------------------
yum search roles 查系统角色软件包
sudo yum -y install rhel-system-roles
[greg@control ansible]$ vim ansible.cfg
roles_path = /home/greg/ansible/roles:/usr/share/ansible/roles
[greg@control ansible]$ ansible-galaxy list
[greg@control ansible]$ cp -r /usr/share/doc/rhel-system-roles/timesync/example-timesync-playbook.yml /home/greg/ansible/timesync.yml
cp /usr/share/ansible/rhel-system-roles.timesync ./roles/timesync //看题目要求要什么名字就拷成什么名字
[greg@control ansible]$ vim timesync.yml //修改yml文件
修改如如下样子,只保留现在的样子
- hosts: all
vars:
timesync_ntp_servers:
- hostname: 172.25.254.254
- iburs: yes
roles:
- timesync //看清楚这里题目的要求要用哪个角色,要不要改rhel-system-roles.timesync
[greg@control ansible]$ ansible-playbook timesync.yml
检测:ansible all -m shell -a "grep "server" /etc/chrony.conf"
----------------------------------------------------------------------------
[greg@control ansible]$ vim roles/requirements.yml
---
- name: balancer
src: http://materials/haproxy.tar
- name: phpinfo
src: http://materials/phpinfo.tar
[greg@control ansible]$ ansible-galaxy install -r /home/greg/ansible/roles/requirements.yml -p /home/greg/ansible/roles
检查:
tree
[greg@control ansible]$ ansible-galaxy list
-------------------------------------------------
[greg@control ~]$ cd /home/greg/ansible/roles
[greg@control roles]$ ansible-galaxy init apache //初始化,会全部建立文件夹出来
[greg@control roles]$ vim apache/tasks/main.yml
---
- name: install apache
yum:
name: httpd
state: present
- name: start service apache
service:
name: httpd
state: started
enabled: yes
- name: start service firewalld
service:
name: firewalld
state: started
enabled: yes
- name: open firewalled port
firewalld:
service: http
permanent: yes
state: enabled
immediate: yes
- name: template a file
template:
src: index.html.j2 //本同上要替换下面路径的文件位置(一般默认在template文件夹下,不用写绝对路径,这是ansible role规则定义好的)
dest: /var/www/html/index.html //受控机上的位置
[greg@control roles]$ vim apache/templates/index.html.j2
Welcome to {{ ansible_fqdn }} on {{ ansible_default_ipv4.address }} //这些系统变量要清楚
[greg@control roles]$ cd ..
[greg@control ansible]$ vim apache.yml
---
- name: test roles
hosts: webservers //这里一定是webservers不是所有,要是所有后面balancer安装LB会出错
roles:
- apache //直接调用我们手动定义好的角色apache
ansible-playbook apache.yml
验证直接打开火狐浏览器查看
----------------------------------------------------------------------
[greg@control ansible]$ vim roles.yml
---
- name: use apache and php
hosts: webservers
roles:
- apache //前面手动角色定义好的
- name: use apache and php
hosts: webservers
roles:
- phpinfo //前面用ansible-galaxy 自动角色装好的,这里直接调用
- name: use role balancer
hosts: balancers
roles:
- balancer
//前面和phpinfo一起用ansible-galaxy安装好的自动角色,里面有j2魔板,已经关联webservers主机组,直接拿来调用不用修改
[greg@control ansible]$ ansible-playbook roles.yml
测试:
$ curl http://node5/hello.php
------------------------------------------------------------------------------------
[greg@control ansible]$ vim lv.yml //这题就牢记block rescue always 这个架构,永远不会错
---
- name: create lv
hosts: all
tasks:
- debug:
msg: Volume group done not exist
when: "'research' in ansible_lvm.vgs"
- name: main all
block:
- name: create data of 1500M
lvol:
vg: research
lv: data
size: '1500' //lvol必须要引,不引会有waring
rescue:
- debug:
msg: Could not create logical volume of that size
- name: create data of 800M
lvol:
vg: research
lv: data
size: '800'
when: "'research' in ansible_lvm.vgs"
always:
- name: mkfs-ext4-800
filesystem:
dev: /dev/rescue/data
fstype: ext4
when: "'research' in ansible_lvm.vgs"
------------------------------------------------------------
[greg@control ansible]$ wget http://materials/hosts.j2
[greg@control ansible]$ vim hosts.j2
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
{% for host in groups['all'] %}
{{ hostvars[host]['ansible_default_ipv4']['address'] }} {{ hostvars[host]['ansible_fqdn'] }} {{ hostvars[host]['ansible_hostname'] }}
{% endfor %}
[greg@control ansible]$ vim hosts.yml
---
- name: create myhosts
hosts: all
tasks:
- name: template a file /etc/myhosts
template:
src: /home/greg/ansible/hosts.j2
dest: /etc/myhosts
when: inventory_hostname in groups['dev']
:wq
[greg@control ansible]$ ansible-playbook hosts.yml
---------------------------------------------------------------
[greg@control ansible]$ vim issue.yml
---
- name: replace issue
hosts: all
tasks:
- name: replace Development
copy:
content: "Development"
dest: /etc/issue
when: inventory_hostname in groups['dev']
- name: replace Test
copy:
content: "Test"
dest: /etc/issue
when: inventory_hostname in groups['test']
- name: replace Production
copy:
content: "Production"
dest: /etc/issue
when: inventory_hostname in groups['prod']
[greg@control ansible]$ ansible-playbook issue.yml
测试:
[greg@control ansible]$ ansible prod -m shell -a "cat /etc/issue"
-----------------------------------------------------------
[greg@control ansible]$ cat webcontent.yml
---
- name: web_d
hosts: dev
roles:
- apache //用前面手动建立的角色
tasks:
- name: mkdir_webdev
file:
dest: /webdev
group: webdev
mode: 2755
state: directory
setype: httpd_sys_content_t
- name: create_ln_s
file:
src: /webdev
dest: /var/www/html/webdev
state: link
- name: web_open
copy:
dest: /webdev/index.html
setype: httpd_sys_content_t
content: Development
[greg@control ansible]$ ansible-playbook webcontent.yml
-------------------------------------------------------------
ansible dev -m setup |grep "mem" //输出所有信息用于辅助过滤cpu 内存等信息
[greg@control ansible]$ cat /home/greg/ansible/hwreport.yml
---
- name: crteate_report.txt
hosts: all
tasks:
- name: get_url
get_url:
url: http://materials/hwreport.empty
dest: /root/hwreport.txt
force: yes
- name: hostname
lineinfile:
dest: /root/hwreport.txt
regexp: "{{ item.name }}" //下面的循环会一个一个的name值带进来查找
line: "{{ item.name }}={{ item.value }}" //同样下面的loop循环会把name和value带进来
loop:
- name: HOST
value: "{{ ansible_hostname }}"
- name: MEMORY
value: "{{ ansible_memtotal_mb }}"
- name: BIOS
value: "{{ ansible_bios_version }}"
- name: DISK_SIZE_VDA
value: "{{ ansible_devices.vda.size | default('NONE') }}"
- name: DISK_SIZE_VDB
value: "{{ ansible_devices.vdb.size | default('NONE') }}"
[greg@control ansible]$ ansible-playbook hwreport.yml
---------------------------------------------------------------------------------
vim ansible.cfg
修改地址和删除注释,增加对密码文件加密码的文件,最外层锁的那个文件
vault_password_file = /home/greg/ansible/secret.txt
用yum格式创建一个密码库文件,写入两个变量账号密码放到密码库中
vim locker.yml
---
pw_developer: Imadev
pw_manager: Imamgr
建立一个加密和解密的文件并对加密和解密的密码进行设置,等于是锁上加锁
vim /home/greg/ansible/secret.txt
whenyouwishuponastar
对最底层的锁进行加密码生成,上面主配文件已经改成了secret.txt作为生成工具,所以这里不用指定了
ansible-vault encrypt locker.yml
验证
cat locker.yml
ansible-value view locker
----------------------------------------------------------------------------------------
[greg@control ansible]$ wget http://materials/user_list.yml #下载文件
vim /home/greg/ansible/users.yml
---
- name: create user for dev,test
hosts: dev,test
vars_files: #变量名和vars一样,内部定义好的
- /home/greg/ansible/locker.yml #值1 密码库文件 ,上一题创建的好的
- /home/greg/ansible/user_list.yml #值2 用户文件 ,刚下载好的
tasks:
- name: create group1
group:
name: devops
state: present
- name: create user1
user: #user用户管理模块
name: "{{ item.name }}" #创建用户,用户名从变量中取
groups: devops #附加组 devops
password: "{{ pw_developer | password_hash('sha512') }}" #密码 pw_developer 上一题创建的好的
append: yes #配合groups使用,追加附属组
state: present
loop: "{{ users }}" #循环变量
when: item.job == 'developer' #描述
- name: create user for prod
hosts: prod
vars_files:
- /home/greg/ansible/locker.yml //再写一次,因为是2个hosts,上面是1个,这里又1个
- /home/greg/ansible/user_list.yml
tasks:
- name: create group2
group:
name: opsmgr
state: present
- name: create user2
user:
name: "{{ item.name }}"
groups: opsmgr
password: "{{ pw_manager | password_hash('sha512') }}" //pw_manager上一题创建好的,直接调用pw_manager的值,如果不是变量是密码一定要用引号引起来,不然报错
append: yes
state: present
loop: "{{ users }}"
when: item.job == 'manager'
ansible dev,test -m shell -a 'id bob; id sally; id fred' #验证
另一种写法:
[greg@control ansible]$ cat users.yml
---
- name: main
hosts: all
vars_files:
- /home/greg/ansible/locker.yml
- /home/greg/ansible/user_list.yml
tasks:
- name: group
group:
name: devops
state: present
when:
- inventory_hostname in groups.dev or inventory_hostname in groups.test
- name: user dev
user:
name: "{{ item.name }}"
state: present
groups: devops
append: yes
password: "{{ pw_developer|password_hash('sha512') }}"
loop: "{{ users }}"
when:
- item.job == 'developer'
- inventory_hostname in groups.dev or inventory_hostname in groups.test
- name: shell #考试有可能加了密码有效期参数,就这样写
shell: chage -M "{{ item.password_max_days }}" "{{ item.name }}"
loop: "{{ users }}"
when:
- item.job == 'developer'
- inventory_hostname in groups.dev or inventory_hostname in groups.test
- name: group2
group:
name: opsmgr
state: present
when:
- inventory_hostname in groups.prod
- name: user dev2
user:
name: "{{ item.name }}"
state: present
groups: opsmgr
append: yes
password: "{{ pw_manager|password_hash('sha512') }}"
loop: "{{ users }}"
when:
- item.job == 'manager'
- inventory_hostname in groups.prod
-------------------------------------------------------------------------------------------------
wget http://materials/salaries.yml #下载密码库文件
vim ansible.cfg //在上面主配文件已添加进去了,这里必须注释掉,不然不能改
#vault_password_file = /home/greg/ansible/secret.txt
ansible-vault rekey salaries.yml #更新密码库 密码
#密码更改完,恢复原样 ,再把注释关掉
vim ansible.cfg
vault_password_file = /home/greg/ansible/secret.txt
另一种方法,如果不注释掉配置文件就要用这个命令:
ansible-value rekey --ask-uault-pass salaries
insecure8sure #输入密码
bbs2you9527 #新密码输入2次
ansible-vault view salaries.yml #查看密码库 密码
--------------------------以下为附加题----------------------------------
yum install rhel-system-roles -y
cp -a /usr/share/ansible/roles/linux-system-roles.selinux/ relos/selinux
#复制到roles目录,按题要求用selinux角色
cp -a /usr/share/doc/rhel-system-roles/selinux/example-selinux-playbook.yml ansible/selinux.yml #复制到ansible目录
vim /home/greg/ansible/selinux.yml
#该文件内容,多余的可以删除(把从selinux_booleans删到tasks上面,再用 批量替换成我们刚才复制的名称就行了:%s/rhel-system-roles.linux/selinux/g就行了)
册完留下的就是下面的样子
[root@controls ansible]# cat selinux.yml
---
- name: Manage SELinux policy example
hosts: all
vars:
# Use "targeted" SELinux policy type
selinux_policy: targeted
# Set "enforcing" mode
selinux_state: enforcing
# Switch some SELinux booleans
# Prepare the prerequisites required for this playbook
tasks:
- name: Creates directory
file:
dest: /tmp/test_dir
state: directory
mode: "0755"
- name: Add a Linux System Roles SELinux User
user:
comment: Linux System Roles SELinux User
name: sar-user
- name: Execute the role and catch errors
block:
- name: Include selinux role
include_role:
name: 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
reboot:
- name: Wait for managed host to come back
wait_for_connection:
delay: 10
timeout: 300
- name: Reapply the role
include_role:
name: selinux
----------------------------------------------------------
date -d 2022-01-20 +%s #获取对应日期的unix时间戳
1642636800
vim create_user.yml
---
- hosts: all
vars:
- users:
- name: jack
- name: jony
tasks:
- name: create user
user:
name: "{{ item.name }}"
password: "{{ 'redhat'| password_hash('sha512') }}"
state: present
loop: "{{ users }}"
- name: Set user validity period
user:
name: "{{ item.name }}"
uid: 1111 #指定用户uid
expires: 1642636800 #指定账户到期时间,需要获取时间戳
state: present
loop: "{{ users }}"
when: item.name=='jony' #作用于jony这个用户
- name: Password expired
shell: chage -M 30 "{{ item.name }}" #shell命令,账号使用期限30天
loop: "{{ users }}"
when: item.name =='jack'
---------------------------------------------------------------------------------
vim crontab.yml //考试我抽到了这题,这题精髓就是:那些分时日月周要用哪个就写哪个,不用的不要写上去这点很重要
---
- hosts: all
tasks:
- name: create a cron file under /etc/cron.d
cron:
name: Lgin time
minute: "39"
hour: "22"
day: ""
month: "*/3"
weekday: "0"
user: jack
job: "last "
------------------------------------------------------------------------------
vim partition.yml
[root@controls ansible]# cat test.yml
---
- name: parted-mkfs-mount
hosts: all
tasks:
- name: sdb-is-not-exist
debug:
msg: disk does not exsit
when: "'sdb' not in ansible_devices"
- name: main-all
block:
- name: cratte-1500
parted:
device: /dev/sdb
number: 1
state: present
part_end: 1500MiB
when: "'sdb' in ansible_devices"
rescue:
- name: print-not-1500
debug:
msg: could not create partation of that size
- name: cratte-800
parted:
device: /dev/sdb
number: 1
part_end: 800MiB
state: present
when: "'sdb' in ansible_devices"
always:
- name: mkfs-ext4-800
filesystem:
dev: /dev/sdb1
fstype: ext4
when: "'sdb' in ansible_devices"
- name: mount-all
mount:
path: /newpart
src: /dev/sdb1
fstype: ext4
state: mounted
when: "'sdb' in ansible_devices"
------------------------------------------------------------------