ansible中playbook实施
编写和运行 ansible playbook
对于操作查看指定用户,我们使用临时命令来做的话:
ansible pc2.hehe.com -m user -a “name=redhat uid=1000 state=present”

如果使用palybook 来编写操作,我们需要用 yaml 格式编写,后缀扩展名为yml
yaml 对于缩进量没有严格要求,但是有两个基本原则’
1.处于同一层次结构中同一级别的数据元素必须具有相同的缩进量’
2.如果项目属于其他项目的子项,其缩进量必须大于父项’
同一 playbook 中的键应当使用相同的缩进量
playbook编写方式:
创建文件并编写:vim user.yml
--- #格式开头三个破折号,文档的开始标记
- name: Check user #对playbook功能进行描述,选择写
hosts: pc1.hehe.com #添加受管主机或组
tasks: #运行模块
- name: Redhat User
user:
name: redhat
uid: 1000
state: present
... #格式,结尾三个省略号,结束标记(通常可以省略)
执行 playbook 前最好进行语法验证
ansible-playbook --syntax-check xxx.yml
检查完语法后,可以再测试空运行看命令执行是否有误
ansible-playbook -C xxx.yml

检测都没有问题后,我们就可以去真实执行playbook了
ansible-playbook xxx.yml

实验测试:
为受管主机去安装apache服务并且设置为开机启动
[root@work testlist-inventory]# vim service.yml
---
- name: Setup Apache
hosts: usersevers
tasks:
- name: Install Apache
yum:
name: httpd
state: latest
- name: Apache is enable
service:
name: httpd
state: started
enabled: true
...
然后使用 ansible-playbook --syntax-check 和 ansible-playbook -C 进行语法和空运行检测,没有问题后我们直接去进行操作

提高输出详细程度
ansible-playbook 默认输出不提供详细任务执行信息。
-v 参数提供,共四个级别:
-v #显示任务结果
-vv #显示任务结果和任务配置
-vvv #包含关于与受管主机的连接信息
-vvvv #增加连接插件相关的额外详细程度选项(包括受管主机上用于执行脚本的用户及所 执行的脚本)
yaml 的注释方式
1.在行前直接写 # 注释
2.在行中也可以用 # 注释行中#号后的内容
playbook中多个tasks实施操作
实验操作:在受管主机中安装apache服务,并且在火墙中添加http服务,开启服务并开机启动,设置默认发布页面为“hello world”,最后在本机连接测试
[root@work testlist-inventory]# vim intranet.yml
---
- name: Enable intranet services
hosts: usersevers
become: yes #使用身份提升,因为需要设置firewall
tasks:
- name: latest version of httpd and firewalld installd #检测 httpd 是否安装和是否最新版本
yum:
name:
- httpd
- firewalld
state: latest
- name: test html page is configured #检测是否配置默认发布页面
copy:
content: "Welcome to world!\n"
dest: /var/www/html/index.html
- name: firewalld enabled and running #检测防火墙是否开启并处于 enable 状态
service:
name: firewalld
enabled: true
state: started
- name: firewalld permits access to httpd service #检测防火墙是否允许 httpd 服务访问
firewalld:
service: http
permanent: true
state: enabled
immediate: yes
- name: httpd enabled and running #检测 httpd 是否开启和设置开机启动
service:
name: httpd
enabled: true
state: started
- name: Test intranet web server #在本机测试
hosts: localhost
become: no
tasks:
- name: connect to intranet web server #测试访问pc1
uri:
url: http://servera.lab.example.com
return_content: yes
status_code: 200 #200表示连接正常
...
还是先进行语法和空运行检测没有问题后我们执行playbook

进行真实执行后我们得到成功的答案,为了验证可以用浏览器测试

本文详细介绍如何使用AnsiblePlaybook进行自动化部署和管理,包括编写Playbook文件、执行语法检查、空运行测试以及最终的执行过程。通过实例演示在受管主机上安装Apache服务、配置防火墙、设置默认网页并进行远程测试。
863

被折叠的 条评论
为什么被折叠?



