关注公众号获取更多学习资源

介绍

Ansible是一款简单的运维自动化工具,只需要使用ssh协议连接就可以来进行系统管理,自动化执行命令,部署等任务


Ansible的特点


  1. ansible不需要单独安装客户端,也不需要启动任何服务
  2. ansible是Python中的一套完整的自动化执行任务模块
  3. ansible playbook 采用yaml配置,对于自动化任务执行过一目了然


Ansible组成结构

  • Ansible

ansible是Ansible的命令工具,核心执行工具;一次性或临时执行的操作都是通过该命令执行。

  • Ansible Playbook

任务剧本(又称任务集),编排定义Ansible任务集的配置文件,由Ansible顺序依次执行,yaml格式。

  • Inventory

Ansible管理主机的清单,默认是/etc/ansible/hosts文件。

  • Modules

Ansible执行命令的功能模块,Ansible2.3版本为止,共有1039个模块。还可以自定义模块。

  • Plugins

插件,模块功能的补充,常有连接类型插件,循环插件,变量插件,过滤插件,插件功能用的较少。

  • API

提供给第三方程序调用的应用程序编程接口,提供一个功能强大,操作性强的Web管理界面和REST API接口



管理机环境要求

运行Ansible的服务器必须且只需要安装有 Python 2.7+ 或者 Python 3.5+。Red Hat, Debian, CentOS, macOS, 任一BSD系列的系统均可。但windows不能用于管理机。

选择管理机时,需要注意的时,网络条件越好越便于管理。比如:当你选择在云上使用 Ansible时,那么管理机和管理节点都在云上是最佳选择,连接外网的节点速度则会慢很多,也存在很大的安全风险。

安装

配置epel


wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum clean all
yum makecache


安装ansible

sudo yum install epel-release
sudo yum install ansible
ansible --version
ansible 2.9.25
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, Nov 16 2020, 22:23:17) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]


Ansible Inventory文件

Inventory文件通常用于定义要管理的主机的认证信息,例如ssh登录用户名、密码以及key相关信息。可以同时操作一个组的多台主机,组与主机组之间的关系都是通过inventory文件配置。配置文件路径为:/etc/ansible/hosts


Ansible基本使用

配置连接

基于密码连接


cat /etc/ansible/hosts
#主机+端口+密码
[test-k8s] #定义分组 webserver,可以定义多个分组
192.168.253.214 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass="123456"
192.168.253.215 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass="123456"
192.168.253.216 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass="123456"

Inventory内置参数

一文快速掌握Ansible自动化运维_centos



其他配置文件

/etc/ansible/ansible.cfg #主配置文件,配置ansible工作特性
/etc/ansible/hosts #主机清单 (将要连接操控的主机IP地址写在此配置文件的最下方)
/etc/ansible/roles/ #存放角色的目录


ansible相关命令


/usr/bin/ansible     #主程序,临时命令执行工具
/usr/bin/ansible-doc #查看配置文档,模块功能查看工具
/usr/bin/ansible-galaxy #下载/上传优秀代码或Roles模块的官网平台
/usr/bin/ansible-playbook #定制自动化任务,编排剧本工具/
/usr/bin/ansible-pull #远程执行命令的工具
/usr/bin/ansible-vault #文件加密工具
/usr/bin/ansible-console #基于Console界面与用户交互的执行工具

ansible命令格式


ansible <需要执行命令的目标主机或群组> <ansible命令选项,指定模块> <需要使用的模块,shell命令模块> <ansible命令选项,指定模块中要用到的参数> <模块中的参数(shell命令)>

配置ansible.cfg

vi /etc/ansible/ansible.cfg
host_key_checking = False #将这个参数注释去掉,表示不检测host key


测试ansible


#ansible test-k8s  -m ping  #操作test-k8s组下面的主机,-m指定执行ping模块
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.253.214 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.253.216 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.253.215 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}


Ansible常用模块

ansible-doc -l #列出ansible支持的模块
ansible-doc ping #查看模块帮助信息


