ansible笔记,


自动化运维工具

  • Puppet
    • Ruby开发,c/s架构,扩展性强,基于SSL认证
    • 远程命令执行相对较弱
  • SaltStack
    • Python开发,c/s架构,轻量级
    • 配置语法YAML
  • Ansible

    • Python开发,使用paramiko模块,分布式,无需客户端,轻量级
    • 配置语法YAML
    • 更强的远程命令执行功能
  • git源码

  • 英文手册
  • 中文手册

ansible特性

  • 相比puppet和SaltStack,无需客户端,更轻量级
  • 不需启动服务,仅仅是一个工具
  • 一套框架,使用不同的模块和插件
  • 更强的远程命令执行操作
  • 核心能力:使用yaml定制playbook
  • 丰富内置模块
  • API接口

应用

  • 自动化应用部署、配置
  • 持续交付、无宕机更新
  • 自动扩缩容
  • Tower:ansible web管理界面

ansible架构

ansible模块

  • 核心:ansible
  • 核心模块:core modules
  • 扩展模块:custom modules
  • 插件:plugins
  • 剧本:playbooks
  • 连接插件:connectior plugins
  • 主机群:Host Inventory

ansible工作原理

push推送

  • ansible将任务以临时文件或命令的形式传输到远程客户端执行并返回结果,结束后删除临时文件

ansible远程连接发展变化

  • paramiko
  • OpenSSH
  • 加速模式
    • python-keyczar包
    • accelerate: true
    • accelerate_port: 5099

ansible角色

  • 管理节点
    • 安装了 Python 2.6 或 Python 2.7都可以运行Ansible(windows系统不可以做控制主机)
  • 托管节点
    • 安装了 Python 2.6 或 Python 2.7
  • ansible默认使用SSH管理远程节点

ansible应用场景

  • 所有操作从运维角度划分
    • 文件传输
    • 命令执行
  • 所有操作从自动化工作类型角度划分
    • 应用部署
    • 配置管理
    • 任务流编排

ansible 安装

#pip安装
yum -y install gcc glibc-devel zlib-devel openssl-devel
yum -y install python-pip python-devel
pip install --upgrade pip
pip install ansible --upgrade
#yum安装
#配置epel源
yum -y install ansible 
#直接从源码安装运行
git clone git://github.com/ansible/ansible.git --recursive
cd ./ansible 
source ./hacking/env-setup
sudo easy_install pip
sudo pip install paramiko PyYAML Jinja2 httplib2
sudo make install
#ansible升级
git pull --rebase
git submodule update --init --recursive
  • 使用源码自己打包rpm
git clone git://github.com/ansible/ansible.git
cd ./ansible
make rpm
sudo rpm -Uvh ~/rpmbuild/ansible-*.noarch.rpm

Python多环境扩展管理

ansible目录结构

/etc/ansible 配置文件目录
/usr/bin/ansible 执行文件
/usr/lib/python2.7/site-packages/ansible lib库文件
/usr/share/doc/ansible-2.5.2 help文档
/usr/share/man/man1/ansible-config.1.gz man文档

ansible读取配置文件顺序

  • 命令执行目录
  • ~/.ansible.cfg
  • /etc/ansible/ansible.cfg

ansible 配置

  • 全局配置
    • /etc/ansible/ansible.cfg
  • 托管主机配置
    • /etc/ansible/hosts
[test]
192.168.204.101

[test2]
192.168.204.101:40000

[test3]
192.168.204.101 ansible_connection=ssh ansible_ssh_user=cy
  • 配置SSH-Key
-以SSH登录过程区分Client/Server
    - Client:192.168.204.100
    - Server:192.168.204.101
    - Server:修改SSH服务配置
        egrep -i "RSAAuthentication|PubkeyAuthentication|AuthorizedKeysFile|StrictModes|dns" /etc/ssh/sshd_config  
        sed -i 's/#StrictModes yes/StrictModes no/g' /etc/ssh/sshd_config 
        sed -i 's/#RSAAuthentication yes/RSAAuthentication yes/g' /etc/ssh/sshd_config 
        sed -i 's/#PubkeyAuthentication yes/PubkeyAuthentication yes/g' /etc/ssh/sshd_config 
        sed -i 's/#UseDNS yes/UseDNS no/g' /etc/ssh/sshd_config 
    - Client:生成公钥并加入到Server中
        - ssh-keygen -t rsa
        - ssh-copy-id -i id_rsa.pub root@192.168.204.101
        - ssh-copy-id -i id_rsa.pub cy@192.168.204.101 

主机清单inventory

/etc/ansible/hosts

