Ansible playbook功能详解

Ansible playbook 基础

yaml语言官网:www.yaml.org
playbook简介

由多个模块组成,后缀名 .yaml .yml

playbooks 是一种简单的配置管理系统与多机器部署系统的基础.与现有的其他系统有不同之处,且非常适合于复杂应用的部署.
Playbooks 可用于声明配置,更强大的地方在于,在 playbooks 中可以编排有序的执行过程,甚至于做到在多组机器间,来回有序的执行特别指定的步骤.并且可以同步或异步的发起任务.
adhoc,主要是使用 /usr/bin/ansible 程序执行任务.而使用 playbooks 时,更多是将之放入源码控制之中,用之推送你的配置或是用于确认你的远程系统的配置是否符合配置规范。

playbook特殊字符的含义
hosts:主机组
remote_user: 认证用户
tasks: 任务,执行命令
handlers: 触发器
vars: 变量
#: 注释
加密playbook
decrypt:解密
encrypt:加密
view:查看加密后的 .yaml文件
edit:编辑加密后的 .yaml文件
rekey: 重置密码

1.为一个文件进行加密,加密之后的 .yaml文件是不能执行的,需要解密
[root@localhost ansible]# ansible-vault  encrypt  test.yaml
New Vault password: 输入密码
Confirm New Vault password: 输入密码 
Encryption successful

2.将文件进行解密
[root@localhost ansible]# ansible-vault decrypt test.yaml 
Vault password: 输入密码
Decryption successful

playbook 只针对某一台主机执行,测试playbook ,忽略剧本错误
1.'测试运行 playbook' ,-C(大)  并不会真正运行,先测试一遍
ansible-playbook -C  yaml剧本

2.'针对某一台主机执行'  --limit 主机地址/域名
ansible-playbook test3.yaml --list-hosts	查看执行剧本主机
ansible-playbook test3.yaml  --limit 192.168.10.21	针对某一台主机执行剧本
192.168.10.21              : ok=2    changed=1 

3. '忽略剧本错误',不论是否执行成功,都继续执行此剧本
ignore_errors:True  或者 || /bin/true

---
task:
	- name: run this command and ignore the result
	  shell: /usr/bin/somecommand || /bin/true
	- name: ...
          ...
---
task:
    - name: run this command and ignore the result
      shell: /usr/bin/semecommand
      ignore_errors: True
    - name:...
      ...
ansible-console 交互下的ahdoc模式
[root@localhost ansible]# ansible-console

root@all (3)[f:5]$ cd db
root@db (1)[f:5]$ shell netstat -anpt | grep httpd
192.168.10.22 | CHANGED | rc=0 >>
tcp6       0      0 :::80                   :::*                    LISTEN      7655/httpd          

root@db (1)[f:5]$ exit

一、主机和用户

1.基础的playbook主机用户写法
---
    - hosts: db				#指定主机清单中的主机
      remote_user: root			#指定用户
            
2.指定多个主机
---
	#第一台主机
	- hosts: db
	  remote_user: root
	  
---
	#第二台主机
	- hosts:nginx
	  remote_user: root
普通用户执行root用户权限,su
提权参数:
become:yes		开启提权
become-method:su	 使用su命令进入到root用户
become-user:root	指定提权等级用户

1.在hosts清单里,设置 root用户密码
[db]
192.168.10.22   ansible_become_pass=密码

2.playbook剧本使用方法
---
	#方法1,整个剧本提权 到root权限
    - hosts: db
      remote_user: zs
      become: yes
      become_method: su
      become_user: root

---
	#方法2,指定 tasks单独指令进行提权
	 tasks:
        - name: date
          shell: date > /tmp/date.txt
          become: yes
          become_method: su
          become_user: root
   
普通用户提权,sudo
提权参数:
become:yes			开启提权
become-method:sudo	 使用su命令进入到root用户

1.在主机清单写入 sudo密码
[db]
192.168.10.22   ansible_sudo_pass=密码

2.playbook剧本使用方法
---
    - hosts: db
      remote_user: zs
      become: yes
      become_method: sudo
      tasks:
          - name: date
            shell: date > /tmp/date.txt

二、tasks列表

1.每一个 play 包含了一个 task 列表(任务列表).一个 task 在其所对应的所有主机上(通过 host pattern 匹配的所有主机)执行完毕之后,下一个 task 才会执行