远程命令模块

command模块

command 作为 Ansible 的默认模块,可以运行远程权限范围所有的 shell 命令,不支持管道符。




ansible test-k8s -m command -a "free -m"  #查看test-k8s分组主机内存使用情况
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.253.215 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 15866 3532 534 580 11799 11423
Swap: 0 0 0
192.168.253.216 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 15866 5479 803 639 9583 9417
Swap: 0 0 0
192.168.253.214 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 7802 3287 278 4 4236 4212
Swap: 0 0 0


shell模块

shell模块基本和command相同,但是shell支持管道符



ansible test-k8s -m shell -a "/data/script/test.sh"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.253.216 | CHANGED | rc=0 >>
sssss
192.168.253.215 | CHANGED | rc=0 >>
sssss
192.168.253.214 | CHANGED | rc=0 >>
sssss


copy模块

实现主控端向目标主机拷贝文件,类似于 scp 功能


#ansible test-k8s -m copy -a "src=/tmp/test-ansible dest=/tmp/ owner=root group=root mode=0755"
#ansible test-k8s -m command -a "ls /tmp/test-ansible -l"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.253.214 | CHANGED | rc=0 >>
-rwxr-xr-x 1 root root 0 12月 4 10:35 /tmp/test-ansible
192.168.253.216 | CHANGED | rc=0 >>
-rwxr-xr-x 1 root root 0 12月 4 10:35 /tmp/test-ansible
192.168.253.215 | CHANGED | rc=0 >>
-rwxr-xr-x 1 root root 0 12月 4 10:35 /tmp/test-ansible

stat模块

获取远程文件状态信息,atime/ctime/mtime/md5/uid/gid 等信息



ansible test-k8s -m stat -a "path=/tmp/test-ansible"


get_url模块

实现在远程主机下载指定 URL 到本地,支持 sha256sum 文件校验

#ansible test-k8s -m get_url -a "url=http://nginx.org/download/nginx-1.18.0.tar.gz dest=/tmp/ mode=0440 force=yes"
#ansible test-k8s -m command -a "ls /tmp/nginx-1.18.0.tar.gz"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.253.216 | CHANGED | rc=0 >>
/tmp/nginx-1.18.0.tar.gz
192.168.253.214 | CHANGED | rc=0 >>
/tmp/nginx-1.18.0.tar.gz
192.168.253.215 | CHANGED | rc=0 >>
/tmp/nginx-1.18.0.tar.gz


yum模块

软件包管理



ansible test-k8s -m yum -a "name=curl state=latest"


cron模块

远程主机crontab配置

#ansible test-k8s -m cron -a "name='list dirs' hour='6,3' job='ls -l'"
#效果
#crontab -l
#Ansible: list dirs
* 6,3 * * * ls -l


user模块


#添加用户
ansible test-k8s -m user -a "name=su comment='user su'"
#删除用户
ansible test-k8s -m user -a "name=su state=absent remove=yes"



Playbook

Playbooks 是 Ansible的配置,部署,编排语言.他们可以被描述为一个需要希望远程主机执行命令的方案,或者一组IT程序运行的命令集合,由一个或多个play组成的列表,play的主要功能在于将事先归并为一组的主机装扮成事先通过ansible中的task定义好的角色。从根本上来讲,所谓的task无非是调用ansible的一个module。将多个play组织在一个playbook中,即可以让它们联合起来按事先编排的机制完成某一任务.


Playbook核心元素


Hosts 执行的远程主机列表Tasks 任务集Varniables 内置变量或自定义变量在playbook中调用Templates 模板,即使用模板语法的文件,比如配置文件等Handlers 和notity结合使用,由特定条件触发的操作,满足条件方才执行,否则不执行tags 标签,指定某条任务执行,用于选择运行playbook中的部分代码。


