Ansible——playbook介绍

文章目录

  • 一、Ansible的主机清单管理
    • 1、基本配置
    • 2、类似的主机名配置
    • 3、定义变量
  • 二、YAML
    • 1、YAML介绍
    • 2、格式
    • 3、YAML支持的数据结构
  • 三、playbook简介
  • 四、playbook的核心元素
  • 五、playbook剧本示例
  • 六、playbook使用变量的方法
  • 七、template模板
  • 八、roles模块


一、Ansible的主机清单管理

1、基本配置

vim /etc/ansible/hosts
[webserver]					# 设置组名
www1.xxxxx.com				# 定义被监控的主机,可以是主机名也可以是IP地址
www2.xxxxx.com:22222		# 冒号后定义远程连接端口,默认是ssh的22端口

2、类似的主机名配置

[webserver]
www[01:50].xxxxxxx.com ansible_ssh_user=root ansible_ssh_pass=abc123
# 这句话表示01到50的主机,可以使用免交互的方式进行管理
[dbbservers]
db-[a:f].xxxxxxx.com		# 支持匹配a b c d e f 

3、定义变量

(1)主机变量

[webserver]
www1.xxxxxxx.com http_port=80 maxRequestsChild=808
www2.xxxxxxx.com http_port=8080 maxRequestsChild=909

(2)组变量

[servers:vars]
ntp_server=ntp.xxxxxx.com
nfs_server=nfs.xxxxxx.com

(3)组嵌套

[apache]
http1.xxxxxxx.com
http2.xxxxxxx.com
[nginx]
ngx1.xxxxxxx.com
ngx2.xxxxxxx.com
[webservers:children]
apache
nginx

4)inventory变量参数

参数													说明
ansible_ssh_host						将要连接的远程主机名,与你想要设定的主机的别名不同的话,可通过此变量设置 
ansible_ssh_port						ssh端口号,如果不是默认的端口号,通过此变量设置
ansible_ssh_user						默认的ssh用户名
ansible_ssh_pass						ssh密码(这种方式并不安全,强烈建议使用--ask-pass或SSH密钥)
ansible_ssh_private_key_file			ssh使用的私钥文件,适用于有多个密钥,而你不想用SSH代理的情况
ansible_ssh_common_args					此设置附加到sftp,scp和ssh默认命令行
ansible_sftp_extra_args					此设置附加到默认sftp命令行
ansible_scp_extra_args					此设置附加到默认scp命令行
ansible_ssh_extra_args					此设置附加到默认ssh命令行
ansible_ssh_pipelining					确定是否使用SSH管道,可以覆盖ansible.cfg中的设置
ansible_shell_type						目标系统的shell类型,默认情况下,命令的执行使用”sh“语法,可设置为”csh“或”fish“
ansible_python_interpreter				目标主机的python路径,适用于的情况系统中有多个 Python, 或者命令路径不是"/usr/bin/python
ansible_*_interpreter					这里的*可以是ruby或Perl或者其他语言的解释器,作用和ansible_python_interpreter类似	
ansible_shell_executable				将设置ansible控制器将在目标机器上使用的shell,覆盖ansible.cfg中的默认为/bin/sh

二、YAML

1、YAML介绍

YAML另一种标记语言,是用来写配置文件的语言,非常简洁和强大
YAML语法和其他语言类似,也可以表达散列表,标量等数据结构
结构通过空格来展示,序列里配置项通过”-“来代表,Map里键值用”:“来分隔;

2、格式

大小写敏感
使用缩进表示层级关系
缩进时不允许使用制表符,只允许使用空格
缩进的空格数不重要,只要相同层级的元素左侧对齐即可

3、YAML支持的数据结构

对象:键值对的集合,又称映射(mapping)、哈希(hashes)、字典(dictionary)
例如:name:example Developer
键 值

数组:一组按次序排列的值,又称为序列(sequence)、列表(list)
例如: - football
- basketball

纯量 单个的、不可再分的值
例如:number:33.33
sure:true

YAML例子

name:zhangsan
age:21
name:lisi
age:22
people:
- name:zhangsan
		age:21
		-name:lisi
		age:22

