ansible学习笔记之——知识点整理,ansible学习笔记


相关命令

1.ansible-doc命令:获取模块列表,及模块使用格式;
ansible-doc -l :获取列表
ansible-doc -s module_name :获取指定模块的使用信息

2.ansible-vault
ansible-vault主要应用于配置文件中含有敏感信息,又不希望他能被人看到,vault可以帮你加密/解密这个配置文件

3.ansible-galaxy
下载第三方扩展模块

4.ansible-pull
The ansible-pull is a small script that will checkout a repo of configuration instructions from git, and then run ansible-playbook against that content.

5.ansible-playbook
执行playbook

ansible使用

ansible 命令格式

ansible [-f forks] [-m module_name] [-a args]

<host-pattern> 指明管控主机,以模式形式表示或者直接给定 IP ,必须事先定义在文件中; all 设置所有
[-f forks] 指明每批管控多少主机,默认为 5 个主机一批次
[-m module_name] 使用何种模块管理操作,所有的操作都需要通过模块来指定
[-a args] 指明模块专用参数; args 一般为 key=value 格式 注意:command模块(默认模块 )的参数非为kv格式,而是直接给出要执行的命令即可;

更多参数 ansible -h

一些常用模块

command模块 [执行远程命令]
shell模块 [执行远程主机的shell/python脚本]
script模块 [在远程主机执行主控端的shell/python脚本]
raw模块 [类似于command模块、支持管道传递]

#user

# ansible test -m user -a ‘name=mtest state=present system=true’

#crontab

# ansible test -m cron -a ‘name=”Time” state=present minute=”*/5” job=”/usr/sbin/ntpdate time.nist.gov”’

#file

# ansible test -m file -a ‘path=/tmp/test.txt state=touch mode=600 owner=mtest’

#copy template
Tips:Template可以把变量(vars)传过去(文件中)

# ansible test -m copy -a ‘src=/root/1 dest=/tmp/ owner=mtest mode=755’

#yum

# ansible test -m yum -a ‘name=httpd state=present’
ansible test -m yum -a ‘name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present’

#service

# ansible test -m service -a ‘name=httpd state=started enabled=yes’

#script

# ansible test -m script -a ‘/root/1.sh’

#setup 收集主机的系统信息

# ansible test -m setup –tree /tmp/facts #将所有主机的信息输入到/tmp/facts目录下

playbook 使用

playbooks 是 ansible 更强大的配置管理组件,实现基于文本文件编排执行的多个任务,且多次重复执行

(1) 核心元素
Tasks 任务、 Variables 变量、 Templates 模板、 Handlers 处理器、 Roles 角色

(2)playbooks 中 定义任务:
- name: task description 注释 描述信息
module_name: module_args 声明模块:定义 ansible 模块参数

 # vim 1.yml

- hosts: test
  remote_user: root
  gather_facts: False
  tasks:
       - name: install php
         yum: name=php state=present

# vim useradd.yml

- hosts: test
  remote_user: root
  gather_facts: False
  vars:
       username: ghosts
       password: 12345
  tasks:
       - name: add user
         user: name={{username}} state=present
       - name: set password
         shell: /bin/echo {{password}} | /usr/bin/passwd --stdin {{username}}

变量的重新赋值调用# ansible-playbook useradd.yml –extra-vars “username=ubuntu”

条件判断

- hosts: test
  remote_user: root
  #gather_facts: False(需要收集facts的信息时,必须开启)
  tasks:
       - name: install php
         yum: name=php state=present
         when: ansible_os_family == "Redhat"

迭代

- hosts: test
  remote_user: root
  gather_facts: False
  tasks:
       - name: add users
         user: name={{item}} state=present
         with_items:
                   - user1
                   - user2
- hosts: test
  remote_user: root
  gather_facts: False
  tasks:
       - name: add users
         user: name={{item.name}} state=present groups={{item.groups}}
         with_items:
                   - {name: 'user1',groups: 'root'}
                   - {name: 'user2',groups: 'ko'}

Handlers
handlers:也是task,但只有其关注的条件满足时,才会被触发执行
Handlers最佳的应用场景是用来重启服务,或者触发系统重启操作

- hosts: test
  remote_user: root
  gather_facts: False
  tasks:
       - name: install httpd
         yum: name=httpd state=present

       - name: install config file
         copy: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
         notify:                  # 如果copy执行完之后文件发送了变化,则执行
               - restart httpd      # 调用handler
         tags: conf

       - name: start httpd service
         service: name=httpd state=started

  handlers:
       - name: restart httpd
         service: name=httpd state=restarted

在 notify 中定义内容一定要和tasks中定义的 - name 内容一样,这样才能达到触发的效果,否则会不生效。
tags运行一部分内容 ansible-playbook -t conf web.yml

sudo
clien赋予sudo权限

