ansible-playbook使用教程,


• playbook 是什么?

– playbook 是 ansible 用于配置,部署,和管理托管主机
 剧本。通过 playbook 的详细描述,执行其中的一系列
 tasks,可以让远端主机达到预期的状态。
– 也可以这么理解,playbook 字面意思,即剧本,现实中
 由演员按照剧本表演,在 Ansible 中由计算机进行表
 演,由计算机安装,部署应用,提供对外服务,以及组织
 计算机处理各种各样的事情playbook是什么

• 为什么要使用playbook

 – 执行一些简单的任务,使用ad-hoc命令可以方便的解决
 问题,但是有时一个设施过于复杂,需要大量的操作时候,
 执行的 ad-hoc 命令是不适合的,这时最好使用playbook,
 就像执行 shell 命令与写 shell 脚本一样,也可以理解为
 批处理任务
– 使用 playbook 你可以方便的重用编写的代码,可以移
 植到不同的机器上面,像函数一样,最大化的利用代码
 在使用 Ansible 的过程中,你也会发现,你所处理的大
 部分操作都是编写 playbookplaybook语法基础

• playbook 语法格式

– playbook由 YAML 语言编写,遵循 YAML 标准
– 在同一行中,#之后的内容表示注释
– 同一个列表中的元素应该保持相同的缩进
– playbook 由一个或多个 play 组成
– play 中 hosts,variables,roles,tasks 等对象的表示
方法都是键值中间以 “: ” 分隔表示
– YAML 还有一个小的怪癖. 所有的 YAML 文件开始行都
应该是 —. 这是 YAML 格式的一部分, 表明一个文件的
开始playbook语法基础

• playbook 构成

– Target: 定义将要执行 playbook 的远程主机组
– Variable: 定义 playbook 运行时需要使用的变量
– Tasks: 定义将要在远程主机上执行的任务列表
– Handler: 定义 task 执行完成以后需要调用的任务playbook语法基础

• Playbook执行结果

• 使用 ansible-playbook 运行playbook文件,得到输
出内容为 JSON 格式。并且由不同颜色组成,便于识
别。一般而言
• 绿色代表执行成功
*代表系统代表系统状态发生改变
• 红色代表执行失败playbook语法基础
• 第一个playbook

- hosts: all
  remote_user: root
  tasks:
# 第一行,表示开始
– hosts 行的内容是一个或多个组或主机的 patterns,以
逗号为分隔符
– remote_user 就是账户名
– tasks
– 每一个 play 包含了一个 task 列表(任务列表).
– 一个 task 在其所对应的所有主机上(通过 host
pattern 匹配的所有主机)执行完毕之后,下一个 task
才会执行.
– 有一点需要明白的是(很重要),在一个 play 之中,
所有 hosts 会获取相同的任务指令,这是 play 的一个
目的所在,也就是将一组选出的 hosts 映射到 task,执
行相同的操作playbook语法基础


使用方法

环境准备

6台机器
 1 ansible  管理机器
 2 web1  托管机器
 3 web2  托管机器
 4 db1    托管机器
 5 db2    托管机器
 6 cache   托管机器

安装

[root@ansible ~]# yum repolist
[root@ansible ~]# yum install -y ansible

安装完成以后执行,没有报错,正确显示版本即可

ansible –version
ansible 2.4.2.0
config file = /etc/ansible/ansible.cfg
configured module search path = [u’/root/.ansible/plugins/modules’, u’/usr/share/ansible/plugins/modules’]
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Aug 4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]

配置本地解析

[root@ansible ~]# cat /etc/hosts
192.168.1.1 ansible
192.168.1.2 web1
192.168.1.3 web2
192.168.1.4 db1
192.168.1.5 db2
192.168.1.6 cache

ansible.cfg 中 inventony 指定主机分组文件的路径和地址,默认分组文件 hosts

hosts 的配置    //在配置文件最后添加

[root@ansible ~]# vim /etc/ansible/hosts
[web]
web1
web2

[db]
db[1:2]         //意思是db1到db2

[other]
cache

[other]
cache ansible_ssh_user="root" ansible_ssh_pass="123"
修改配置文件

[root@ansible ~]# vim /etc/ansible/ansible.cfg
61 host_key_checking = False //去掉注释

测试结果
[root@ansible ~]# ansible cache -m ping           //测试结果 成功结果如下
cache | SUCCESS => {
    "changed": false, 
    "ping": "pong"
} 
添加子组
[root@ansible ansible]# vim /etc/ansible/hosts