2.每一个 task 必须有一个名称 name,这样在运行 playbook 时,从其输出的任务执行信息中可以很好的辨别出是属于哪一个 task 的

3.下面是一种基本的 task 的定义,service moudle 使用 key=value 格式的参数,这也是大多数 module 使用的参数格式:

在这里插入图片描述

4.如果 action 行看起来太长,你可以使用 space(空格) 或者 indent(缩进) 隔开连续的一行
在这里插入图片描述

三、Handlers: 在发生改变时执行的操作

’notify’ 会在 playbook 的每一个 task 结束时被触发,而且即使有多个不同的 task 通知改动的发生, ‘notify’ actions 只会被触发一次.

1.当一个配置文件被修改后,可以执行多次重启操作
---
	- name: copy conf file
	  copy: src=/usr/local/httpd/conf/httpd.conf  dest=/etc/httpd/conf/ backup=yes
	  notify: 
	      - restart memcached
	      - restart apache
handlers:
	- name: restart memcached
	  service: name=memcached state=restarted
	- name: restart apache
	  service: name=httpd state=restarted

四、tags 标签

执行剧本中的某一个标签 tasks内容,写一个简单的http剧本如下

---
    - hosts: db
      remote_user: root
      tasks:
          - name: mount sr0
            mount: src=/dev/sr0 path=/media state=mounted fstype=iso9660
          - name: yum httpd
            yum: name=httpd state=installed
            #标签1:安装httpd服务
            tags: install_http
          - name: copy conf
            copy: src=/etc/httpd/conf/httpd.conf                                                  dest=/etc/httpd/conf/httpd.conf                                                 backup=yes
            #标签2:复制配置文件
            tags: copy_conf
            notify:
                 - restart httpd
          - name: start httpd
            service: name=httpd state=started enabled=yes
            #标签3:启动httpd服务
            tags: start_httpd

      handlers:
          - name: restart httpd
            service: name=httpd state=restarted

根据标签,来挑取 任务执行,比如说修改配置文件之后,
只执行复制配置文件,并根据notify重启服务

-t 指定标签 格式: -t 标签名,标签2 剧本名

1.修改配置文件监听端口
[root@localhost ansible]# vim /etc/httpd/conf/httpd.conf 
Listen 8080

2.执行第二个标签和第三个标签,复制配置文件并根据notify重启服务
[root@localhost ansible]# ansible-playbook -t copy_conf httpd.yaml
TASK [copy conf] ************************************************************************
changed: [192.168.10.22]

RUNNING HANDLER [restart httpd] *********************************************************
changed: [192.168.10.22]

root@db (1)[f:5]$ shell netstat -anpt | grep httpd
192.168.10.22 | CHANGED | rc=0 >>
tcp6       0      0 :::8080                 :::*                    LISTEN      
验证结果:单独执行复制配置文件标签后,通过notify执行了handles触发器重启服务

3.查看剧本中的所有标签
[root@localhost ansible]# ansible-playbook  httpd.yaml  --list-tags
play #1 (db): db	TAGS: []
TASK TAGS: [copy_conf, install_http, start_httpd]

五、variables变量

变量遵循的是 yaml语法的 Dictionary字典,由多个key与value构成

系统自带变量,支持通配符查询

格式: ansible 主机组 -m  setup  -a  'filter=*_'
例句: 查询定义主机IP地址的变量
ansible db -m setup -a 'filter=*address*'

例句:查询有关内存的变量
ansible db -m setup | grep mem
示例:
---
    #一个员工的信息
    vars:
       name: sunhaiming
       age: 21
       sex: man
1.ahdoc设置变量
1.自带变量,过滤出相要查询的对应的变量
[root@localhost ansible]# ansible db -m setup -a 'filter=ansible_proc_cmdline'

2.设置自定义变量
ahdoc格式:ansible-playbook  -e  "var=变量值"  剧本名
编写一个简单的剧本,引用变量 var
[root@localhost ansible]# vim test.yaml
---
    - hosts: db
      remote_user: root
      tasks:
        - name: touch file
          shell: echo {{ var }} >/tmp/vars.txt

ahdoc执行:
[root@localhost ansible]# ansible-playbook -e "var=hello world" test.yaml 

这种设置变量的方法测试即可,不适用于剧本
2.playbook设置变量
1.编写一个剧本,在剧本中设置好变量,用vars:来指定
[root@localhost ansible]# vim test.yaml
---
    - hosts: db
      remote_user: root
      vars:
          var: hello world!
          http_port: nginx
      tasks:
        - name: touch file
          shell: echo {{ var }} >/tmp/vars.txt
        - name: netstat nginx
          shell: netstat -anpt | grep {{ http_port }}