badwolf.example.com:5309 指定 SSH 端口 5309
jumper ansible_ssh_port=5555 ansible_ssh_host=192.168.1.50 设置主机别名为 jumper
www[01:50].example.com 支持通配符匹配 www01 www02 ...www50
[databases]
db-[a:f].example.com 支持字母匹配 a b c...f
  • 可以设置主机变量和组变量
  • hosts和group变量目录结构
/etc/ansible/host_vars/all #host_vars 目录用于存放 host 变量,all 文件对所有主机有效
/etc/ansible/group_vars/all #group_vars 目录用于存放 group 变量,all 文件对所有组有效
/etc/ansible/host_vars/foosball #文件 foosball 要和 hosts 里面定义的主机名一样,表示只对 foosball 主机有效
/etc/ansible/group_vars/raleigh #文件 raleigh 要和 hosts 里面定义的组名一样,表示对raleigh 组下的所有主机有效
  • hosts文件支持的常用指令
ansible_ssh_host:主机地址
ansible_ssh_port:主机端口
ansible_ssh_user:ssh用户名
ansible_ssh_pass:ssh密码
ansible_sudo_pass:sudo密码
ansible_sudo_exe:sudo路径
ansible_connection:连接类型
ansible_ssh_private_key_file:私钥文件路径
ansible_shell_type:shell类型
ansible_python_interpreter:python解释器路径

主机通配模式

ansible webservers -m ping 操作hosts文件中webservers组的所有主机
ansible all -m ping 操作hosts文件中的所有主机
ansible * -m ping 操作hosts文件中的所有主机
ansible 192.168.1.* -m ping 通配符,操作hosts文件中的所有192.168.1.0网段主机

ansible webservers:dbservers -m ping 操作hosts文件中webservers组或dbservers组的主机
ansible webservers:!dbservers -m ping 操作hosts文件中在webservers组且不在dbservers组的主机
ansible webservers:&dbservers -m ping 操作hosts文件中同时在webservers组和dbservers组的主机
ansible webservers:dbservers:&staging:!phoenix -m ping 操作hosts文件中在webservers组或dbservers组,必须还存在于 staging 组中,但是不在 phoenix 组中的主机

ansible-playbook -e webservers:!{{excluded}}:&{{required}} 

ansible webservers1[0] -m ping 操作hosts文件中在webservers1组中的第一个主机
ansible webservers1[0-25] -m ping 操作hosts文件中在webservers1组中的第一个到第26个主机

ansible ~(web|db).*\.example\.com -m ping ~开头,正则表达式匹配主机

ansible-playbook site.yml --limit datacenter2 排除主机datacenter2
ansible-playbook site.yml --limit @retry_hosts.txt 排除retry_hosts.txt文件中的主机

yaml格式

--- #YAML 格式要求
ntp_server: acme.example.org #变量名:变量值
database_server: storage.example.org

ansible 执行模式

  • ad_hoc模式
  • playbook模式

ansible用法

  • ansible -i 主机 -m 模块名 -a ‘模块参数’ ansible其他参数
    • -i 主机配置;默认/etc/ansible/hosts配置,也可以使用all,对所有主机执行
    • -m 模块名;不指定时默认command,默认模块可以在/etc/ansible/ansible.cfg中修改,ansible-doc -l显示所有模块
    • -a 模块参数;ansible-doc 模块名,可以显示模块参数
    • ansible其他参数;
