Linux | 一小时入门ansible

前言:
方便自动化批量部署Linux服务器,Ansible通过ssh协议进行所有操作,无需安装client端,其幂等性使得多次执行也不会在远程服务器上造成重复操作。

简书
Ansible中文指南
Ansible Documentation

Architecture

      Ansible----------
      |               |       -----------------------Group
      |  -----------  |       |                          |
      | | Inventory | |       |                          |
      |  -----------  |    |--|->|Server1|Server2|Server3|
      |               |    |  |                          |
      | ------------- |    |  |                          |
      | |  Modules  | |    |  ----------------------------
      | ------------- |    |
PC--->|---------------|---->
      | ------------- |    |
      | |  Plugins  | |    |
      | ------------- |    |
      |               |    |
      | ------------- |    |---->ServerA ServerB ServerC
      | | Playbooks | |
      | ------------- |
      |               |
      -----------------

Core

组件功能
Ansible核心程序
Core Modules核心模块,所有任务均有模块完成
Host InventoryAnsible管理的主机信息,包括IP地址、SSH端口号、账号、密码等
Custom Modules自定义模块,完成核心模块无法完成的任务,支持任意语言编写
Playbooks“剧本”,YAML格式,模块化定义一些列任务,供外部同意调用
Connection Plugins连接插件,建立Ansible与其他主机间的通信

Install Ansible

  • 安装
yum install ansible
  • 卸载
yum remove ansible
  • 重要文件
# 配置文件,一般情况无需修改

/etc/ansible/ansible.cfg

# 主机清单,保存管理的主机的信息

/etc/ansible/hosts

# 公共角色

/etc/ansible/roles
  • 命令集
命令作用
ansible定义并运行简单任务
ansible-config查看、编辑、管理Ansible配置
ansible-doc文档查看工具
ansible-galaxy共享和下载roles的工具
ansible-inventory查看inventory信息
ansible-playbook执行playbook
ansible-pull从仓库中拉取playbooks
ansible-vault文件加解密工具
ansible-consoleREPL控制台执行Ansible任务

Inventory

  • 示例配置
118.25.36.248 ansible_ssh_pass=******
111.231.83.137 ansible_ssh_pass=******

[servers]
118.25.36.248
111.231.83.137

[servers:vars]
ansible_ssh_user=root
  • 主机
192.168.0.2

www.example.com

www[01:50].example.com

db-[a:f].example.com
  • 主机变量
主机 k1=v1 k2=v2...
[组名]
主机 k1=v1 k2=v2...
主机 k1=v1 k2=v2...
...
  • 组变量
[组名:vars]
k1=v1
k2=v2
...

初步体验

  • 实例:在指定主机上创建文件
ansible 118.25.36.248 -m copy -a "content='hello' dest=/root/hello.txt"
--------主机名或组--------模块-----------参数--------------------------
  • 查看所有模块
ansible-doc -l
https://docs.ansible.com/ansible/devel/modules/list_of_all_modules.html
  • 查看参数文档
ansible-doc -s copy
  • 幂等性
#同等的条件,一次请求和重复的多次请求对系统资源的影响是一致的

Modules

  • 默认模块:command
ansible servers -a "date"
  • 常用模块:
ping  command  shell  yum  service  pip  copy

user  group  get_url  file  template  unarchive ...
  • 示例:安装docker/配置加速镜像/启动
ansible servers -m yum -a "name=docker state=latest skip_broken=yes"

ansible servers -m copy -a "src=/etc/docker/daemon.json dest=/etc/docker/daemon.json"

ansible servers -m service -a "name=docker state=started enabled=yes"

Playbook

  • 编写playbook文件:docker.yml
---
- host: servers
  remote_user: root
  tasks:
  - name: ensure docker is at the latest version
    yum: name=docker state=latest skip_broken=yes
  - name: config docker daemon
    copy: src=/etc/docker/daemon.json dest=/etc/docker/daemon.json
    notify:
    - restart docker
  - name: ensure docker is running
     service: name=docker state=started
  handlers:
    - name: restart docker
      service: name=httpd state=restarted
#host:主机
#remote_user:用户
#task:任务
#name:任务名称
#notify:变更通知
#handlers:处理器 
  • 执行playbook
ansible-playbook docker.yml