[app:children]          //添加子组  app包含db和web部分
db
web

[web:vars]              
ansible_ssh_user="root"
ansible_ssh_pass="123"
• 列出要执行的主机,不执行任何操作

ansible all –list-hosts

• 批量检测主机

ansible all -m ping

• 批量执行命令

ansible all -m command -a ‘命令’ -k

• 自定义配置文件

– 创建任意文件夹
– 在文件夹里面创建配置文件 ansible.cfg
[defaults]
inventory = myhosts //指定文件
host_key_checking = False

- 在文件夹里创建主机文件

[root@ansible ooxx]# vim myhosts
[app1]
web1
db1

[app2]
web2
db2

[app]
cache

给所有主机部署密钥

创建密钥

[root@ansible ~]# ssh-keygen -t rsa -b 2048 -N ''

给所有主机发送密钥

[root@ansible ~]# cd /root/.ssh/
[root@ansible .ssh]# ansible all -m authorized_key -a "user=root exclusive=true manage_dir=true key='$(< /root/.ssh/id_rsa.pub)'" -k

案例

为web1安装Apache
并把监听端口改为8080
设置默认主页 hello world
启动服务,并设置为开机自启

- hosts: web1
  remote_user: root
  tasks:
        - name: install the latest version of Apache
          yum:
            name: httpd
            state: installed
        - lineinfile:
            path: /etc/httpd/conf/httpd.conf
            regexp: "^Listen"
            line: "Listen 8080"
        - shell: echo "hello world" > index.html
          args:
            chdir: /var/www/html
        - service:
            name: "httpd"
            enabled: yes
            state: started

为cache添加用户jj
把123456设置为默认密码,并使用密码过滤器
使该用户第一次登录强制修改密码

---
- hosts: cache
  remote_user: root
  vars:
    username: "jj"
  tasks:
    - user:
        name: "{{username}}"
        password: "{{'123456' |password_hash('sha512')}}"
    - shell: chage -d 0 "{{username}}"

密码过滤器:
password_hash(‘sha512’)


为web添加用户zhang3
并使用忽略错误,避免用户存在 停止脚本 //当返回值为1时,停止运行
默认密码为123123
使该用户第一次登录时强制修改密码

---
- hosts: web
  remote_user: root
  vars:
    username: "zhang3"
  tasks:
    - shell: useradd "{{username}}"
      ignore_errors: True
    - shell: echo 123123 |passwd --stdin "{{username}}"
    - shell: chage -d 0 "{{username}}"

为cache安装httpd
修改配置文件 把ServerName改为localhost
修改配置文件 把监听端口改为8080
设置默认网页 hello world
利用handlers 在配置Apache时自动重启

---
  - hosts: cache
    remote_user: root
    tasks:
      - name: install the latest version of Apache
        yum:
          name: httpd
          state: installed
        notify:
          - boot start
          - restart httpd
      - lineinfile:
          path: /etc/httpd/conf/httpd.conf
          regexp: "^Listen"
          line: "Listen 8080"
        notify:
          - restart httpd
      - lineinfile:
          path: /etc/httpd/conf/httpd.conf
          regexp: "^#ServerName"
          line: "ServerName localhost"
        notify:
          - restart httpd
      - shell: echo "hello world" > index.html
        args:
          chdir: /var/www/html
    handlers:
      - name: restart httpd
        service:
          name: httpd
          state: restarted
      - name: boot start
        service:
          name: httpd
          enabled: yes

循环添加多用户

---
  - hosts: db2
    remote_user: root
    tasks:
      - name: creater user
        user:
          name: "{{item.name}}"
          password: "{{item.pwd |password_hash('sha512')}}"
          group: "{{item.group}}"
        with_items:
          - { name:"nb",pwd:"aa",group:"a" }
          - { name:"dd",pwd:"bb",group:"b" }
          - { name:"cc",pwd:"cc",group:"c" }
          - { name:"xx",pwd:"dd",group:"d" }

把系统平均负载高于0.7的web服务器停掉

---
- hosts: web
  remote_user: root
  tasks:
    - shell: uptime | awk '{printf("%.2f",$(NF-2))}'
      register: result
    - service: name=httpd state=stopped
      when: result.stdout |float > 0.7
#追加 debug 调试信息
#   - name: Show debug info
#     debug: var=ooxx

~
“`

相关内容

    暂无相关文章