# visudo

root    ALL=(ALL)       ALL
tyt     ALL=(ALL)       ALL

server

# vim /etc/ansible/hosts

[test]
192.168.182.130 ansible_sudo_pass=***

# vim msu.yml

- hosts: test
  remote_user: tyt
  gather_facts: False
  tasks:
       - name: httpd start
         service: name=httpd state=started
         sudo: yes

获取执行命令的输出结果(用于判断) –Register

- hosts: test
  remote_user: root
  gather_facts: False
  tasks:
       - name: echo date
         command: date
         register: date_output
       - name: echo date_output
         command: echo "14"
         when: date_output.stdout.split(' ')[2] == '14'                                                          

使用delegate_to关键字便可以配置任务在其他机器上执行.其他模块还是在所有配置的管理机器上运行的,当到了这个关键字的任务就是使用委托的机器上运行.而facts还是适用于当前的host

  - name: Fetch configuration from all webservers
    hosts: webservers
    tasks:
      - name: Get config
        get_url: dest=configs/{{ ansible_hostname }} force=yes url=http://{{ ansible_hostname }}/diagnostic/config
        delegate_to: test

本地操作功能 –local_action ,转给本地

- hosts: test
  remote_user: root
  gather_facts: False
  tasks:
       - name: add host
         local_action: shell echo "192.168.182.130 www.nginx4.com" >> /etc/hosts

# vim /etc/ansible/hosts

[test]
192.168.182.130

ansilbe自1.2版本引入的新特性,用于层次性、结构化地组织playbook。roles能够根据层次型结构自动装载变量文件、tasks以及handlers等。要使用roles只需要在playbook中使用include指令即可。简单来讲,roles就是通过分别将变量、文件、任务、模块及处理器放置于单独的目录中,并可以便捷地include它们的一种机制。角色一般用于基于主机构建服务的场景中,但也可以是用于构建守护进程等场景中。
1、创建role的步骤
①创建以roles命名的目录;
②在roles目录中分别创建以各角色名称命名的目录,如webservers、dbservers等;
③在每个角色命名的目录中分别创建files、handlers、meta、tasks、templates和vars目录;用不到的目录可以创建为空目录,也可以不创建;
④在playbook文件中,调用各角色;
2、role内各目录中可用的文件
tasks目录:至少应该包含一个名为main.yml的文件,其定义了此角色的任务列表;此文件可以使用include包含其它的位于此目录中的task文件;
files目录:存放由copy或script等模块调用的静态文件;
templates目录:template模块会自动在此目录中寻找Jinja2模板文件;
handlers目录:此目录中应当包含一个main.yml文件,用于定义此角色用到的各handler;此文件可以使用include包含其它的位于此目录中的handler文件;
vars目录:至少有一个main.yml文件,用于定义此角色用到的变量;
meta目录:至少有一个main.yml文件,用于定义此角色的特殊设定及其依赖关系;ansible 1.3及其以后的版本才支持;
default目录:为当前角色设定默认变量时使用此目录;应当包含一个main.yml文件;

ansible-playbook参数:
–check模式,仅检测,但不实行
–diff 内容变更对比
–synctax-check 检测一下语法是否有问题
become 的使用,当需要执行某些特殊操作需要专门权限时,可以用become_user那强调切换

host inventory

ansible基于ssh连接inventory中指定的远程主机时还可以通过参数指定其交互方式常用的参数如下所示
ansible_ssh_host # 要连接的主机名
ansible_ssh_port # 端口号默认是22
ansible_ssh_user # ssh连接时默认使用的用户名
ansible_ssh_pass # ssh连接时的密码
ansible_sudo_pass # 使用sudo连接用户是的密码
ansible_ssh_private_key_file # 秘钥文件如果不想使用ssh-agent管理时可以使用此选项
ansible_shell_type # shell的类型默认sh

Dynamic Inventory指通过外部脚本获取主机列表,并按照ansible 所要求的格式返回给ansilbe命令的。这部分一般会结合CMDB资管系统、zabbix 监控系统、crobble安装系统、云计算平台等获取主机信息。(Ansible在接受脚本动态获取主机信息时支持的是json格式)

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
hostlip = ['192.168.182.130','192.168.182.129']
group = 'mserver'
hostdata = {group:{"hosts":hostlip}}
#hostdata = {group:host1ip}
print json.dumps(hostdata,indent=4)

Ansible调用

# ansible -i muser.py mserver -m command -a ‘uptime’

api

Ansible-api

#!/usr/bin/env python
# -*- coding=utf-8 -*-

import ansible.runner
import json

runner = ansible.runner.Runner(
    module_name='ping',
    module_args='',
    pattern='test',
    forks=5
)

datastructure = runner.run()
data = json.dumps(datastructure,indent=4)
print data

相关内容

    暂无相关文章