Playbook Roles

  • 结构目录
|----roles                
|  |----docker            
|  |  |----defaults         
|  |  |----files            
|  |  |  └────daemon.json
|  |  |----handlers         
|  |  |----meta             
|  |  |----tasks
|  |  |  └────main.yml
|  |  |----templates        
|  |  └────vars             
|  |----mariadb
|  |  └────tasks
|  |    └────main.yml
|  └──mongo
|    └────tasks
|      └────main.yml
└────site.yml

- 剧本:site.yml
- 角色:docker、mongo、mariadb
-     普通文件:files
-     模板文件:templates
-     默认变量:defaults
-     其他变量:vars
-     元数据:meta
-     包含该角色要执行的任务列表:tasks
-     处理器,不仅该角色可以使用,其他角色也能使用:handlers
  • 编写剧本

    • site.yml
---
- hosts: 118.25.36.248
  roles:
   - docker
   - {role:mongo,port:27017}
   
- hosts: 111.231.83.137
  roles:
   - docker
   - {role:mariadb,port:3306}

#roles:使用角色
  • 创建角色

roles/docker/task/main.yml

- name: ensure docker os at latest version
  yum: name=docker state=latest skip_broken=yes
- name: config docker daemon
  copy: src=daemon.json dest=/etc/docker/daemon.json
  notify:
  - restart docker
- name: ensure docker is running
  service: name=docker state=started

​ roles/docker/handlers/main.yml

- name: restart docker
  service: name=http state=restarted

​ roles/docker/file/daemon.json

{
    "registry-mirrors": ["https://obww7jh1.mirror.aliyuncs.com"]
}

Playbook Variables

  • 定义变量

在Inventory中定义

tezign.com http_port=80

在Playbook中定义

---
- hosts: 118.25.36.248
  vars:
   port: 27017
  roles:
   - docker
   - mongo

在Role中定义

---
- hosts: 118.25.36.248
  roles:
   - docker
   - {role:mongon,port:27017}
  • 使用变量
- name: Run mongo container
  docker:
   name: mongo
   image: mongo:latest
   state: started
   ports:
   - "{{port}}: 27017"
   volumes:
   - mongo_data: /data/db

Playbook Template (Jinja2)

  • 编写模板
{
    "registry-mirrors": [{{mirror_url}}]
}
  • 使用模板
- name: coding docker daemon
  template: src=daemon.json.j2 dest=/etc/docker/daemon.json
  notify:
  - restart docker

Playbook Register Variables

  • 简单示例
- name: test play
  hosts: all
  tasks:
   - shell: cat /etc/docker/daemon.json
     register: daemon_contents
   - shell: echo "daemon contains the word aliyun"
     when: daemon_contents.stdout.find('aliyun')!=-1

#register:将任务执行的结果保存到变量,供后续任务使用

Playbook Loops

  • 简单示例
- name: add serveral users
  user:
   name: "{{item}}"
   state: present
   groups: "wheel"
  loop:
    - testuser1
    - testuser2
    
#loop:循环执行

等价于

- name: add user testuser1
  user:
   name: "testuser1"
   state: present
   groups: "wheel"
- name: add user testuser2
  user:
   name: "testuser2"
   state: present
   groups: "wheel"
  • List 对象
- name: add serveral users
  user:
   name: "{{item.name}}"
   state: present
   groups: "{{item.groups}}"
  loop:
   - {name:'testuser1',groups:'wheel'}
   - {name:'testuser1',groups:'root'}

Playbook Conditionals

  • 简单示例
tasks:
 - name: "shutdown CentOS 6 systems"
  command: /sbin/shutdown -t now
  when:
   - ansible_distribution == "CentOs"
   - ansible_distribution_major_version == "6"
   
# when:条件判断

Playbook Tags

  • 定义TAG
tasks:
 - name: "print date"
   command: date
   tags:
    - date
tasks:
 - name: "print date"
   command: date
   tags: [date,now]
roles:
 - {role:webserver,tags:['web','foo']}
  • 使用TAG
ansible-playbook test.yml --tags "date"
  • 跳过TAG
ansible-playbook test.yml --skip-tags "date,now"

本文链接:

https://blog.zhigu34.cn/archives/36.html
1 + 1 =
快来做第一个评论的人吧~