Playbook语法


  • 连续的项目(即列表)用 -减号来表示,key/value(字典)用冒号:分隔
  • 以 --- (三个减号)开始,必须顶行写;
  • 次行开始写Playbook的内容,但是一般要求写明该playbook的功能
  • 缩进必须统一,不能空格和tab混用
  • 缩进级别必须是一致的,同样的缩进代表同样的级别,程序判别配置的级别是通过缩进结合换行来实现的;
  • K/V的值可同行写,也可换行写。同行使用 :分隔,换行写需要以 - 分隔;


示例:

cat copyfile.yaml
---
- hosts: test-k8s #定义需要执行的主机或主机组,已经在hosts文件定义好的
remote_user: root #在目标主机执行的用户
tasks: #定义任务的开始
- name: "copy file" #任务的名称
copy: src=/etc/passwd dest=/tmp/passwd #调用模块,具体要做的事情
notify: handlers test #指定要执行哪个handlers,名称对应下面handlers的name
handlers:
- name: handlers test #和notify名称要一样。
shell: echo "devops yunwei" >> /tmp/devops.txt #触发要执行的动作

说明: notify这边语法相当于shell的 && ,如果tasks执行失败,不会执行handlers


执行

ansible-playbook copyfile.yaml
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details


PLAY [test-k8s] *******************************************************************************************************************************************************************************************************


TASK [Gathering Facts] ************************************************************************************************************************************************************************************************
ok: [192.168.253.214]
ok: [192.168.253.215]
ok: [192.168.253.216]


TASK [copy file] ******************************************************************************************************************************************************************************************************
changed: [192.168.253.216]
changed: [192.168.253.214]
changed: [192.168.253.215]


RUNNING HANDLER [handlers test] ***************************************************************************************************************************************************************************************
changed: [192.168.253.214]
changed: [192.168.253.215]
changed: [192.168.253.216]


PLAY RECAP ************************************************************************************************************************************************************************************************************
192.168.253.214 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.253.215 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.253.216 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

验证

ansible test-k8s -m shell -a "ls /tmp/passwd"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.253.215 | CHANGED | rc=0 >>
/tmp/passwd
192.168.253.216 | CHANGED | rc=0 >>
/tmp/passwd
192.168.253.214 | CHANGED | rc=0 >>
/tmp/passwd
[root@test-ops-218 yaml]# ansible test-k8s -m shell -a "cat /tmp/devops.txt"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.253.215 | CHANGED | rc=0 >>
devops yunwei
192.168.253.214 | CHANGED | rc=0 >>
devops yunwei
192.168.253.216 | CHANGED | rc=0 >>
devops yunwei



Playbook变量

yaml文件中定义变量


#cat vars.yaml
---
- hosts: test-k8s
remote_user: root
vars:
pkg: devops.txt
tasks:
- name: delete devops.txt
shell: rm -f /tmp/{{ pkg }}
#ansible-playbook
#ansible test-k8s -m shell -a "ls /tmp/devops.txt"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.253.214 | FAILED | rc=2 >>
ls: 无法访问/tmp/devops.txt: 没有那个文件或目录non-zero return code
192.168.253.215 | FAILED | rc=2 >>
ls: 无法访问/tmp/devops.txt: 没有那个文件或目录non-zero return code
192.168.253.216 | FAILED | rc=2 >>
ls: 无法访问/tmp/devops.txt: 没有那个文件或目录non-zero return code


引用外部变量

在命令行使用--extra-vars参数赋值变量;

--extra_vars "变量名=变量值"

# cat extra_vars.yaml
---
- hosts: test-k8s
remote_user: root
tasks:
- name: create file
file:
path: /tmp/{{ filename }}
mode: 0644
state: touch
# ansible-playbook extra_vars.yaml --extra-vars "filename=temp.txt"
#ansible test-k8s -m shell -a "ls /tmp/temp.txt"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.253.215 | CHANGED | rc=0 >>
/tmp/temp.txt
192.168.253.214 | CHANGED | rc=0 >>
/tmp/temp.txt
192.168.253.216 | CHANGED | rc=0 >>
/tmp/temp.txt


inventory(资产)中定义的变量

也就是在/etc/ansible/hosts文件中定义的变量;


