RHCE学习笔记2

王忘杰
2022-09-18 / 0 评论 / 263 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年09月25日,已超过791天没有更新,若内容或图片失效,请留言反馈。

yml文件 yaml声明式语言,要求语法检测必须通过
key:[空格]值
hosts:[空格]值
user模块,创建一个用户 参数:state
state: present
ansible-doc -s user 范例
ansible-doc user 范例
user:

name: johnd
comment: John Doe
uid: 1040
group: admin

使用vim写yml文件
hosts 跟inventory清单里的一台主机,跟主机组 多个主机之间或者多个组之间用逗号隔开,隔开比如web,db,lamp | all所有清单
all 即 ansible.cfg中inventory所有主机
yml写完后,通过ansible-playbook命令运行
ansible-playbook -i /tmp/invenoty2.py 使用指定清单

新建一个剧本first.yml

  • name: This is first yml file
    hosts: web,db
    tasks:

        - name: create user upnange123
          user:
                  name: upnange123
                  state: present
                  uid: 1800
    

通过ansible-playbook --syntax-check first.yml进行语法检查
playbook: first.yml 语法通过
执行完playbook后随后进行验证,通过add-hoc
ansible 组名 | 主机名 -m shell | command 都可以 -a 执行一些传统命令
command 直接对接shell环境 /bin/bash | /bin/false

格式不对检查报错
ansible-playbook --syntax-check first.yml
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 1 (char 0)
Syntax Error while loading YAML.
did not find expected '-' indicator

剧本增加模块

  • name: This is first yml file
    hosts: web,db
    tasks:

        - name: create user upnange123
          user:
                  name: upnange123
                  state: present
                  uid: 1800
        - name: verify upnange123 is exist
          shell:
                  cmd: tail -1 /etc/passwd
    

ansible-playbook first.yml 执行脚本

PLAY [This is first yml file]

读取yml文件剧本

TASK [Gathering Facts] *

收集事实变量

ok: [serverc]
ok: [serverb]
ok: [servera]
ok: [serverd]

TASK [create user upnange123]

执行第一个任务,创建用户

changed: [serverb]
changed: [serverc]
changed: [servera]
changed: [serverd]

TASK [verify upnange123 is exist] **

执行第二个任务

changed: [serverc]
changed: [serverd]
changed: [servera]
changed: [serverb]

PLAY RECAP *

回放执行过程

servera : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
serverb : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
serverc : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
serverd : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

ansible 幂等性
ok 绿色 成功 没有对结果产生影响
changed 黄色 成功了对结果产生影响
ignored 任务执行失败 忽略

找手感环节1:
最开始的playbook:
找到你的手感
vim first.yml
---(回车)
(空格)(空格)-(空格)name:(空格)xxxxxxxx(回车)
直接写hosts:(空格)xxx(回车)
直接写tasks:(回车)
直接写-(空格)name:(空格)xxxxxxxx(回车)
直接写模块比如shell:(回车)
直接写参数比如cmd:(空格)xxxxxxxx(回车)
多个参数,直接写参数比如create:(空格)xxxxxxxx(回车)
到此,一个play就结束了

多个play,先进行语法检测,多用复制粘贴

主机列表项方式

  • name: xxx
    hosts:

        - web
        - db

    tasks:

        - name: xxx
          shell: xxx
    

tasks列表项方式,直接 -模块

  • name: This is first yml file

    hosts: web,db

    hosts:

        - web
        - db 

    tasks:

        - name: create user upnange123
          user:
                  name: upnange123
                  state: present
                  uid: 1800
        - name: verify upnange123 is exist
          shell:
                  cmd: tail -1 /etc/passwd
        - user:
                name: upnange123
                state: absent
                remove: yes
    

最终验证:
ansible all -m shell -a "id upnange123"

语法检测
ansible-playbook --syntax-check first.yml进行语法检查
-C 预运行,并不真正运行,只是模拟运行
ansible-playbook -C 7.yml

排错
ansible-playbook 7.yml -v
-v 显示较为详细任务输出
-vv 任务所在行数
-vvv 环境用到的包
-vvvv 任务是通过哪个用户的身份去运行
-vv平时用的多

找手感2:
对 YAML 格式的识别以及格式上的自动对齐
vi ~/.vimrc
autocmd FileType yaml setlocal ai ts=2 sw=2 et

写playbook时开两个窗口,一个vim xxx.yml 另一个ansible-doc xxx
需要熟悉常用模块的参数

经典部署httpd
1、传统命令方式部署:
1.1 安装单节点 servera yum install httpd
1.2 启动服务器 systemctl enable --now httpd
1.3 搞站点website /var/www/html echo "xxx" > index.html
1.4 改端口httpd.conf apache 80-8080
1.5 重启httpd systemctl restart httpd
1.6 发现index.html 无法通过firefox访问 selinux端口策略、安全性上下文,firewalld查看端口开放

2、ansible不是httpd
2.1 yum模块
2.2 service模块
2.3 copy模块
2.4 lineinfile模块
2.5 service模块
2.6 copy | file setype参数,firewalld模块