1.托管节点系统重装后,SSH登录会提示输入密码
可以在ansible.cfg中配置
[defaults]
host_key_checking=False
2.在使用 paramiko 模式时,主机 keys 的检查会很慢
3.默认情况下Ansible会记录一些模块的参数等信息到每个被控端的syslog日志文件里,除非在任务或者剧本里设置了 no_log: True 会不记录日志
- u 用户名;使用该用户名登录远程主机,默认使用当前用户,该用户必须在远程主机存在,ansible.cfg中可配置
- U 用户名;sudo到哪个用户,默认root
- k ;提示输入SSH密码
- K;提示sudo密码,当未配置NOPASSWD时使用
- s;sudo运行
- S;使用su命令
- l;显示所支持的所有模块 ?
- s;指定模块显示剧本片段 ?
- f;并行任务数,默认5
—private-key=PRIVATE_KEY_FILE;私钥路径,使用这个文件来验证连接
-v;详细信息
-M MODULE_PATH;要执行的模块的路径,默认为/usr/share/ansible/
—list-hosts;只打印有哪些主机会执行这个 playbook 文件,不是实际执行该 playbook 文件
-o;压缩输出,摘要输出.尝试一切都在一行上输出
-t Directory;将内容保存在该输出目录,结果保存在一个文件中在每台主机上
-B;后台运行超时时间
-P  调查后台程序时间
-T Seconds, —timeout=Seconds 时间,单位秒s
-P NUM, —poll=NUM 调查背景工作每隔数秒
-c Connection,  —connection=Connection 连接类型使用。可能的选项是paramiko(SSH),SSH和地方。当地主要是用于crontab或启动
—tags=TAGS  只执行指定标签的任务 例子:ansible-playbook test.yml –tags=copy 只执行标签为copy的那个任务
—list-tasks 列出所有将被执行的任务
-C, —check 只是测试一下会改变什么内容,不会真正去执行;相反,试图预测一些可能发生的变化
—syntax-check   执行语法检查的剧本,但不执行它
-l SUBSET,  —limit=SUBSET 进一步限制所选主机/组模式 –limit=192.168.0.15 只对这个ip执行
—skip-tags=SKIP_TAGS    只运行戏剧和任务不匹配这些值的标签 —skip-tags=copy_start
-e EXTRA_VARS,  —extra-vars=EXTRA_VARS 额外的变量设置为键=值或YAML / JSON
-l  —limit 对指定的 主机/组 执行任务 —limit=192.168.0.10192.168.0.11 或 -l 192.168.0.10192.168.0.11 只对这个2个ip执行任务
-v
-vvv
-vvvv

ansible常用模块操作

  • 并行性和shell命令
ansible altanta -a "/sbin/reboot" -f 10 重启 altanta 主机组的所有机器,每次重启 10 台
ansible altanta -a "/usr/bin/foo" -u geekwolf 以 geekwolf 用户身份在 atlanta 组的所有主机运行 foo 命令
ansible atlanta -a "/usr/bin/foo" -u geekwolf --sudo 以 geekwolf 用户身份 sudo 执行命令 foo
ansible atlanta -a "/usr/bin/foo" -u username -U otheruser  sudo 到其他用户执行命令非 root指令
ansible raleigh -m shell -a 'echo $TERM' 使用 shell 模块在远程主机执行命令,未指定时默认使用command模块,不支持变量和管道
  • 文件传输
ansible altanta -m copy -a "src=/etc/hosts dest=/tmp/hosts" 拷贝本地的/etc/hosts 文件到 atlanta 主机组所有主机的/tmp/hosts
ansible altanta -m file -a "dest=/srv/foo/a.txt mode=600" file 模块更改文件的用户及权限
ansible altanta -m file -a "dest=/srv/foo/b.txt owner=test group=test" file 模块更改文件的用户及权限
ansible altanta -m file -a "dest=/path/to/c mode=755 owner=mdehaan group=mdehaan state=directory" 创建目录
ansible webservers -m file -a "dest=/path/to/c state=absent" 删除文件或目录
  • 软件包管理
  • 用户和用户组
ansible all -m user -a "name=foo password=<>" 新增、修改用户
ansible all -m user -a "name=foo state=absent" 删除用户
mkpasswd --method=
  • 源码部署
ansible webserver2 -m git -a "repo=https://github.com/Icinga/icinga2.git dest=/tmp/myapp version=HEAD"
  • 服务管理
ansible webservers -m service -a "name=httpd state=started" 启动httpd服务
ansible webservers -m service -a "name=httpd state=restarted" 重启httpd服务
ansible webservers -m service -a "name=httpd state=stopped" 关闭httpd服务
  • 后台运行
ansible all -B 3600 -a "/usr/bin/long_running_operation --do-stuff" 后台执行命令 3600s,-B 表示后台执行的时间
ansible all -m async_status -a "jid=123456789" 检查任务的状态
ansible all -B 1800 -P 60 -a "/usr/bin/long_running_operation --do-stuff" 后台执行命令最大时间是 1800s 即 30 分钟,-P60s 检查下状态默认 15s
  • 收集系统信息
ansible all -m setup 搜集主机的所有系统信息
ansible all -m setup --tree /tmp/facts 搜集系统信息并以主机名为文件名分别保存在/tmp/facts 目录
ansible all -m setup -a 'filter=ansible_*_mb' 搜集和内存相关的信息
ansible all -m setup -a 'filter=ansible_eth[0-2]' 搜集网卡信息

ansible对windows的支持

  • 管理主机
    • 安装pywinrm模块
#/etc/ansible/hosts
[win2]
192.168.0.8
#  /etc/ansible/group_vars/win2.yml
ansible_ssh_user: Administrator
ansible_ssh_pass: --
ansible_ssh_port: 5986
ansible_connection: winrm
  • 托管主机
    • 安装powershell
    • 将端口 5985(HTTP)、5986(HTTPS)受限给 Ansible 控制端访问
    • get-executionpolicy
    • set-executionpolicy remotesigned
  • 支持windows的ansible模块列表