2.执行剧本
[root@localhost ansible]# ansible-playbook test.yaml
3.将变量放在一个文件中,通过调用文件使用变量

vars_files: 指定变量文件

1.编写一个 .yaml 文件存放 vars变量
'注意另起文件写变量的时候注意: 冒号后面需要空格'
[root@localhost ansible]# vim vars.yaml
var1: samba
var2: vsftpd

[root@localhost ansible]# vim test2.yaml 
---
- hosts: db
  remote_user: root
  vars_files:
       - /etc/ansible/var.yaml
  tasks:
       - name: yum samba
         yum: name={{ var1 }} state=installed
       - name: yum vsftpd
         yum: name={{ var2 }} state=installed
4.在主机清单里设置变量
方法1,针对某个主机设置变量
[db]
192.168.10.21  http_port: 81
192.168.10.22  http_port: 82

方法2,设置公用变量
[db:vars]
var1=value1
var2=value2
var3=value3

注意:此时这里的 vars公用变量由 : 变成了=号

六、模板 templates

目录:templates, 模块:template 在剧本中引用template不要带 s

文本文件,嵌套有脚本(使用模板编程语言编写)
jinja2语言,使用字面量,有如下形式
字符串:使用单引号或双引号
数字:整数、浮点数
列表:[item1,item2]
元组:(item1,item2)
字典:{item1,item2}
布尔型:{key1:value1,key2:value2,…}

算数运算:+ - * / // % **
比较操作:== ,!= > < ,>= <=
逻辑运算:and or not
流式表达:For If When

案例:
nginx服务的  worker_processes auto:

1.在 ansible 目录下 单独创建一个 templates 目录,同级目录
[root@localhost ansible]# mkdir templates

2.将 nginx.conf 文件 复制到 templates目录下,并重命名 .j2结尾
[root@localhost templates]# cp /usr/local/nginx/conf/nginx.conf  ./nginx.conf.j2

3.获取有关 CPU的系统变量
[root@localhost templates]# ansible db -m setup | grep cpu
"ansible_processor_vcpus": 1, 

4.将系统变量添加在 nginx.conf.j2 模板中
worker_processes  {{ ansible_processor_vcpus }};

5.通过 nginx.conf.j2 模板的 template模块来传递配置文件
tasks:
    - name: copy temolate
      template: src=nginx.conf.j2   dest=/usr/local/nginx/conf/nginx.conf
      notify: restart nginx
handlers:
    - name: restart nginx
      shell: killall nginx && nginx
案例2:根据不同主机生成不同端口的nginx服务
1.修改 Inventory 主机清单,设置每个主机的 端口变量
[db]
192.168.10.21  http_port: 81
192.168.10.22  http_port: 82

2.修改 nginx.conf.j2模板中的端口设置,设置成通过变量获取
server {
	listen  {{ http_port }};
	listen  [::]:{{ http_port }};

When 条件测试

通过前一条任务的执行结果来为某tasks命令执行,通过when语句来进行条件判断,采用jinja2的格式。
when语句在 task后添加子句,即可使用条件测试。

案例:如果操作系统为 RedHat 则输出 ‘hello world!’
tasks:
	- name: echo hello world
	  command: /usr/bin/echo  'hello world' > /tmp/when.txt
	  when: ansible_os_family == 'RedHat'
案例2:如果操作系统为 6版本,则进行关机
[root@localhost templates]# ansible all -m setup -a 'filter=*distribution*'
"ansible_distribution_major_version": "7"
"ansible_distribution_major_version": "6"

tasks:
	- name: shutdown -h
	  shell: shutdown -h now
	  when: ansible_distribution_major_version == '6'

‘hello world!’

tasks:
	- name: echo hello world
	  command: /usr/bin/echo  'hello world' > /tmp/when.txt
	  when: ansible_os_family == 'RedHat'
案例2:如果操作系统为 6版本,则进行关机
[root@localhost templates]# ansible all -m setup -a 'filter=*distribution*'
"ansible_distribution_major_version": "7"
"ansible_distribution_major_version": "6"

tasks:
	- name: shutdown -h
	  shell: shutdown -h now
	  when: ansible_distribution_major_version == '6'
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值