举例

  • name: deploy httpd
    hosts: servera,serverb
    tasks:

        - name: install httpd package
          yum:
                    name: httpd
                    state: present
        - name: Start service httpd, if not started
          service:
                    name: httpd
                    state: started
                    enabled: yes
        - name: copy index.html
          copy:
                  content: 'upnange666'
                  dest: /var/www/html/index.html
                  owner: apache
                  group: apache
                  mode: '0444'
                  setype: httpd_sys_content_t
        - name: modify httpd.conf port 8080
          lineinfile:
                  path: /etc/httpd/conf/httpd.conf
                  regexp: '^Listen'
                  line: Listen 8080
        - name: restart httpd service
          service:
                  name: httpd
                  state: restarted
        - name: verify firewalld service is started
          service:
                  name: firewalld
                  state: started
                  enabled: yes
        - name: add firwalld policy tcp 8080
          firewalld:
                  port: 8080/tcp
                  permanent: yes
                  immediate: yes
                  state: enabled

验证
[student@workstation ansible]$ curl http://serverb:8080
upnange666[student@workstation ansible]$

playbook中的远程用户
ansible 控制节点ansible.cfg
remote_user=student | devops

被管理节点又devops用户 | devops sudo
1、被管理环境要有用户
2、要有sudo权限

ansible.cfg
remote_user=devops
除了bastion之外,其他的跑ansible任务没有问题

觉得bastion用devops不太方便 ,没有用户,调用已经存在的sudo用户
抛开全局默认的远程用户,单独执行yml针对bastion配置student用户执行
grep -v -e "#" -e "^$" ansible.cfg 查看配置方法

举例

  • name: create user devops for bastion
    hosts: bastion
    remote_user: student
    become: True
    become_method: sudo
    become_user: root
    tasks:

        - name: creat user
          user:
                  name: devops
                  state: present
    

该报错跟用户是否存在有关:
[student@workstation ansible]$ ansible bastion -m shell -a "id student"
bastion | UNREACHABLE! => {

"changed": false,
"msg": "Failed to connect to the host via ssh: devops@bastion: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
"unreachable": true

}
该报错表示devops用户没有加入sudo:
[student@workstation ansible]$ ansible bastion -m ping
bastion | FAILED! => {

"msg": "Missing sudo password"

}

变量命名
字母开头,字母、数字、下划线
变量 在不同的位置进行调用和使用
1、playbook中 优先级局中 通过vars定义变量 也可以通过vars_files 将一个外部的yml作为变量的文件使用
2、执行playbook 通过ansible-playbook -e 使用 优先级最高
3、inventory清单中指定主机组变量
优先级排序

一、在playbook中应用变量

  • name: deploy httpd
    hosts: servera,serverb
    vars:

        pack_name: httpd
        service_name: httpd
        service_port: 8080

    tasks:

        - name: install "{{ pack_name }}" package
          yum:
                    name: "{{ pack_name }}"
                    state: present
        - name: Start service "{{ service_name }}", if not started
          service:
                    name: "{{ service_name }}"
                    state: started
                    enabled: yes
        - name: copy index.html
          copy:
                  content: 'upnange666'
                  dest: /var/www/html/index.html
                  owner: apache
                  group: apache
                  mode: '0444'
                  setype: httpd_sys_content_t
        - name: modify httpd.conf port "{{ service_port }}"
          lineinfile:
                  path: /etc/httpd/conf/httpd.conf
                  regexp: '^Listen'
                  line: Listen "{{ service_port }}"
        - name: restart "{{ service_name }}" service
          service:
                  name: "{{ service_name }}"
                  state: restarted
        - name: verify firewalld service is started
          service:
                  name: firewalld
                  state: started
                  enabled: yes
        - name: add firwalld policy tcp "{{ service_port }}"
          firewalld:
                  port: "{{ service_port }}/tcp"
                  permanent: yes
                  immediate: yes
                  state: enabled
    

二、创建外部vars变量文件
[student@workstation vars]$ cat ~/ansible/vars/httpd.yml
pack_name: httpd
service_name: httpd
service_port: 8080

引用外部vars变量文件

[student@workstation ansible]$ cat deploy-httpd.yml

  • name: deploy httpd
    hosts: servera,serverb
    vars_files:

        - vars/httpd.yml

    tasks:

[student@workstation ansible]$ cat remove_httpd.yml

  • name: remove httpd
    hosts: servera,serverb
    vars_files:

        - vars/httpd.yml

    tasks:

        - name: remove
          yum:
                  name: "{{ pack_name }}"
                  state: absent
    

三、在playbook运行时指定变量名,优先级最高
ansible-playbook -e 变量名=变量值 -e 变量名=变量值
[student@workstation ansible]$ ansible-playbook remove_httpd.yml -e pack_name=redis

PLAY [remove "redis"] *

TASK [Gathering Facts] **
ok: [serverb]
ok: [servera]

四、在清单中对单一主机指定变量,清单中优先级比playbook中定义vars | vars_file 要低
[student@workstation ansible]$ cat inventory
bastion
[web]
servera pack_name=redis

在清单中对主机组中所有主机设置变量
[student@workstation ansible]$ cat inventory
bastion
[web]
servera
serverb
[db]
serverc
serverd
[web:vars]
pack_name=vsftp

优先级
1、ansible-playbook -e 优先级最高
2、vars | vars_file 优先级居中
3、清单变量优先级最低