#cat /etc/ansible/hosts
[test-k8s:vars]
issue="hello k8s"
#cat vars.yaml
---
- hosts: test-k8s
remote_user: root
tasks:
- name: delete devops.txt
shell: echo {{ issue}} > /tmp/devops.txt
#ansible-playbook vars.yaml
#ansible test-k8s -m shell -a "cat /tmp/devops.txt"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.253.215 | CHANGED | rc=0 >>
hello k8s
192.168.253.216 | CHANGED | rc=0 >>
hello k8s
192.168.253.214 | CHANGED | rc=0 >>
hello k8s

注意:组变量定义时,不要落下关键字vars,[组名:vars]

playbook中引用{{ 变量名 }}即可。


tags

tags用于让用户选择运行playbook中的部分代码。

# cat tag.yaml
---
- hosts: test-k8s
remote_user: root
tasks:
- name: create file1
tags:
- file1
file:
path: /tmp/file1
mode: 0644
state: touch
- name: create file2
tags:
- file2 #给这个任务打标签
file:
path: /tmp/file2
mode: 0644
state: touch


#ansible-playbook tag.yaml --tags file2 # 选择file2这个标签执行
#ansible test-k8s -m shell -a "ls -l /tmp/file2"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.253.214 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 12月 4 15:30 /tmp/file2
192.168.253.215 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 12月 4 15:30 /tmp/file2
192.168.253.216 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 12月 4 15:30 /tmp/file2


Playbook的流程控制

when条件判断

当关键字when后面的条件满足时(也就是通过运算得到的结果为true时),才会执行当前任务。


#cat when.yaml
---
- hosts: test-k8s
remote_user: root
tasks:
- name: "touch centos 7 flag file"
command: "touch /tmp/this_is_{{ ansible_distribution }}_{{ ansible_distribution_major_version }}system"
when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == '7') #如果是centos系统,并且为7版本,执行上面代码
- name: "touch centos 6"
command: "touch /tmp/this_is_{{ ansible_distribution }}_{{ ansible_distribution_major_version }}system"
when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == '6') #如果是centos系统,并且是6版本,执行上面代码
#ansible-playbook when.yaml
#ansible test-k8s -m shell -a "ls /tmp/this_is_CentOS_7system -l"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
192.168.253.214 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 12月 4 15:43 /tmp/this_is_CentOS_7system
192.168.253.215 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 12月 4 15:43 /tmp/this_is_CentOS_7system
192.168.253.216 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 12月 4 15:43 /tmp/this_is_CentOS_7system

ansible_distributionansible_distribution_major_version都是是Facts变量,分别表示Linux发行版和版本号


循环语句

标准循环with_items


---
- name: when and with_items
hosts: load-node
remote_user: root
gather_facts: false
tasks:
- name: Create groups
group: name=testgroup6 state=present
ignore_errors: yes
register: excu_result
- name: Append excu_result to tmp.txt
shell: "echo {{ excu_result }} > /tmp/tmp.txt"
- name: Create some users
user: name={{ item }} group=testgroup6 state=present
when: excu_result|success
with_items:
- testuser1
- testuser2
- testuser3

说明:


  • gather_facts: false表示运行此playbook时不收集目标主机的系统信息。因为默认此项是开启的,每次运行playbook都会收集主机facts,这会影响playbook的运行速度。将gather_facts设为false即可关闭。
  • when:excu_result|success的意思为当变量excu_result执行结果为成功状态,则执行当前的任务。其中success为Ansible内部过滤器方法,返回True代表命令运行成功。还有excu_result|failed表示excu_result执行结果为失败状态;excu_result|skipped表示excu_result执行被跳过。
  • with_items的值还可以写成[testuser1, testuser2, testuser3]
  • register关键字定义一个变量,这个变量的值就是任务执行的输出结果
  • ignore_errors: yes 屏蔽当前任务的报错信息


更多文章请扫一扫

 扫描下面二维码关注公众号获取更多学习资源

一文快速掌握Ansible自动化运维_配置文件_02