自动化运维管理工具 Ansible的脚本------------playbook剧本

3 篇文章 0 订阅
2 篇文章 0 订阅

一、inventory 主机清单

1、主机清单

ansible默认的主机清单是==/etc/ansible/hosts==文件
主机清单可以手动设置,也可以通过Dynamic Inventory动态生成
一般主机名使用FQDN

Inventory支持对主机进行分组,每个组内可以定义多个主机,每个主机都可以定义在任何一个或多个主机组内。

如果是名称类似的主机,可以使用列表的方式表示各个主机
vim /etc/ansible/hosts
[webservers]
192.168.118.17:2222			#冒号后定义远程连接端口,默认是ssh的22端口
192.168.118.1[2:3]			#范围是:192.168.118.12192.168.118.13

[dbservers]
db-[a:f].example.org		#支持匹配 a~f

inventory 中的变量


ansible_host	ansible连接节点时的IP地址
ansible_port	连接对方的端口号,ssh连 接时默认为22
ansible_user	连接对方主机时使用的主机名。不指定时,将使用执行ansible或ansible-playbook命令的用户
ansible_passwd	连接时的用户的ssh密码,仅在未使用密钥对验证的情况下有效
ansible_ssh_private_key_file	指定密钥认证ssh连接时的私钥文件
ansible_ssh_common_args	提供给ssh、sftp、 scp命 令的额外参数
ansible_become	允许进行权限提升
ansible_become_method	指定提升权限的方式,例如可使用sudo/su/runas等方式
ansible_become_user	提升为哪个用户的权限,默认提升为root
ansible_become_password	提升为指定用户权限时的密码

主机变量

[webservers]
192.168.118.17 ansible_port=22 ansible_user=root ansible_password=abc123			#不建立将密码直接写入配置,不安全

组变量

[webservers:vars]				#表示为 webservers 组内所有主定义变量
ansible_user=root
ansible_password=abc1234

[all:vars]						#表示为所有组内的所有主机定义变量
ansible_port=22

组嵌套

[nginx]
192.168.118.14
192.168.118.15
192.168.118.16

[apache]
192.168.118.1[2:3]

[webservers:children]
nginx					#表示为 webservers 主机组中包含了nginx组和apache组内的所有主机
apache

2、YAML

YAML:另一种标记语言。是用来写配置文件的语言,非常简洁和强大。
YAML语法和其他语言类似,也可以表达散列表、标量等数据结构。

(1)基本语法规则

大小写敏感
使用缩进表示层级关系
缩进时不允许使用Tab键,只允许使用空格。
缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
结构通过空格来展示;序列里配置项通过-来代表;Map里键值用:来分隔;YAML的扩展名为yaml

(2)YAML支持的数据结构

对象
键值对的集合,又称为映射(mapping)/哈希(hashes)/字典(dictionary)


例如: name (): Example()

类class:(物品)
  对象1:(桌子)
    属性(名称,长、宽、高等)
    方法(动词,放东西)
    ...
  对象2
  对象3

数组
一组按次序排列的值,又称为序列(sequence)/列表(list)

例如:-Apple
     -Orange

纯量
单个的、不可再分的值

例如:number: 12.30
     sure: true

二、剧本(playbook)

1、playbook介绍

playbook是ansible用于配置,部署,和管理被控节点的剧本。通过playbook的详细描述,执行其中的tasks,可以让远端主机达到预期的状态。playbook是由一个或多个”play”组成的列表。当对一台机器做环境初始化的时候往往需要不止做一件事情,这时使用playbook会更加适合。通过playbook你可以一次在多台机器执行多个指令。通过这种预先设计的配置保持了机器的配置统一,并很简单的执行日常任务。

ansible通过不同的模块实现相应的管理,管理的方式通过定义的清单文件(hosts)所管理的主机包括认证的方式连接的端口等。所有的功能都是通过调用不同的模块(modules)来完成不同的功能的。不管是执行单条命令还是play-book都是基于清单文件

playbook格式:

  • playbook由YMAL语言编写。YMAL格式是类似于JSON的文件格式,便于人理解和阅读,同时便于书写。

  • 一个剧本里面可以有多个play,每个play只能有一个tasks,每个tasks可以有多个name