debug信息输出

[student@workstation ansible]$ cat regist.yml

  • name: register copy module
    hosts: web
    tasks:

        - name: copy output
          copy:
                  src: upnange.txt
                  dest: /opt/
                  mode: 4777
          register: upnange
        - name: debug output
          debug:
                  #msg: "upnange.txt copy sucess!"
                  var: upnange
    

变量类型
字符串

数组
[student@workstation vars]$ cat users.yml
users:

    upwen:
            uid: 1888
            user-name: upwen2022
            shell: /bin/bash
    upnange:
            uid: 1900
            user-name: upnange666
            shell: /bin/nologin

取值
users.upwen.user_name
users'upnange'

需要调试!

[student@workstation ansible]$ cat useradd.yml

  • name: useradd user
    hosts: web
    vars_files:

        - vars/users.yml

    tasks:

        - name: create user "{{ users.upwen.user_name }}"
          user:
                  name: "{{ users.upwen.user_name }}"
                  uid: "{{ users.upwen.uid }}"
                  shell: "{{ users.upwen.shell }}"
                  state: present
        - name: create user "{{ users['upnange']['user_name'] }}"
          user:
                  name: "{{ users['upnange']['user_name'] }}"
                  uid: "{{ users['upnange']['uid'] }}"
                  shell: "{{ users['upnange']['shell'] }}"
                  state: present

[student@workstation ansible]$ cat vars/users.yml
users:

    upwen:
            uid: 1888
            user_name: upwen2022
            shell: /bin/bash
    upnange:
            uid: 1900
            user_name: upnange666
            shell: /bin/nologin

过滤器 用来设置密文密码
password: "{{ 'redhat' | password_hash('sha512') }}"

举例

  • name: useradd user
    hosts: web
    vars_files:

        - vars/users.yml

    tasks:

        - name: create user "{{ users.upwen.user_name }}"
          user:
                  name: "{{ users.upwen.user_name }}"
                  uid: "{{ users.upwen.uid }}"
                  shell: "{{ users.upwen.shell }}"
                  state: present
                  password: "{{ 'redhat' | password_hash('sha512') }}"
        - name: create user "{{ users['upnange']['user_name'] }}"
          user:
                  name: "{{ users['upnange']['user_name'] }}"
                  uid: "{{ users['upnange']['uid'] }}"
                  shell: "{{ users['upnange']['shell'] }}"
                  state: present
                  password: "{{ 'redhat' }}"

验证,不使用passwd过滤器的显示为明文
[student@workstation ansible]$ ansible web -m shell -a "tail -4 /etc/shadow"
servera | CHANGED | rc=0 >>
upwen2022:!!:19252:0:99999:7:::
upnange666:!!:19252:0:99999:7:::
upwen2033:$6$.bNwaSnhAOaSFJs1$GOVFXHv4TbSmJQwP676gEGnHEtHE.bTHnOBR7KyHal5jD/125j6yGfok5wOD0SU1it.og01i1YjWZ2WeQCwjj0:19252:0:99999:7:::
upnange667:redhat:19252:0:99999:7:::
serverb | CHANGED | rc=0 >>
upwen2022:!!:19252:0:99999:7:::
upnange666:!!:19252:0:99999:7:::
upwen2033:$6$4jdDWFLp3bfV0aV3$PXLKRGG4ccsH4NaXWfQXmKaylBqGu5ItITw8wUOmsLbbctkx9lF/4SHiSfAEODXI35YvmGXIR/Zmpvt5L5uXq.:19252:0:99999:7:::
upnange667:redhat:19252:0:99999:7:::

管理机密定义
管理机密
ansible vault 创建、编辑、加密、解密、查看文件

创建新的加密yml文件
ansible-vault create vault1.yml
编辑
edit
查看
view

指定密码运行
--ask-vault-pass

通过文件读取密码
--vault-password-file=/xx.txt

通过ansible.cfg配置密码,配置后全部操作免密
第140行,取消注释修改
vault_password_file = /xx

先创建再加密
ansible-vault encrypt useradd.yml
解密
ansible-vault decrypt useradd.yml
更新密码
rekey

管理事实:
1、收集事实

2、关闭开启事实收集
gather_facts: no | yes

3、收集事实变量
ansible servera -m setup

4、魔法变量
ansible localhost -m debug -a "var=hostvars.localhost"

ansible实施与控制
简单循环 loop "{ item }}"
示例

[student@workstation ansible]$ cat loop1.yml

  • name: create user
    hosts: web
    tasks:

        - name: loop user
          user:
                  name: "{{ item }}"
                  state: present
          loop:
                  - upwen12
                  - upwen13
                  - upwen14
                  - upwen15
    

when条件
魔法变量
事实变量
rc值 result code num
变量 == 值
变量 != 值
变量 is defined
变量 is not defined

when举例

[student@workstation ansible]$ cat when1.yml

  • name: when test
    hosts: web,db,balancer
    tasks:

        - name: install haproxy on balancer group
          yum:
                  name: haproxy
                  state: latest
          when: inventory_hostname in groups.web
        - name: install redis on db group
          yum:
                  name: redis
                  state: latest
          when: inventory_hostname in groups['db']
    

