ansible学习笔记二:playbook

Tani ·
更新时间:2024-09-21
· 806 次阅读

ansible学习笔记二:playbook环境:测试ansible-playbook1. 测试一例:2. 在yml内增加tags及handlers3. 在yml内增加变量:3.1 方法1,外部通过-e去指定:3.2 方法2,内部指定:3.3 方法3,用setup模块里的变量:3.4 方法4,在其他文件内指定变量:4. 通过template生成模板,在模板文件内修改成变量模式,以实现各机器的不一致:5. playbook内添加when:5.1 相当于if判断5.2 相当于shell里的for循环:5.2.1 测试1,迭代:5.2.2 测试2,迭代嵌套子变量:5.3.1 写成表达式的方式:5.3.2 或者可以写成下面的方式5.4 比较复杂的5.5 在for循环内添加if判断
继续接上一章,上一章记录了常用的模块,这里就开始把模块应用到ansible-playbook内。 环境:

因为自己笔记本性能问题,这里只用两台虚拟机做测试:

服务器名 IP
ansible-server 192.168.31.53
ansible-client 192.168.31.167
测试ansible-playbook 1. 测试一例:

ansible-playbook的文件是yml格式的,这里先说下yml里的格式:

格式 说明
默认开头以3个-开头
host 指定剧本运行在什么主机组
remote_user 指定以什么用户去执行下面的动作
tasks 动作开始
name 说明当前动作是做什么的

这里需要注意的是,每一个name下,只能跟一个动作

写yml,执行完之后检查各项,用-C去检查
示例:在/root/下创建newfile文件,增加test99用户,指定为系统用户,shell类型为:/sbin/nologin,安装httpd服务,拷贝本机/var/www/html/index.html到指定机器/var/www/html目录下,开启httpd服务,并设为开机自启

[root@ansible ~]# cat file.yml

--- - hosts: all remote_user: root tasks: - name: create new file file: name=/root/newfile state=touch - name: create new user user: name=test99 system=yes shell=/sbin/nologin - name: install package yum: name=httpd - name: copy html copy: src=/var/www/html/index.html dest=/var/www/html/ - name: start service service: name=httpd state=started enabled=yes

当运行完上面的之后,检查

[root@ansible ~]# ansible all -m shell -a ‘ls /root/ -l’
192.168.31.167 | CHANGED | rc=0 >>
total 8
-rw-r–r-- 1 root root 21 Feb 8 22:19 123
-rw-r–r-- 1 root root 1190 Feb 5 22:57 ks.cfg
-rw-r–r-- 1 root root 0 Feb 9 04:13 newfile

[root@ansible ~]# ansible all -m shell -a ‘getent passwd test99’
192.168.31.167 | CHANGED | rc=0 >>
test99❌987:981::/home/test99:/sbin/nologin

[root@ansible ~]# ansible all -m shell -a ‘ss -tln| grep :80’
192.168.31.167 | CHANGED | rc=0 >>
LISTEN 0 128 :::80 ::



playbook ansible

需要 登录 后方可回复, 如果你还没有账号请 注册新账号