三、playbook简介

playbook配置文件使用了YAML语法,具有简介明了、结构清晰等特点,playbook配置文件类似于shell脚本,是一个YAML格式的文件,用于保存针对特定需求的任务列表,之前介绍的ansible命令虽然可以完成各种任务,但是当配置一些复杂的任务时,逐条输入就显得效率非常地下了,更有效的方案是在playbook配置文件中放置所有的任务代码,利用ansible-playbook命令执行该文件,可实现自动化运维,YAML文件的扩展名通常为.yaml或者.yml

四、playbook的核心元素

tasks:任务,即调用模块完成某操作
variables:变量
templates:模板
handlers:处理器,当某种条件满足时,触发执行的操作
roles:角色

五、playbook剧本示例

- hosts: test01
  vars:
    http_port: 80
    max_clients: 200
  user: root
  tasks:
  - name: ensure apache is at the latest version
    yum: name=httpd state=latest
  - name: write the apache config file
    template: src=/srv/httpd.j2 dest=/etc/httpd.conf
    notify:
    - restart apache
  - name: ensure apache is running
    service: name=httpd state=started
  handlers:
   - name: restart apache
     service: name=httpd state=restarted

执行一个playbook

ansible-playbook [yaml文件名]

例如:

ansible-playbook ping.yml
-k (-ask-pass)用来交互输入ssh密码
-K(-ask-become-pass)用来交互输入sudo密码;-u:指定用户
补充命令

ansible-playbook nginx.yaml --syntax-check			# 检查yaml文件的语法
ansible-playbook nginx.yaml --list-task				# 检查tasks任务
ansible-playbook nginx.yaml --list-hosts			# 检查生效的主机
ansible-playbook nginx.yaml --start-at-task='Copy Nginx.conf'    # 从某一个task任务开始

1)hosts和users介绍

- hosts: test01					# 指定主机组,可以是一个或多个组
  remote_user:root				# 指定远程主机执行的用户名

2)为每个任务定义远程执行用户

- hosts: test
  remote_user: root
  tasks:
   - name: test connection
     ping:
     remote_user: root		

指定远程主机sudo切换用户

- hosts:test
  remote_user: root
  become: yes
  become_user: mysql

4)tasks列表和action

- hosts: 192.168.66.11
  remote_user: root
  tasks:
   - name: disable selinux
     command: '/sbin/setenforce 0'
   - name: make sure apache is running
     service: name=httpd state=started

play中只要执行命令的返回值不为0,就会报错,tasks停止

- hosts: test
  remote_user: root
  tasks:
   - name: disable selinux
     command: '/sbin/setenforce 0'
     ignore_errors: True					# 忽略错误,强制返回成功
   - name: make sure apache is running
     service: name=httpd state=started

另一个示例:

- hosts: test
  remote_user: root
  tasks:
   - name: create nginx group
     group: name=nginx system=yes gid=208
   - name: create nginx user
     user: name=nginx uid=208 group=nginx system=yes
- hosts: test01
  remote_user: root
  tasks:
   - name: copy file to mysql
     copy: src=/etc/inittab dest=/opt/inittab.bak     

5)Handlers

- hosts: test
  remote_user: root
  tasks:
   - name: install httpd package
     yum: name=httpd state=latest
   - name: install configuration file for httpd
     copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf
     notify:
      - restart httpd
   - name: start httpd service
     service: enabled=true name=httpd state=started
  handlers:
   - name: restart httpd
     service: name=httpd state=restarted

这里也可以引入变量

- hosts: test
  remote_user: root
  vars:
  - package: httpd
  - service: httpd
  tasks:
   - name: install httpd package
     yum: name={{package}} state=latest
   - name: install configuration file for httpd
     copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf
     notify:
      - restart httpd
   - name: start httpd service
     service: enabled=true name={{service}} state=started
  handlers:
   - name: restart httpd
     service: name={{service}} state=restarted

六、playbook使用变量的方法

1、通过ansible命令传递
例如:编译如下yaml

- hosts: test01
  remote_user: root
  vars:
  - user:
  tasks:
  - name: add new user
    user: name={{user}}