rc举例

[student@workstation ansible]$ cat rc.yml

  • name: rc
    hosts: web
    tasks:

        - name: rpm
          shell:
                  cmd: rpm -qa | grep -i haproxy
          register: upnange
        - name: debug
          debug:
                  var: upnange.rc
    

when结合rc举例

[student@workstation ansible]$ cat rc.yml

  • name: rc
    hosts: web
    tasks:

        - name: rpm
          shell:
                  cmd: rpm -qa | grep -i haproxy
          register: upnange
        - name: remove
          yum:
                  name: haproxy
                  state: absent
          when: upnange.rc == 0
        - name: debug
          debug:
                  var: upnange.rc
    

验证
ansible web -m shell -a "rpm -qa | grep -i haproxy"


程序处理
启动服务 | 重启服务 handlers实现
必须对应一个play模块 对应的任务黄色changed 实现handlers
ansible幂等性 黄色changed
handlers 整个playbook中最后才去运行
1、install httpd 触发handlers
2、搞网站
3、改主配置文件端口 8080
4、防火墙策略
最后一步 handlers start | restart 服务 curl | firefox

举例

upnange666[student@workstation ansible]$ cat handlers.yml

  • name: deploy httpd
    hosts: servera,serverb

    vars:

    pack_name: httpd

    service_name: httpd

    service_port: 8080

    vars_files:

        - vars/httpd.yml

    tasks:

        - name: install "{{ pack_name }}" package
          yum:
                    name: "{{ pack_name }}"
                    state: present
          notify:
                    - restart "{{ service_name }}" service
        - name: copy index.html
          copy:
                  content: 'upnange666'
                  dest: /var/www/html/index.html
                  owner: apache
                  group: apache
                  mode: '0444'
                  setype: httpd_sys_content_t
        - name: modify httpd.conf port "{{ service_port }}"
          lineinfile:
                  path: /etc/httpd/conf/httpd.conf
                  regexp: '^Listen'
                  line: Listen "{{ service_port }}"

    handlers:

        - name: restart "{{ service_name }}" service
          service:
                  name: "{{ service_name }}"
                  state: restarted
        - name: verify firewalld service is started
          service:
                  name: firewalld
                  state: started
                  enabled: yes
        - name: add firwalld policy tcp "{{ service_port }}"
          firewalld:
                  port: "{{ service_port }}/tcp"
                  permanent: yes
                  immediate: yes
                  state: enabled

验证
[student@workstation ansible]$ curl http://servera:8080
upnange666

任务控制,失败处理

需修改验证

[student@workstation ansible]$ cat rremove_httpd.yml

  • name: remove "{{ pack_name }}"
    hosts: servera,serverb
    vars_files:

        - vars/httpd.yml

    tasks:

        - name: remove
          yum:
                  name: http
                  state: absent
          ignore_errors: yes
    

handlers强制通过

[student@workstation ansible]$ cat deploy-httpd.yml

  • name: deploy httpd
    hosts: servera,serverb
    force_handlers: yes

指定失败条件
failed_when:
举例:

[student@workstation ansible]$ cat failed_when.yml

  • name: failed_when
    hosts: web
    tasks:

        - name: excute /bin/false
          command: /bin/false
          register: upnange
          failed_when: upnange.rc != 1
        - name: debug
          debug:
                  var: upnange.rc

验证:
TASK [debug]
ok: [servera] => {

"upnange.rc": "1"

}
ok: [serverb] => {

"upnange.rc": "1"

}

ansible 块与错误处理
block | rescue | always
首先在block跑play任务,
成功-》进入always中运行play任务
不成功-》进入rescue中,执行rescue里的play任务,再去走always

举例

[student@workstation ansible]$ cat block_rescure_always.yml

  • name: block & rescure & always
    hosts: web
    tasks:

        - name: block & rescure & always
          block:
                  - name: vaerify upnange
                    shell: id -un upnange
    
          rescue:
                  - name: create user upnange
                    user:
                            name: upnange
                            state: present
    
          always:
                  - name: mofity upnange user groups is wheel
                    user:
                            name: upnange
                            groups: wheel
                            append: yes

验证
[student@workstation ansible]$ ansible web -m shell -a "id upnange"
serverb | CHANGED | rc=0 >>
uid=1906(upnange) gid=1906(upnange) groups=1906(upnange),10(wheel)
servera | CHANGED | rc=0 >>
uid=1906(upnange) gid=1906(upnange) groups=1906(upnange),10(wheel)

在被管理节点执行
lineinfile:

blockinfile:
创建写入
ansible web -m blockinfile -a "path=/opt/up.txt create=true block='up666'"
清空内容
[student@workstation ansible]$ ansible web -m blockinfile -a "path=/opt/up.txt state=absent"

sefcontext: selinux模块

stat:

jinja2模板
模板 xxx.j2 文件名 使用事实变量 | 魔法变量
通过template模块 src参数指定xxx.j2 dest= ansible被管理节点中的一个目标
在被管理节点中可以输出 自己的事实变量的内容 servera fqdn ip kernel
也可以在servera输出 别人的事实变量的值
servera | b | c /etc/hosts文件

通过jinja2 获取配合循环for控制if