2、playbooks 的组成

  • Tasks:任务,即通过 task 调用 ansible 的模块将多个操作组织在一个playbook 中运行。
  • Variables:变量
  • Templates:模板
  • Handlers:处理器,当 changed 状态条件满足时,(notify)触发执行的操作。
  • Roles:角色

3、案例:编写httpd的playbook

vim test1.yaml
---     #yaml文件以---开头,以表明这是一个yaml文件,可省略
- name: first play     #定义一个play的名称,可省略
  gather_facts: false    #设置不进行facts信息收集,这可以加快执行速度,可省略
  hosts: webservers    #指定要执行任务的被管理主机组,如多个主机组用冒号分隔
  remote_user: root    #指定被管理主机上执行任务的用户
  tasks:     #定义任务列表,任务列表中的各任务按次序逐个在hosts中指定的主机上执行
   - name: test connection    #自定义任务名称
     ping:     #使用 module: [options] 格式来定义一个任务
   - name: disable selinux
     command: '/sbin/setenforce 0'    #command模块和shell模块无需使用key=value格式
     ignore_errors: True     #如执行命令的返回值不为0,就会报错,tasks停止,可使用ignore_errors忽略失败的任务
   - name: disable firewalld
     service: name=firewalld state=stopped    #使用 module: options 格式来定义任务,option使用key=value格式
   - name: install httpd
     yum: name=httpd state=latest
   - name: install configuration file for httpd
     copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf    #这里需要一个事先准备好的/opt/httpd.conf文件
     notify: "restart httpd"    #如以上操作后为changed的状态时,会通过notify指定的名称触发对应名称的handlers操作
   - name: start httpd service
     service: enabled=true name=httpd state=started
  handlers:     #handlers中定义的就是任务,此处handlers中的任务使用的是service模块
   - name: restart httpd    #notify和handlers中任务的名称必须一致
     service: name=httpd state=restarted


------------------------------------------------------------------------------

- name: first play
gather_facts: false
hosts: webservers
remote_user: root 
tasks:
 - name: test connection
ping:
- name: disable selinux
command: '/sbin/setenforce 0'
 ignore_errors: True
- name: disable firewalld
 service: name=firewalld state=stopped
 - name: install httpd
 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

① Ansible 管理端编写好playbook剧本
在这里插入图片描述

② 在webservers端(client1)准备httpd模板配置文件
在这里插入图片描述

③ 在webservers端(client1)将准备好的httpd模板配置文件发送到Ansible管理端
在这里插入图片描述
④ 确认被控制端的httpd服务是否安装,firewalld处于开启状态,本机的httpd模板文件准备完成并且路径和剧本配置一致
在这里插入图片描述

在这里插入图片描述
⑤ 执行playbook剧本

在这里插入图片描述
没有报错就成功了

4、补充命令

格式:
ansible-playbook [yaml文件名]
例如:ansible-playbook ping.yml
参数:-k(–ask-pass) 用来交互输入ssh密码
     -K(-ask-become-pass) 用来交互输入sudo密码
     -u 指定用户

补充命令:
ansible-playbook XXXX.yaml --syntax-check   #检查yaml文件的语法是否正确
ansible-playbook XXXX.yaml --list-task      #检查tasks任务
ansible-playbook XXXX.yaml --list-hosts     #检查生效的主机
ansible-playbook XXXX.yaml --start-at-task='ensure apache is at the latest version'  #指定从某个task开始运行

5、hosts 和 users 介绍

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

还可以为每个任务定义远程执行用户:

 - hosts: mysql
   remote_user: root
   tasks:
   - name: test connection
     ping:
     remote_user: mysql   #指定远程主机执行tasks的运行用户为mysql

执行playbook时:  ansible-playbook ping.yml -k

6、指定远程主机 sudo 切换用户

 - hosts: mysql
   remote_user: root
   become: yes         #2.6版本以后的参数,之前是sudo,意思为切换用户运行
   become_user: mysql   #指定sudo用户为mysql
   tasks:
   - name: copy text
     copy: src=/etc/fstab dest=/home/mysql/fstab.bak

执行playbook时: ansible-playbook ping.yml -K

7、tasks列表和action