win_feature : 安装和卸载功能
win_get_url : 从给定的 url 下载文件
win_group : 添加和删除本地组
win_msi : 安装和卸载 MSI 文件
win_ping : windows 版本的 ping 模块
win_service : 管理 windows 服务
win_stat : 返回关于 windows 文件的信息
win_user : 管理本地账号

ansible win2 -m win_user -a "name=bob password=Password12345" 添加用户 bob 及密码

playbook详解

  • yaml语法
  • playbook组成
    • Target section 要执行playbook的远程主机
    • Variable section 运行时需要使用的变量
    • Task section 要在远程主机上执行的任务列表
    • Handler section 执行完task后需要调用的任务
---
- hosts: webservers
  vars:
    http_port: 80
    max_client: 200
  remote_user: root
  tasks:
  - name: ensure apache is at the latest version
    yum: pkg=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 
  • 主机和用户
---
- hosts: webservers
    remote_user: root
    sudo: yes
    sudo_user: test
    tasks:
        - name: test
        ping:
        remote_user:yourname
  • 任务列表
---
- hosts: server
    tasks:
    - name: test1
        copy: src=/etc/ansible/hosts dest=/tmp/hosts 
              owner=root group=root mode=0644
    - name: test2
        shell: /usr/bin/echo
        ignore_errors: True
    - name: make sure apache is running
        service: name=httpd state=running
    - name: disabled selinux
        command: /sbin/setenforce 0
  • 变量的使用
    • 有效的变量名;字母数字下划线,字母开头
    • 在inventory中定义变量
    • 在playbook中定义变量
    • 从角色和文件包中定义变量
    • 使用变量Jinja2
      • 模板中
        • My amp goes to {{ max_amp_value }}
      • playbook中
        • template: src=foo.cfg.j2 dest={{ remote_install_path }}/foo.cfg
    • Jinja2过滤器
        -
  • 变量文件分离
---
- hosts: all
  remote_user: root
  vars:
    favcolor: blue
  vars_files:
    - /vars/external_vars.ymal
  tasks:
  - name: this is just a placeholder
    command: /bin/echo foo

# /vars/external_vars.yml
somevar: somevalue
password: magic
  • 通过命令行传递变量
---
- hosts: '{{ hosts }}'
  remote_user: '{{ user }}'
  tasks:
    - ...

ansible-playbook test.yml --extra-vars "hosts=vipers user=test"
ansible-playbook test.yml --extra-vars '{"pacman":"mrs","ghosts":["inky","pinky","clyde","sue"]}'
ansible-playbook test.yml --extra-vars "@some_file.json"
  • 变量优先级
    • extra vars(命令中-e)最优先
    • inventory 主机清单中连接变量(ansible_ssh_user 等)
    • play 中 vars、vars_files 等
    • 剩余的在 inventory 中定义的变量
    • 系统的 facts 变量
    • 角色定义的默认变量(roles/rolesname/defaults/main.yml)
    • PS:子组会覆盖父组,主机总是覆盖组定义的变量
  • 变量使用总结
    • 定义在hosts和group变量中
    • 在playbook中指定
    • 任意指定变量文件
    • 交互方式获取变量值
    • 获取setup模块的变量

条件判断与循环

  • 条件判断
    • when条件判断
  • 循环
    • 标准循环with_items
    • 嵌套循环with_nested

Notify和Handlers

- 在 playbook 中,notify 行为在每个任务执行的最后会被触发调用 handlers
- 即使 notify 多个任务也只是被触发一次
- handlers 是任务列表和普通任务没有区别
- 通过 notify 触发使用 name 来引用
- 在一个 play 里面无论对一个 handlers 通知调用多少次,都只是在所有任务执行完后执行一次

角色和包含

  • 任务包含文件并且复用
  • 角色
site.yml
webservers.yml
fooservers.yml
roles/
     common/
            files/
            templates/
            tasks/
            handlers/
            vars/
            defaults/
            meta/
     webservers/
            files/
            templates/
            tasks/
            handlers/
            vars/
            defaults/
            meta/
  • 在角色中嵌入模块

运行playbook

  • ansible-playbook playbook.yml -f 10
  • ansible-playbook playbook.yml –verbose
  • ansible-playbook playbook.yml –list-hosts
  • ansible-playbook playbook.yml –list-tasks

playbook高级特性

相关内容

    暂无相关文章