jinja2语法

调用变量: {{ ansible_facts.fqdn }}
ansible servera -m setup 输出servera的事实变量

循环:
{{% for xxxx %}}
中间贯穿变量的使用
{{% endfor %}}

结合事实变量
xx.j2
welcome to vist {{ ansible_facts.fqdn }}

结合魔法变量
xx.j2
也可以这样写:
[student@workstation ansible]$ cat for.j2
{% for upnange in groups['all'] %}
{{ hostvars[upnange].ansible_facts.default_ipv4.address }} {{ hostvarsupnange['fqdn'] }} {{ hostvarsupnange['hostname'] }}
{% endfor %}


管理大项目 CMDB 配置管理数据库
动态清单

演示 动态清单
启动环境
[student@workstation ansible]$ lab projects-inventory start

Setting up workstation for lab exercise work:

· Verifying Ansible installation.............................. SUCCESS
· Creating working directory.................................. SUCCESS
· Deploying ansible.cfg....................................... SUCCESS

[student@workstation ansible]$ cd ~
[student@workstation ~]$ cd projects-inventory/
[student@workstation projects-inventory]$ ll
total 4
-rw-r--r--. 1 student student 33 Sep 18 09:39 ansible.cfg

下载脚本
wget http://materials.example.com/labs/projects-inventory/inventorya.py
wget http://materials.example.com/labs/projects-inventory/inventoryw.py
chmod +x *.py

ansible -i ./inventorya.py servera --list-hosts

./inventorya.py --list

配置并行
[student@workstation ansible]$ cat ansible.cfg | grep forks

forks = 5

滚动更新,防止同时停止服务
serial: 1
位置在hosts下一行

包含include和导入import,引申roles角色
把yml拆分多个小的yml
安装:install.yml
防火墙:firewalld.yml
管理服务:service.yml

import 静态操作,解析剧本时对所有import静态处理
include动态操作,执行playbook时进行处理

install.yml 负责主要是安装的功能
service.yml 负责主要是服务管理的功能
注意,不要写hosts

总体yml project1.yml 写hosts
import install.yml
include service.yml

举例

[student@workstation ansible]$ cat install.yml

  • name: install package
    yum:

        name: vsftpd
        state: latest

[student@workstation ansible]$ cat service.yml

  • name: service manage
    service:

        name: vsftpd
        state: started
        enabled: yes

[student@workstation ansible]$ cat porject1.yml

  • name: project1
    hosts: db
    tasks:

        - name: import install vsftpd
          import_tasks: install.yml
        - name: include service vsftpd
          include_tasks: service.yml
    

验证
[student@workstation ansible]$ ansible-playbook porject1.yml

PLAY [project1] *

TASK [Gathering Facts] **
ok: [serverd]
ok: [serverc]

TASK [install package] **
changed: [serverd]
changed: [serverc]

TASK [include service vsftpd] *
included: /home/student/ansible/service.yml for serverc, serverd

TASK [service manage] *
changed: [serverc]
changed: [serverd]

PLAY RECAP **
serverc : ok=4 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
serverd : ok=4 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

通过角色简化playbook
roles角色
通过roles 标准化的目录结构
目录1 子目录: var 子目录:template
目录1 变成一个角色 使用 任何的yml 不带hosts

写一个用于调用该角色的一个yml 这个yml文件指定hosts
[student@workstation ansible]$ cat ansible.cfg | grep roles

additional paths to search for roles in, colon separated

roles_path = /home/student/ansible/roles