执行命令:
ansible-playbook a.yml -e “user=testvar”
查看:
ansible test01 -a ‘tail /etc/passwd’

2、直接在yaml中定义变量—如上handlers示例
3、直接引用一些变量
如:引用ansible的固定变量

vim test.yml
- hosts: test01
  remote_user: root
  tasks:
   - name: copy file
     copy: content={{ansible_all_ipv4_addresses}} dest=/opt/1.txt

4、引用主机变量

vim /etc/ansible/hosts
在test01组的主机后面添加如下
[test01]
192.168.66.11 testvar="8080"			# 定义testvar变量的值为8080

vim test.yml
- hosts: test01
  remote_user: root
  tasks:
   - name: copy file
     copy: content= {{ansible_all_ipv4_addresses}} {{testvar}} dest=/opt/1.txt

5、条件测试
单条件判断:

vim when.yml
- hosts: test01
  remote_user: root
  tasks:
   - name: shutdown centos
     command: /sbin/shutdown -r now				# h:关机,r:重启
     when: ansible_distribution == "CentOS"

多条件判断:

vim when.yml
- hosts: test01
  remote_user: root
  tasks:
   - name: shutdown centos7 systems
     command: /sbin/shutdown -r now
     when:
      - ansible_distribution == "CentOS"
      - ansible_distribution_major_version == "7"

组条件判断:

vim when.yml
- hosts: test01
  remote_user: root
  tasks:
    - name: shutdown CentOS 6 and Debian 7 systems
      command: /sbin/shutdown -t now
      when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == "6") or
            (ansible_distribution == "Debian" and ansible_distribution_major_version == "7")

自定义变量进行条件测试

vim when.yml
- hosts: all
  vars:
   exist: "True"
  tasks:
   - name: create file
     command: touch /tmp/test.txt
     when: exist | match("True")
   - name: delete file
     command: rm -rf /tmp/test.txt
     when: exist | match("False")

6、迭代

- hosts: test
  remote_user: root
  tasks:
   - name: add user
     user: name={{item}}
     with_items:
       - tw
       - gcc
       - yy

也可以自己定义

- hosts: test01
  remote_user: root
  tasks:
   - name: add user
     user: name={{ item.name }} state=present groups={{ item.groups }}
     with_items:
       - { name: 'test1', groups: 'wheel'}
       - { name: 'test2', groups: 'root'}

七、template模板

例如:使用template模板安装apache
1、管理端安装apache

yum -y install httpd

cp /etc/httpd/conf/httpd.conf /opt/httpd.conf.j2		# template必须要使用j2的格式的文件

vim /opt/httpd.conf.j2
Listen {{http_port}}
ServerName {{server_name}}
MaxClients {{access_num}}

vim /etc/ansible/hosts
[test]
192.168.241.20 http_port=192.168.241.20:80 server_name=www.hzh.com access_num=100

vim apache.yml
- hosts: test
  remote_user: root
  vars:
   - names: httpd
  tasks:
   - name: install httpd
     yum: name={{names}} state=latest
   - name: config file
     template: src=/opt/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
     notify:
      - restart httpd
   - name: enable httpd
     service: name={{names}} enabled=true state=started
  handlers:
   - name: restart httpd
     service: name={{names}} state=restarted
ansible-playbook apache.yml

2、在远程主机上查看

grep -i listen /etc/httpd/conf/httpd.conf
grep -i maxclient /etc/httpd/conf/httpd.conf
grep -i servername /etc/httpd/conf/httpd.conf

tags在一个playbook中,我们会定义多个task,如果我们只要执行某一个task或者多个task时,就可以使用tags标签了
(1)打标签,只执行某一段的task

vim test.yml
- hosts: test
  remote_user: root
  tasks:
    - name: copy hosts file
      copy: src=/etc/hosts dest=/opt/hosts
      tags:
       - qqq
    - name: touch file
      file: path=/opt/hosts11 state=touch
执行命令:
ansible-playbook test.yml --tags="qqq"

(2)实际上,不光可以为单个或者多个task指定同一个tags,playbook还提供一个特殊的tags为always,也就是不管前面的tags,它一直会执行这个tags

