编写基本的 ansible playbook
1.编写和运行 playbook
1. 查看指定用户的临时命令
'yaml 格式通常以 yml 为扩展名,yaml 对于缩进量没有严格要求,但是有两个基本原则'
1.处于同一层次结构中同一级别的数据元素必须具有相同的缩进量
2.如果项目属于其他项目的子项,其缩进量必须大于父项
把上面的改写为 playbook
剧本内容:
执行结果:
例1:编写playbook在受管主机中安装 apache
剧本内容:
执行结果:
效果:在node2中我们查看结果,可以看到在node2中apache安装成功。
例2:编写playbook,使得受管主机实现服务开机启动**
剧本内容
执行结果:
效果:
我们看到,http和ftp服务实现了开机自启
2. 提高输出详细程度
因为ansible-playbook 默认输出不提供详细任务执行信息。
-v 参数提供,共四个级别:
-v #显示任务结果
-vv #显示任务结果和任务配置
-vvv #包含关于与受管主机的连接信息
-vvvv #增加连接插件相关的额外详细程度选项(包括受管主机上用于执行脚本的用户及所
执行的脚本)
注意:
在执行 playbook前最好进行语法检测,这样我们就可以很容易的判断出我们的playbook哪里写错了。
正确的语法输出结果如下图
错误的会出现报错:它会指出错误的具体信息
3. 执行空运行
执行空运行意思就是说并没有执行命令,而是显示我们执行playbook命令时将会在目标主机中产生什么效果。
我们来看一下效果:
我们没有在目标主机中安装HTTP服务,来进行一下空运行。
执行结果看似和运行了雅漾,但是它并没有运行。
在目标主机中还是没有安装HTTP服务。
所以,空运行只会报告执行这个 playbook 将会发生什么结果,但不会真正去改变目标主机的效果。
例3:安装、配置默认发布页并启动 apache
做此实验时,我们首先创建一个新的目录demo
第一步:
创建配置文件和清单
第二步:
创建默认发布页面
第三步:
编写符合要求的playbook
第四步:
检测语法
第五步:
空运行
第六步:
执行 playbook
运行结果:
2.实施多个 playbook
模板:
---
- name: first play #第一个playbook
hosts: servera.example.com
tasks:
- name: first task #第一个playbook的第一个任务
yum:
name: httpd
status: present
- name: second task #第一个playbook的第二个任务
service:
name: httpd
enabled: true
- name: second play #第二个playbook
hosts: serverb.example.com
tasks:
- name: first task #第二个playbook的第一个任务
service:
name: mariadb
enabled: true
#...
...
ansible-doc -l #列出所有模块
ansible-doc yum #查看具体yum模块的用法
ansible-doc -s yum #终端中输出 yum 模块中各参数的用法
PLAYBOOK 语法变化
- yaml 注释
# This is a YAML comment
some data # This is also a YAML comment #两种方式
- yaml字符串
this is a string #单引号和双引号,具体的在语法部分具体说明
'this is a string'
"this is a string"
练习
首先配置清单和配置文件,和上面的例子一样,这里就不列出了
下面我们直接编写关于多个playbook
---
- name: Enable intranet services
hosts: web
become: yes
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 westos!\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 #测试访问 rhel8_node2
uri:
url: http://rhel8_node2.westos.com
return_content: yes
status_code: 200
ansible-playbook --syntax-check intranet.yml
#检测语法
ansible-playbook -C intranet.yml
#空运行
ansible-playbook -v intranet.yml
#运行,-v显示任务结果
可以看到返回了内容 welcome to westos和状态码 200
效果: