自动化运维---playbook入门指南

自动化运维—ansible playbook(一)

playbook主要使用YMAL语法,这里通过几个例子直接了解编写规则!

示例1:

写一个playbook脚本,使其执行ping和创建目录的动作:
首先在server4中删除/testdir下的所有内容(如果之前没有做过即可忽略):
在这里插入图片描述
编写脚本:

vim ping.yml 
---
- hosts: testB
  remote_user: root
  tasks:
  - name: ping the host
    ping:
  - name: make directory haha
    file:
      path: /testdir/haha
      state: directory

注意:playbook脚本名的后缀一定是.yml或者.yaml
在这里插入图片描述
在这里插入图片描述

脚本解释:
操作对象:testB
在主机中以指定用户身份进行操作:root
tasks后是要执行的动作
第一个动作名为:ping the host(自己定义)
使用的模块:ping(没有指定参数)
第二个动作名为:make directory haha(自己定义)
使用的模块:file
指定参数:路径及名称:/testdir/haha;类型:目录

注意:
1.脚本以---开头
2.每个部分的开头需要有-和一个空格
3.参数名后面要加冒号,冒号后要有一个空格才能写具体内容

测试脚本内容是否正确:

ansible-playbook --syntax-check ping.yml 

执行:

ansible-playbook ping.yml

在这里插入图片描述

示例2:

修改操作对象为testA:

vim ping.yml 
---
- hosts: testA
  remote_user: root
  tasks:
  - name: ping the host
    ping:
  - name: make directory haha
    file:
      path: /testdir/haha
      state: directory

模拟执行:

ansible-playbook --check ping.yml 	

执行:

ansible-playbook ping.yml

在这里插入图片描述
在这里插入图片描述
注意:此处的hosts和/etc/ansible/hosts文件中写的内容保持一致,可以是组名、别名,也可以是ip

示例3:

vim touch-test.yml
---
- hosts: testB
  remote_user: root
  tasks:
  - name: make testfile
    file:
      path: /testdir/testfile
      state: touch
      mode: 0700

在这里插入图片描述
模拟执行:

ansible-playbook --check touch-test.yml 

执行:

ansible-playbook touch-test.yml

在这里插入图片描述
在这里插入图片描述

示例4:

cp touch-test.yml touch-test1.yml 
vim touch-test1.yml 
---
- hosts: testB
  remote_user: root
  tasks:
  - name: make testfile
    file: path=/testdir/testfile state=touch mode=0700

在这里插入图片描述
参数信息可以写在同一行,不使用冒号的格式,可以使用=号连接
在这里插入图片描述

示例5:

cp touch-test1.yml touch-test2.yml 
vim touch-test2.yml 
---
- hosts: testB
  remote_user: root
  tasks:
  - name: make testfile
    file: path=/testdir/testfile
          state=touch
          mode=0700

在这里插入图片描述
参数信息也可以分开来写,不使用冒号的格式,使用=号连接
在这里插入图片描述

示例6:

vim touch-test2.yml 
---
- hosts: testB
  remote_user: root
  tasks:
  - file: path=/testdir/testfile
          state=touch
          mode=0700

在这里插入图片描述

name参数可以不写,默认为使用的模块名。但这里建议不要省略name参数!
注意:删掉name参数后,file作为开头,所以需要加-

语法检测:

ansible-playbook --syntax-check touch-test2.yml

在这里插入图片描述

示例7:

vim touch-test2.yml 
---
- hosts: testB
  remote_user: root
  tasks:
  - file: path=/testdir/testfile
          state=touch
          mode=0700
    name: make testfile

在这里插入图片描述
name参数可以卸载file后面(顺序不会有影响)
语法检测:

ansible-playbook --syntax-check touch-test2.yml

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值