运维自动化之Ansible进阶Playbook使用指南

每个playbook被称为一个剧本,其中的一系列任务称为戏剧(play)。

yaml 语法

多行缩进
连续项目通过减号 - 表示,列表 []
map结构的key/value用冒号分隔 {}
字符串不一定要用双引号标识
文档开始 ---
选择性符号 ... 可用来表示文档结尾
#表示注释

yaml教程:http://www.ruanyifeng.com/blog/2016/07/yaml.html?f=tt

实例解析

一个简单的apache部署脚本:


#!/bin/bash
yum install --quiet -y httpd httpd-devel
cp /root/httpd.conf /etc/httpd/conf/httpd.conf
systemctl start httpd
systemctl enable httpd

转换为playbook书写:

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

  tasks:
    - name: "install httpd"
      command: yum install --quiet -y httpd httpd-devel
    - name: 复制配置文件
      command: cp /root/httpd.conf /etc/httpd/conf/httpd.conf
    - name: 启动服务
      command: systemctl enable httpd  # 这条将不会执行
      command: systemctl start httpd

注意:一个play下只能有一个command 若存在多条,则只有最后一条生效。

对 playbook 进行优化,使用yum、copy、service模块

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

  tasks:
    - name: "install httpd"
      yum: 
        name:
          - httpd
          - httpd-devel
        state: present
    - name: 复制配置文件
      copy:
        src: "{{ item.src }}"
        dest: "{{ item.dest }}"
        owner: root
        group: root
        mode: 0644
      with_items:
        - {
            src: "/root/httpd.conf",
            dest: "/etc/httpd/conf/httpd.conf" }
        - {
            src: "/root/packages",
            dest: "/etc/httpd/conf/packages" }
    - name: 启动服务
      service: name=httpd state=started enabled=yes

当重复执行一个playbook时,当发现系统现有状态与playbook所定义要实现的状态一致时,会自动跳过该操作。

检查 playbook

[root@ansible-centos7-shanghai-area0 anaible ]# ansible-playbook test.yaml -C # 显示每步的执行情况 但不真执行
[root@ansible-centos7-shanghai-area0 anaible ]# ansible-playbook test.yaml --check 

playbook 实用技巧

1、限定执行范围
--limit
不修改playbook中定义的hosts,限定执行的主机
ansible-playbook test.yaml -C --limit 192.168.122.103   #假如 hosts: all
###
--list-hosts
不执行 仅显示受影响的主机
ansible-playbook test.yaml --list-hosts

2、用户与权限设置
--remote-user
该项目在playbook中设置
设置用于ssh连接的用户,不设置默认为当前系统用户
###
--ask-sudo-pass  废弃
传递sudo密码到远程主机
###
--ask-become-pass -K
传递权限密码
###
--become -b
运行命令的用户,默认为root 可通过 --become-user 指定用户

3、playbook其他参数
--inventory=Path -i Path 指定inventory文件
--verbose -v 显示详细输出 -vvvv 显示精确到每分钟的输出
--extra-vars=Vars -e Vars 定义playbook使用的变量,格式为 "key=value,key=value"
--forks=num -f num 并发任务数
--connection=Type -c Type 连接远程主机的方式,默认ssh 设置为local时,只在本地执行
--check -C 检测模式不执行
--syntax-check 检查语法

ansible-playbook dddd.yaml -k -K --become-method=su
-k --ask-pass 是SSH连接密码
-K --ask-become-pass 提权密码 sudo方式为连接帐户密码 su方式为root密码
--become-method=su  指定提权方式
-b, --become
--become-user=BECOME_USER

注意,如果用sudo模式提权,要求该用户在sudoers文件中,否则会报错:xxx is not in the sudoers file. This incident will be reported.

解决办法:使用su模式 或添加用户权限,visudo 添加 xxx ALL=(ALL) ALL解决办法是:使用su模式 或添加用户权限,visudo 添加 xxx ALL=(ALL) ALL

上一篇
下一篇