- hosts: test
  remote_user: root
  tasks:
    - name: copy hosts file
      copy: src=/etc/hosts dest=/opt/hosts
      tags:
       - qqq
    - name: touch file
      file: path=/opt/hosts11 state=touch
      tags:
       - always
ansible-playbook test.yml --tags="qqq"
去远程端检查下就可以看到,依旧执行

八、roles模块

roles能够根据层次型结构自动装载变量文件

1、roles内各目录的含义解释

files:用来存放由copy模块或者script模块调用的文件
template:用来存放j2模板的,template模块会自动在此目录中寻址j2模板文件
tasks:此目录应当包含一个main.yml文件,用于定义此角色的任务列表,此文件可以使用include包含其他的位于此目录的task文件
handlers:此目录应当包含一个main.yml文件,用于定义此角色中触发条件时执行的动作
vars:此目录应当包含一个main.yml文件,用于定义此角色用到的变量
defaults:此目录应当包含一个main.yml文件,用于为当前角色设定默认变量
meta:此目录应当包含一个main.yml文件,用于为当前角色的特殊设定及其依赖关系

2、在一个playbook中使用roles的步骤
1)创建以roles命令的目录

mkdir -p /etc/ansible/roles        # yum装完默认就有

2)创建全局变量目录

mkdir -p /etc/ansible/group_vars
touch /etc/ansible/group_vars/all			# 文件名称可以自定义,但是在引用的时候需要注意下

3)在roles目录中分别创建以各角色名称命令的目录;例如httpd

mkdir -p /etc/ansible/roles/command

4)在每个角色命令的目录中分别创建files,templates,tasks,handlers,vars,defaults,meta,用不到的目录可以为空

mkdir /etc/ansible/roles/httpd/{files,templates,tasks,handlers,vars,defaults,meta} -p
mkdir /etc/ansible/roles/mysql/{files,templates,tasks,handlers,vars,defaults,meta} -p

5)在每个角色的defaults,vars,tasks,meta,handlers目录下创建main.yml文件,不能自定义

touch /etc/ansible/roles/httpd/{defaults,vars,tasks,meta,handlers}/main.yml
touch /etc/ansible/roles/mysql/{defaults,vars,tasks,meta,handlers}/main.yml

6)在playbook文件中,调用各角色

vim /etc/ansible/test.yml
- hosts: test01
  remote_user: root
  roles:
    - httpd
	- mysql

7)搭建lanp架构
准备需要目录

mkdir /etc/ansible/roles/httpd/{files,templates,tasks,handlers,vars,defaults,meta} -p
mkdir /etc/ansible/roles/mysql/{files,templates,tasks,handlers,vars,defaults,meta} -p
mkdir /etc/ansible/roles/php/{files,templates,tasks,handlers,vars,defaults,meta} -p

准备main.yml文件

touch /etc/ansible/roles/httpd/{defaults,vars,tasks,meta,handlers}/main.yml
touch /etc/ansible/roles/mysql/{defaults,vars,tasks,meta,handlers}/main.yml
touch /etc/ansible/roles/php/{defaults,vars,tasks,meta,handlers}/main.yml

编写httpd模块

vim /etc/ansible/roles/httpd/tasks/main.yml
- name: ensure apache is at the latest version
  yum: pkg= {{servername}} state=latest

vim /etc/ansible/roles/httpd/vars/main.yml
servername: httpd

编写mysql模块

vim /etc/ansible/roles/mysql/tasks/main.yml
- name: ensure mysql is at the latest version
  yum: pkg= {{servername}} state=latest

vim /etc/ansible/roles/mysql/vars/main.yml
servername: mariadb*

编写PHP模块

vim /etc/ansible/roles/php/tasks/main.yml
- name: ensure php is at the latest version
  yum: pkg= {{servername}} state=latest

vim /etc/ansible/roles/php/vars/main.yml
servername: php

创建剧本

vim /etc/ansible/lamp.yml
- hosts: test01
  remote_user: root
  roles:
    - httpd
	- mysql
	- php
ansible-playbook lamp.yml

你可能感兴趣的:(运维)