1、Play的主体部分是task列表,task列表中的各任务按次序逐个在hosts中指定的主机上执行,即在所有主机上完成第一个任务后再开始。在运行playbook时 (从上到下执行),如果一个host执行task失败, 整个tasks都会回滚,请修正playbook中的错误,然后重新执行,即Task的目的是使用指定的参数执行模块,而在模块参数中可以使用变量,模块执行时幂等的,这意味着多次执行是安全的,因为其结果一定的。
2、每一个task必须有一个名称 name,这样在运行playbook时,从其输出的任务执行信息中可以很好的辨别出是属于哪一个task的。
3、定义一个task,常见的格式: ”module: options" 例如: yum: name =httpd
4、ansible的自带模块中,command模块和shell模块无需使用key=value格式

示例

 - hosts: webserver
   remote_user: root
   tasks:
   - name: stop selinux
     command: '/usr/sbin/setenforce 0'
   - name: install httpd
     yum: name=httpd
   - name: start httpd
     service: name=httpd state=started

示例

 - hosts: webserver
   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: mysql
     remote_user: root
     tasks:
     - name: copy file to mysql
       copy: src=/etc/inittab dest=/opt/inittab.back

8、Handlers介绍:

Handlers也是一些task的列表, 和一般的task并没有什么区别。
是由通知者进行的notify,如果没有被notify,则Handlers不会执行,假如被notify了 ,则Handlers被执行不管有多少个通知者进行了notify,等到play中的所有task执行完成之后,handlers也只会被执行一次

示例

 - hosts: webserver
   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: webserver
   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

9、playbook使用变量的方法

1、通过ansible命令传递

例如:编辑如下yamI

vim a.yaml
 - hosts: mysql
   remote_user: root
   vars:
   - user:
   tasks:
   - name: add new user 
     user: name={{user}}

然后执行命令: ansible-playbook a.yml -e "user=testvar"

可以执行命令查看: ansible mysql -m command -a 'tail /etc/passwd'

2、直接在yamI中定义变量,如上handlers示例

vim b.yaml
 - hosts: mysql
   remote_user: root
   vars:
   - user: gcc01
   tasks:
   - name: add new user 
     user: name={{user}}

然后执行命令: ansible-playbook b.yml

3、直接引用一些变量

: 引用ansible 的固定变量
vi test.yaml
 - hosts: mysql
   remote_user: root
   tasks:
   - name: copy file
     copy: content="{{ansible_all_ipv4_addresses}}" dest=/opt/vars.txt

执行命令:  ansible-playbook test.yaml

4、引用主机变量

vi  /etc/ansible/hosts
#在mysq|组的主机后面添加如下
[mysql]
192.168.200.40 testvar="200.45"
#定义testvar变量的值为200.45

vi test.yaml     #添加{{testvar}}主机变量
 - hosts: mysql
   remote_user: root
   tasks:
   - name: copy file
     copy: content="{{ansible_all_ipv4_addresses}},{{testvar}}" dest=/opt/vars.txt

执行命令: ansible-playbook test.yaml

10、条件测试

如果需要根据变量、facts (setup) 或此前任务的执行结果来作为某task执行与否的前提时要用到条件测试,在Playbook中条件测试使用。在task后添加when子句即可使用条件测试: when子句支持 jinjia2 表达式或语法,例如:

1、单条件判断

vim when.yml
 - hosts: mysql
   remote_user: root
   tasks:
     - name: "shutdown CentOS"
       command: /sbin/shutdown -h now
       when: ansible_distribution == "CentOS"

2、多条件判断

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

3、组条件判断

vim when.yml
 - hosts: mysql
   remote_user: root
   tasks:
    - name: "shut down 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")

4、自定义变量进行条件测试 (version2.9版本后被移出,无法使用)

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

5、迭代

当有需要重复性执行的任务时,可以使用迭代机制。其使用格式为将需要迭代的内容定义为item变量引用,并通过with_items语句指明迭代。

 - hosts: webserver
   remote_user: root
   tasks:
   - name: "Install Packages"
     yum: name={{ item }} state=latest
     with_items:
     - httpd
     - mysql-server
     - php

也可以自己定义
 - hosts: webserver
   remote_user: root
   tasks:
   - name: "Add users"
     user: name={{ item.name }} state=present groups={{ item.groups }}
     with_items:
      - { name: 'test1', groups: 'wheel'}
      - { name: 'test2', groups: 'root'}

name表示要操作的软件包的名字;
state标识要做什么操作; 
present:默认的,表示为安装;
lastest:安装为最新的版本;
absent:表示删除。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值