初始化roles
[student@workstation roles]$ ansible-galaxy init apache

  • Role apache was created successfully
    [student@workstation roles]$ ll
    total 0
    drwxrwxr-x. 10 student student 154 Sep 18 10:22 apache
    [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
    角色叫apache 里面包含主体的yml tasks目录下 hadlers 目录用于触发器 vars存放变量文件 templates j2

角色如何去做:
1、自定义
2、系统角色
3、从ansible galaxy 网站 下载 使用

1、自定义 ansible-galaxy init apache
自己从头到尾编写

2、系统角色 直接安装即可 写好调用即可

3、从ansible galaxy网站 通过anisble-galaxy install 方式 指定角色压缩包 写好调用的角色 配置好hosts

系统角色

ansible控制节点
[student@workstation roles]$ sudo yum install rhel-system-roles -y
[student@workstation roles]$ ansible-galaxy list

/usr/share/ansible/roles

  • linux-system-roles.certificate, (unknown version)
  • linux-system-roles.crypto_policies, (unknown version)
  • linux-system-roles.ha_cluster, (unknown version)
  • linux-system-roles.kdump, (unknown version)
  • linux-system-roles.kernel_settings, (unknown version)
  • linux-system-roles.logging, (unknown version)
  • linux-system-roles.metrics, (unknown version)
  • linux-system-roles.nbde_client, (unknown version)
  • linux-system-roles.nbde_server, (unknown version)
  • linux-system-roles.network, (unknown version)
  • linux-system-roles.postfix, (unknown version)
  • linux-system-roles.selinux, (unknown version)
  • linux-system-roles.ssh, (unknown version)
  • linux-system-roles.sshd, (unknown version)
  • linux-system-roles.storage, (unknown version)
  • linux-system-roles.timesync, (unknown version)
  • linux-system-roles.tlog, (unknown version)
  • rhel-system-roles.certificate, (unknown version)
  • rhel-system-roles.crypto_policies, (unknown version)
  • rhel-system-roles.ha_cluster, (unknown version)
  • rhel-system-roles.kdump, (unknown version)
  • rhel-system-roles.kernel_settings, (unknown version)
  • rhel-system-roles.logging, (unknown version)
  • rhel-system-roles.metrics, (unknown version)
  • rhel-system-roles.nbde_client, (unknown version)
  • rhel-system-roles.nbde_server, (unknown version)
  • rhel-system-roles.network, (unknown version)
  • rhel-system-roles.postfix, (unknown version)
  • rhel-system-roles.selinux, (unknown version)
  • rhel-system-roles.ssh, (unknown version)
  • rhel-system-roles.sshd, (unknown version)
  • rhel-system-roles.storage, (unknown version)
  • rhel-system-roles.timesync, (unknown version)
  • rhel-system-roles.tlog, (unknown version)

    /etc/ansible/roles

    [student@workstation roles]$ cd /usr/share/ansible/roles/
    [student@workstation roles]$ ls
    linux-system-roles.certificate rhel-system-roles.certificate
    linux-system-roles.crypto_policies rhel-system-roles.crypto_policies
    linux-system-roles.ha_cluster rhel-system-roles.ha_cluster
    linux-system-roles.kdump rhel-system-roles.kdump
    linux-system-roles.kernel_settings rhel-system-roles.kernel_settings
    linux-system-roles.logging rhel-system-roles.logging
    linux-system-roles.metrics rhel-system-roles.metrics
    linux-system-roles.nbde_client rhel-system-roles.nbde_client
    linux-system-roles.nbde_server rhel-system-roles.nbde_server
    linux-system-roles.network rhel-system-roles.network
    linux-system-roles.postfix rhel-system-roles.postfix
    linux-system-roles.selinux rhel-system-roles.selinux
    linux-system-roles.ssh rhel-system-roles.ssh
    linux-system-roles.sshd rhel-system-roles.sshd
    linux-system-roles.storage rhel-system-roles.storage
    linux-system-roles.timesync rhel-system-roles.timesync
    linux-system-roles.tlog rhel-system-roles.tlog

timesync时间同步的系统角色 复制到
[student@workstation roles]$ cp -av rhel-system-roles.timesync/ /home/student/ansible/roles/

系统角色,写好调用timesync角色的yml

Example Playbook

Install and configure ntp to synchronize the system clock with three NTP servers:

- 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

实验环境ntp在classroom中 classroom.example.com

  • hosts: web
    vars:
    timesync_ntp_servers:

    - hostname: classroom.example.com
      iburst: yes

    roles:

    • rhel-system-roles.timesync

    复制到vim中需要先进入粘贴模式
    :set paste
    验证结果ansible web -m shell -a "chronyc sources -v"
    timedatectl

关注一个点:系统角色已经提前写好 tasks目录下的main.yml时角色主题,不需要 ansible-playbook main --syntax-check
只检查自己调用角色的yml

自定义角色

变量-vars目录
jinja2模板-timplates目录
handlers触发器-handlers目录

自定义角色:

ansible-galaxy init apache

变量:
[student@workstation apache]$ cat ../../var/httpd.yml
pack_name: httpd
service_name: httpd
service_port: 8080

apache角色中的vars目录中的main.yml

[student@workstation vars]$ cat main.yml

vars file for apache

pack_name: httpd
service_name: httpd
service_port: 8080

jinjia2模板:
[student@workstation vars]$ cat ../../../upnange.j2
welcome to vist {{ ansible_facts.fqdn }} {{ ansible_facts['fqdn'] }} on {{ ansible_facts.default_ipv4.address }}

apache角色中的templates目录中的main.yml
[student@workstation templates]$ cp -p /home/student/ansible/upnange.j2 .

handlers触发器:
apache角色中的hanlders目录中的main.yml

  - name: start {{ service_name }} service
    service:
      name: "{{ service_name }}"
      state: started
      enabled: yes

[student@workstation handlers]$ cat main.yml

handlers file for apache

  • name: start {{ service_name }} service
    service:
    name: "{{ service_name }}"
    state: started
    enabled: yes

apache角色中的tasks目录中的main.yml 存放主体的yml

[student@workstation tasks]$ cat main.yml

tasks file for apache

  • name: install {{ pack_name }} package
    yum:
    name: "{{ pack_name }}"
    state: present
  • name: template index.html
    template:
    src: upnange.j2
    dest: /var/www/html/index.html
    owner: apache
    group: apache
    mode: 0444
    setype: httpd_sys_content_t
  • name: modify httpd.conf port {{ service_port }}
    lineinfile:
    path: /etc/httpd/conf/httpd.conf
    regexp: '^Listen'
    line: line: "Listen {{ service_port }}"
    notify:

    • start {{ service_name }} service
  • name: add firewall policy tcp {{ service_port }}
    firewalld:
    port: "{{ service_port }}/tcp"
    permanent: yes
    immediate: yes
    state: enabled

调用apache角色的yml
[student@workstation tasks]$ vim /home/student/ansible/apache.yml


  • name: deploy apache
    hosts: web
    roles:

    • apache

ansible-galaxy

galaxy.ansible.com
rz -E xx
sz -E xx
上传下载

ansible-galaxy

https://galaxy.ansible.com/
community-aws-1.5.0.tar.gz 上传ansible控制节点
rz -E community-aws-1.5.0.tar.gz 直接上传到workstation

sz -E xxxx.txt

F0主机的/content目录下新建roles目录 上传

通过浏览器访问http://content.example.com/roles/

workstation wget http://content.example.com/roles/community-aws-1.5.0.tar.gz

写一个yml 指定角色的来源 并且角色名称

[student@workstation roles]$ cat require.yml

[student@workstation roles]$ ansible-galaxy install -r require.yml -p /home/student/ansible/roles

ansible 故障排除

配置ansible日志
[student@workstation ansible]$ cat ansible.cfg | grep log_path

log_path = /var/log/ansible.log

自动化模块
copy | file | fetch

管理类模块
yum_repository

自动化模块:
copy | file | fetch | yum | user | group | lineinfile | blockinfile | stat | yum_repository | service | firewalld

管理类模块:

搭建YUM仓库
gpgcheck=1
gpgkey=http://content.example.com/rhel8.4/x86_64/dvd/RPM-GPG-KEY-redhat-release

csa rpm --import http://content.example.com/rhel8.4/x86_64/dvd/RPM-GPG-KEY-redhat-release

ansible all -m shell -a "rpm --import http://content.example.com/rhel8.4/x86_64/dvd/RPM-GPG-KEY-redhat-release"

rpm_key管理模块:

[student@workstation ansible]$ cat yum_repository.yml

user管理模块:
name | uid | group私有组 | groups | append | home | state present absent | password + 过滤器 | expires 账户的过期时间 shadow 倒数第2列 19700101+

useradd -e
密码的过期时间 42~60 90 :
ansible all -m shell -a "chage -M xxxxx"

it-manager | PM product manager |
role 身份

存储的管理模块:
涉及到分区parted、文件系统filesystem、挂载mount (标准形式)
LVM lvg lvol

传统命令:
vgcreate -s 16M upnangevg /dev/vdb /dev/vdc2
lvg 模块
1、先去创建转换pv pvcreate /dev/vdb
2、vgcreate

vgcreate -s 32M upnangevg /dev/vdc1
lvg:

  - name: create upnangevg
    lvg:
      vg: upnangevg
      pvs: /dev/vdb
      pesize: 32

创建lv逻辑卷
lvcreate -L xxG -n lv1 upnangevg
lvcreate -l xxxpe个数 -n lv1 upnangevg
lvol:

  - name: create lv1 in upnangevg
    lvol:
      vg: upnangevg
      size: 800m
      lv: lv1

创建文件系统:
mkfs -t ext4 | mkfs.xfs /dev/upnangevg/lv1

filesystem:

  - name: create filesystem ext4
    filesystem:
      fstype: ext4
      dev: /dev/upnangevg/lv1

挂载使用:涉及到开机自动挂载 /etc/fstab 随手写到该文件中
mkdir -p /opt/dir1 && mount /dev/upnangevg/lv1 /opt/dir1 && vi /etc/fstab

mount模块:
state: mounted mount /dev/upnangevg/lv1 + vi /etc/fstab

[student@workstation ansible]$ cat storage.yml

  • name: deploy lvm
    hosts: web
    tasks:

    • name: create upnangevg
      lvg:
      vg: upnangevg
      pvs: /dev/vdb
      pesize: 32m
    • name: create lv1 in upnangevg
      lvol:
      vg: upnangevg
      size: 800m
      lv: lv1
    • name: create filesystem ext4
      filesystem:
      fstype: ext4
      dev: /dev/upnangevg/lv1
    • name: mount filesystem
      mount:
      path: /opt/dir1
      src: /dev/upnangevg/lv1
      fstype: ext4
      state: mounted

分区模块:parted
parted 分区 set 分区号1 lvm on flag
parted -l flag /dev/vdb1 = LVM

[student@workstation ansible]$ cat parted.yml

  • name: parted /dev/vdb in db group
    hosts: db
    tasks:

    • name: parted
      parted:
      device: /dev/vdb
      number: 1
      part_end: 800MiB
      state: present
    • name: create file system
      filesystem:
      fstype: xfs
      dev: /dev/vdb1
    • name: mount
      mount:
      path: /opt/dir2
      src: /dev/vdb1
      fstype: xfs
      state: present

cron计划任务:
crontab -e -u upnange
crontab -e 当前用户(root | upnange)
分 时 日 月 周 命令的全路径(考试跟全路径)
10 17 * echo hello

systemctl restart crond

cron模块:

[student@workstation ansible]$ cat cron.yml

  • name: cron
    force_handlers: yes
    hosts: web
    tasks:

    • name: cron
      cron:
      name: this is a job
      minute: "11"
      hour: "17"
      user: upnange
      job: "/usr/bin/echo hello"
      state: present
      notify:

      • restart crond service
    • name: create file
      file:
      path: /opt/file1
      state: file

    handlers:

    • name: restart crond service
      service:
      name: crond
      state: restarted

[student@workstation ansible]$ ansible web -m shell -a "tail -10 /var/log/cron"

RHCSA:
1、磁盘分区结构 磁盘接口
2、操作系统安装
3、系统启动 init | systemd
4、nmtui | nmcli | nmcli add | nmcli modify
5、systemd功能 systemctl | systemctl --user
6、目录操作mkdir rmdir stat

文件操作 touch cp mv rm
链接文件 ln -s | ln

7、系统信息收集 lscpu df du free timedatectl hostsnamectl tree find more less cat
8、ssh 免密操作
9、用户管理 userad | usermod | userdel
-u -g -G -d -e -p -s -aG -m -r
10、组 私有组 附加组 groupadd groupmod groupdel
11、权限 chmod | chown chgrp

特殊权限 suid | sgid | sticky
ACL setfacl | getfacl

12、软件 rpm -qa -qc -ql

yum 仓库 yum | yum group xx
yum module 模块流 contos-stream 

13、磁盘管理 分区 fdisk gdisk parted
14、lvm pv vg lv
15、swap mkswap dd if=/dev/zero of=/xxx bs=xxx count=xxx
16、VDO | stratis
17、日志 rsyslog journald
18、find
19、容器podman
20、tuned

RHCE:ansible
ansible.cfg 清单 静态 | 动态 CMDB配置管理数据库
自动化模块
过滤器
playbook
角色roles

DevOPS开发运维+自动化

上午 RHCSA 满分300分 210通过 22道题 3个小时 前7天
下午 RHCE 满分300分 210通过 16道题 4个小时 Ansible内容
所有题 都是上机操作

V2.1版本 RHCSA+RHCE 最新版本
RH124&134 RH294 平时上课练习环境
考试练习环境:RHCE_exam vmware 虚拟机 CSA+CE 自带参考的评分脚本
只要按照 样题解析文档 每一道题会包含知识点+解题步骤+最后要注意的细节 考试通过没有任何问题

考试环境
node1 node2 registry
15个人考试
node1.domain01.xxxx
node1.domain03.xxxx

用户密码
node1 root flectrag
node2 自己破解

强烈建议大家,考试的时候 涉及到创建用户、密码、YUM仓库地址 进行复制粘贴

RHCSA 有两道根Podman 镜像服务器 admin redhat321

重要测评信息
重新引导node1 node2 ,保证所有操作开机启动运行,无法引导启动为零分

RHCSA 3个小时考试时间 强烈建议大家1.5个小时昨晚 0.5小时检查
RHCE 4个小时 2小时做完 0.5小时检查

ansible-playbook --syntax-chenck xxx.yml

练习环境
通过快照切换考试环境
F0主机 用户名kiosk 密码redhat

三个组件
红帽 考试题目
虚拟机控制台
终端

node1 node2 虚拟机控制台会用console
node1 一开始不叫node1 IP console root | flectrag nmcli修改IP
node2 叫node2 一开始进不去 root密码不知道 console 重启 -grub xxx

考试通过终端terminal答题

做题 按照样题解析全部做完

26道题
有可能CSA及CE每个部分有一道从没见过的题目
按顺序做题

node1
题目1 配置主机 网络等
通过nmcli配置网络
通过hostnamectl修改主机名

题目2 配置YUM仓库

题目3 调试selinux

题目4 创建用户组

题目5 配置cron计划任务

题目6 配置协作目录

题目7 配置NTP

题目8 atuofs

题目9 配置/var/tmp/fstab权限

题目10 配置用户账户

题目11 查找文件

题目12 查找字符串

题目13 创建存档

题目14 配置容器使其自动运行

题目15 为容器配置持久存储

题目16 可能从新题,可能从下面抽一道
1、编写shell
全路径执行

2、设置用户密码过期时间

3、设置用户默认权限

4、设置sudo

node2
题目1 设置root密码

题目2 配置你的系统以使用默认仓库

题目3 调整逻辑卷大小

题目4 添加swap交换分区

题目5 创建逻辑卷

题目6 创建VDO卷

题目7 调优集

测试参考评分
exam-grade

RHCE
16道题 4小时

control node1 - 5 系统IP采用静态设置
Ansible控制节点已经创建了用户账户greg
Ansible必须通过greg普通用户登录control控制节点
默认工作目录在普通用户家目录下的ansible中 yml ansible inventory roles /home/greg/ansible

题目1 安装配置ansible
ssh greg@control
建议用vim
host_key_checking=False #考试时不需要配置,会扣一点分数
考试时不需要配置被管理节点的sudo

题目2 创建和运行Ansible
考试中用全路径执行 /xxx.sh
GPGKEY导入

题目3 安装软件包

题目4 使用RHEL系统角色

题目5 使用Ansible Galaxy安装角色

题目6 创建和使用角色

题目7 从Ansible Galaxy使用角色

题目8 创建和使用逻辑卷

题目9 生成主机文件

题目10 修改文件内容

题目11 创建web内容目录

题目12 生成硬件报告

题目13 创建密码库

题目14 创建用户账户

题目15 更新Ansible库的密钥

题目16 配置cron作业

参考评分 exam-grade

1

评论

博主关闭了所有页面的评论