在本文中,我们将详细介绍Centos7安装配置ansible运维自动化工具的各个方面,并为您提供关于centos7ansible的相关解答,同时,我们也将为您带来关于ansible自动化运维工具9(a
在本文中,我们将详细介绍Centos7安装配置ansible运维自动化工具的各个方面,并为您提供关于centos7 ansible的相关解答,同时,我们也将为您带来关于ansible 自动化运维工具 9 (ansible角色的安装及使用)、Ansible 运维自动化、Ansible 运维自动化 ( 配置管理工具 )、Ansible运维自动化的有用知识。
本文目录一览:- Centos7安装配置ansible运维自动化工具(centos7 ansible)
- ansible 自动化运维工具 9 (ansible角色的安装及使用)
- Ansible 运维自动化
- Ansible 运维自动化 ( 配置管理工具 )
- Ansible运维自动化
Centos7安装配置ansible运维自动化工具(centos7 ansible)
准备至少两台机器 Centos7,这两台机器都关闭 selinux
IP:106.13.118.132 服务端(ansible) master
IP:148.70.60.244 节点 slaver
服务端:
1、Ansible仓库默认不在yum仓库中,因此我们需要使用下面的命令启用epel仓库
[root@master tools]# yum install -y epel-release
2、安装ansible
[root@master tools]# yum install -y ansible
3、查看ansible版本:
[root@master tools]# ansible --version
ansible 2.7.10
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, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]
4、使用ssh-keygen生成公钥
[root@master tools]# ssh-keygen -P ''''
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:OAgDBVATJg64cL++LrvxVbxYyFDp0joX0eps5mpd2ME root@master
The key''s randomart image is:
+---[RSA 2048]----+
|O+*. .o |
|++ . .o . |
| oo .o + |
|o .o .o+=oE |
|.. ..oo=S++. |
| . +.B+o. |
| . Oo.. |
| .oo.o |
| o*+. |
+----[SHA256]-----+
[root@master tools]# systemctl stop firewalld.service
5、使用ssh-copy-id命令来复制ansible公钥的公钥到节点中,实现无秘钥执行命令
[root@master tools]# ssh-copy-id -i root@148.70.60.244
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host ''148.70.60.244 (148.70.60.244)'' can''t be established.
ECDSA key fingerprint is SHA256:EXMPsKuf0hIIw0Ena8RDnYjm99CoYSqWzX9Nzw0OpxE.
ECDSA key fingerprint is MD5:0f:3b:7f:30:e7:0e:12:83:ea:4c:be:b1:d9:03:57:ef.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted Now it is to install the new keys
root@148.70.60.244''s password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh ''root@148.70.60.244''"
and check to make sure that only the key(s) you wanted were added.
6、输入正确的节点登录密码,测试是否无需密码登录节点
[root@master tools]# ssh root@148.70.60.244
Last login: Thu Apr 25 15:29:42 2019 from 211.137.135.200
7、ctrl+d 退出 服务端 在ansible节点上添加可控制节点,/etc/ansible/hosts ansible的配置文件相对于简单所定义主机可以在webservers中定义节点ip
[root@master tools]# vim /etc/ansible/hosts
[testservers]
148.70.60.244
8、保存退出无需重启服务,测试是否成功
[root@master tools]# ansible -m ping ''testservers''
148.70.60.244 | SUCCESS => {
"changed": false,
"ping": "pong"
}
ansible 服务端执行命令:
[root@master tools]# ansible -m command -a "uptime" ''testservers''
148.70.60.244 | CHANGED | rc=0 >>
16:24:02 up 59 min, 2 users, load average: 0.24, 0.06, 0.06
[root@master tools]# ansible -m command -a "uname -r" ''testservers''
148.70.60.244 | CHANGED | rc=0 >>
3.10.0-514.26.2.el7.x86_64
[root@master tools]#
[root@master tools]# ansible -m command -a "yum install -y telnet*" ''testservers''
9、节点:
[root@slaver tools]# yum install -y epel-release
[root@slaver tools]# yum install -y ansible
[root@slaver tools]# ansible --version
ansible 2.7.10
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 6 2016, 00:28:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)]
[root@slaver tools]# systemctl stop firewalld.service
节点侧验证 Telnet:
[root@slaver tools]# telnet 106.13.118.132 22
Trying 106.13.118.132...
Connected to 106.13.118.132.
Escape character is ''^]''.
SSH-2.0-OpenSSH_7.4
总结
以上是小编为你收集整理的Centos7安装配置ansible运维自动化工具全部内容。
如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。
原文地址:https://www.cnblogs.com/zhangkaimin/p/10769264.html
ansible 自动化运维工具 9 (ansible角色的安装及使用)
目录
- 一、ansible 角色简介
- 1.roles目录结构
- 2.ansible 角色的创建
- 二、ansible角色的使用
- 1.书写task主任务
- 2.触发器模块
- 3.变量模块
- 三、习题测试
- 1.创建角色apache
- 2.设置变量
- 3.设置j2模板
- 4.设置task任务
- 5.设置触发器
- 6.设置执行任务
- 四、控制任务的执行顺序
- 五、多重角色的使用
一、ansible 角色简介
(1)Ansible roles 是为了层次化,结构化的组织Playbook。
(2)roles就是通过分别将变量、文件、任务、模块及处理器放置于单独的目录中,并可以便捷地include它们;
(3)roles一般用于基于主机构建服务的场景中,在企业复杂业务场景中应用的频率很高;
(4)以特定的层级目录结构进行组织的tasks、variables、handlers、templates、files等;相当于函数的调用把各个功能切割成片段来执行。
1.roles目录结构
参数 | 含义 |
---|---|
files 存放copy或script等模块调用的函数 | |
tasks | 定义各种task,要有main.yml,其他文件include包含调用 |
handlers | 定义各种handlers,要有main.yml,其他文件include包含调用 |
vars | 定义variables,要有main.yml,其他文件include包含调用 |
templates | 存储由template模块调用的模板文本 |
Meta | 定义当前角色的特殊设定及其依赖关系,要有main.yml的文件 |
defaults | 要有main.yml的文件,用于设定默认变量 |
tests | 用于测试角色 |
2.ansible 角色的创建
ansible—galaxy命令工具: Ansible galaxy 是一个免费共享和下载 Ansible 角色的网站,可以帮助我们更好的定义和学习roles;
ansible-galaxy命令默认与https://galaxy.ansible.com网站Api通信,可以查找、下载各种社区开发的
Ansible 角色
ansible-galaxy在 Ansible 1.4.2 就已经被包含了,可以在galaxy.ansible.com网站查询roles
列出所有已经安装的galaxy;
roles_path = ~/ansible/roles (默认目录:/etc/ansible/roles)
ansible-galaxy list 查看角色;
可以看到vsftpd角色成功创建
二、ansible角色的使用
1.书写task主任务
示例:下载安装vsftpd,根据变量更改配置文件;
编辑 ~/ansible/roles/vsftps/tasks/main.yml 文件
---
# tasks file for vsftpd
- name: install vsftpd 安装模块
dnf:
name: vsftpd
state: latest
notify: 触发器
- restart vsftpd
- firewalld set
- name: set vsftpd 修改配置模块
lineinfile:
path: /etc/vsftpd/vsftpd.conf
regexp: "anonymous_enable"
line: "anonymous_enable={{ STATE }}"
notify: 触发器
- restart vsftpd
/
2.触发器模块
查看防火墙的设置规则
示例如下
- name: restart vsftpd vsftpd模块
service:
name: vsftpd
state: restarted
enabled: yes
- name: firewalld set 防火墙模块
firewalld:
name: ftp
state: enabeld
permanent: yes
immediate: yes
3.变量模块
启用模块 ~/ansible/vsftpd.yml
执行playbook,为node主机安装vsftpd
接下来测试删除所安装的vsftpd,编辑task主任务模块
执行playbook
再次编辑task主任务模块,测试安装vsftpd
执行playbook
三、习题测试
为node主机下载httpd,要求如下:
输入域名westos.westos.org ------得到访问测试页westos.westos.org;
输入域名linux.westos.org ------得到访问测试页linux.westos.org;
输入其他默认域名 ------得到访问测试页www.westos.org。
1.创建角色apache
2.设置变量
//
---
# vars file for apache
WEBS:
- docroot: /var/www/html
index: www.westos.org
- docroot: /var/www/vhosts/westos.org/westos
name: westos.westos.org
index: westos.westos.org
- docroot: /var/www/vhosts/westos.org/linux
name: linux.westos.org
index: linux.westos.org
//
3.设置j2模板
{% for vhost in WEBS %}
{% if vhost[''name''] is not defined %}
<VirtualHost _default_:80>
{%endif%}
{% if vhost[''name''] is defined %}
<VirtualHost *:80>
ServerName {{vhost[''name'']}}
{%endif%}
DocumentRoot {{vhost[''docroot'']}}
</VirtualHost>
{% endfor %}
4.设置task任务
///
---
# tasks file for apache
- name: install apache
dnf:
name: httpd
state: latest
notify:
- restart apache
- firewalld
- name: create documentroot
file:
path: "{{ item.docroot }}"
state: directory
loop:
"{{WEBS}}"
- name: create index.html
copy:
dest: "{{ item.docroot }}/index.html"
content: "{{ item.index }}"
loop:
"{{WEBS}}"
- name: set vhost
template:
src: vhosts.conf.j2
dest: /mnt/vhost.conf
notify:
- restart apache
5.设置触发器
/
---
# handlers file for apache
- name: restart apache
service:
name: httpd
state: restarted
enabled: yes
- name: firewalld
firewalld:
service: http
state: enabled
permanent: yes
immediate: yes
///
6.设置执行任务
执行playbook
可以在node主机查看到虚拟主机的信息
四、控制任务的执行顺序
playbook中使用roles#
playbook中使用roles:
---
- hosts: server2
roles:
- role: role1
- role: role2
var1: value1 此处变量会覆盖roles中的定义变量
示例:
---
- hosts: server2
roles:
- role: role1 角色任务
pre_tasks: 角色执行前执行的play
- tasks1
tasks: 普通任务
- tasks2
post_tasks: 在角色和普通任务执行完毕后执行的play
- tasks3
handl
在上一个实验的基础上添加任务的执行顺序,继续编辑任务执行模块 ~/ansible/vsftpd.yml
执行playbook;
可以看到,在角色任务之前之前有任务执行
在角色任务之后有任务执行
五、多重角色的使用
首先真机开启火墙,打开地址伪装,使得虚拟机可以上网
ansible—galaxy命令工具:
下载角色:
访问地址角色下载地址:install https://galaxy.ansible.com roles
搜索Nginx
复制下方链接
下载角色成功
可以看到所安装的角色
打包apache角色目录,将原本的目录删除进行实验测试
列出角色,此时只有vsftps和刚刚安装的Nginx
设置执行任务
安装角色
接下来,我们安装Red Hat角色,Red Hat系统角色允许管理员有效地管理主机的指定属性
安装到了/usr/share/ansible目录下
拷贝到devops用户的ansible目录一份
列出已安装的角色
编辑执行任务,完成node主机同步时间
执行playbook
node主机编辑chrony的默认配置文件 /etc/chrony.conf
成功同步到ansible主机的时间
总结
以上是小编为你收集整理的ansible 自动化运维工具 9 (ansible角色的安装及使用)全部内容。
如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。
原文地址:https://blog.csdn.net/qq_38664479/article/details/120998706
Ansible 运维自动化
Ansible 概述
Ansbile是一种IT自动化工具。它可以配置系统,部署软件以及协调更高级的IT任务,列如持续部署,滚动更新。
Ansible 适用于管理企业IT基础设施,从具有少数主机的小规模到数千个实例的企业环境。Ansible 也是一种简单的自动化语言,可以完美地描述IT应用程序基础结构。
具备以下三个特点:
- 简单:减少学习成本
- 强大:协调应用程序生命周期
- 无代理:可预测,可靠和安全
使用文档:https://releases.ansible.com/...
安装 Ansible:
[root@ops ~]# yum install epel-release
[root@ops ~]# yum install ansible -y
- Inventory:Ansible管理的主机信息,包括IP地址、SSH端口、账号、密码等
- Modules:任务均有模块完成,也可以自定义模块,例如经常用的脚本。
- Plugins:使用插件增加Ansible核心功能,自身提供了很多插件,也可以自定义插件。例如connection插件,用于连接目标主机。
- Playbooks:“剧本”,模块化定义一系列任务,供外部统一调用。Ansible核心功能。
主机清单
[root@ops ~]# cat /etc/ansible/hosts
[webservers]
192.168.1.101
192.168.1.102
192.168.1.103
命令行使用
连接远程主机认证
SSH密码认证:
[root@ops ~]# cat /etc/ansible/hosts
[webservers]
192.168.1.101 ansible_ssh_user=root ansible_ssh_pass=’Admin@1234’
192.168.1.102 ansible_ssh_user=root ansible_ssh_pass=’Admin@1234’
192.168.1.103 ansible_ssh_user=root ansible_ssh_pass=’Admin@1234’
SSH密钥对认证:
[root@ops ~]# cat /etc/ansible/hosts
[webservers]
192.168.1.101 ansible_ssh_user=root ansible_ssh_key=/root/.ssh/id_rsa
192.168.1.102 ansible_ssh_user=root ’
192.168.1.103 ansible_ssh_user=root
也可以在配置文件中指定:
[defaults]
private_key_file = /root/.ssh/id_rsa # 默认路径
常用选项
选项 | 描述 |
---|---|
-C, --check | 运行检查,不执行任何操作 |
-e EXTRA_VARS,--extra-vars=EXTRA_VARS | 设置附加变量 key=value |
-u REMOTE_USER, --user=REMOTE_USER | SSH连接用户,默认None |
-k, --ask-pass | SSH连接用户密码 |
-b, --become | 提权,默认root |
-K, --ask-become-pass | 提权密码 |
命令行使用
[root@ops ~]# ansible all -m ping
192.168.1.102 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.1.103 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.1.101 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
[root@ops ~]# ansible all -m shell -a "ls /root" -u root -k
SSH password:
192.168.1.102 | CHANGED | rc=0 >>
etcd-v3.4.13-linux-amd64
etcd-v3.4.13-linux-amd64.tar.gz
192.168.1.101 | CHANGED | rc=0 >>
ca.cer
cfssl-certinfo_linux-amd64
cfssljson_linux-amd64
cfssl_linux-amd64
components.yaml
config.yaml
istio-1.11.4
istio-1.11.4-linux-amd64.tar.gz
transit.nolpay.ae.cer
192.168.1.103 | CHANGED | rc=0 >>
常用模块
ansible-doc –l 查看所有模块
ansible-doc –s copy 查看模块文档
shell
在目标主机执行shell命令
[root@ops ~]# ansible all -m shell -a "chdir=''/var/log/'' ls -l | grep log"
192.168.1.102 | CHANGED | rc=0 >>
-rw-------. 1 root root 0 Nov 4 03:17 boot.log
-rw-------. 1 root root 9219 Nov 4 03:17 boot.log-20211104
-rw-r--r--. 1 root root 292000 Nov 24 10:59 lastlog
-rw-------. 1 root root 0 Nov 21 03:16 maillog
-rw-------. 1 root root 198 Mar 31 2021 maillog-20211107
-rw-------. 1 root root 0 Nov 7 03:43 maillog-20211114
-rw-------. 1 root root 0 Nov 14 03:32 maillog-20211121
-rw-------. 1 root root 0 Mar 31 2021 tallylog
-rw-------. 1 root root 4480 Nov 4 14:21 yum.log
192.168.1.103 | CHANGED | rc=0 >>
-rw-------. 1 root root 0 Nov 5 03:45 boot.log
-rw-------. 1 root root 9305 Nov 4 03:14 boot.log-20211104
-rw------- 1 root root 8383 Nov 5 03:45 boot.log-20211105
-rw-r--r--. 1 root root 292000 Nov 24 10:59 lastlog
-rw------- 1 root root 0 Nov 21 03:40 maillog
-rw-------. 1 root root 424 Nov 4 14:27 maillog-20211107
-rw------- 1 root root 0 Nov 7 03:21 maillog-20211114
-rw------- 1 root root 0 Nov 14 03:49 maillog-20211121
-rw-------. 1 root root 0 Mar 31 2021 tallylog
-rw-------. 1 root root 4480 Nov 4 14:21 yum.log
192.168.1.101 | CHANGED | rc=0 >>
-rw-------. 1 root root 0 Nov 5 03:12 boot.log
-rw-------. 1 root root 9241 Nov 4 03:08 boot.log-20211104
-rw------- 1 root root 8294 Nov 5 03:12 boot.log-20211105
-rw-r--r--. 1 root root 292000 Nov 24 10:59 lastlog
-rw------- 1 root root 0 Nov 21 03:43 maillog
-rw-------. 1 root root 424 Nov 4 15:41 maillog-20211107
-rw------- 1 root root 0 Nov 7 03:31 maillog-20211114
-rw------- 1 root root 0 Nov 14 03:25 maillog-20211121
-rw-------. 1 root root 0 Mar 31 2021 tallylog
-rw-------. 1 root root 7792 Nov 4 14:43 yum.log
参数说明:
- chdir参数 : 此参数的作用就是指定一个目录,在执行对应的命令之前,会先进入到 chdir 参数指定的目录中
- executable参数:默认情况下,shell 模块会调用远程主机中的 /bin/sh 去执行对应的命令,通常情况下,远程主机中的默认 shell 都是 bash。如果你想要使用其他类型的 shell 执行命令,则可以使用此参数指定某种类型的 shell 去执行对应的命令。指定 shell 文件时,需要使用绝对路径
- removes参数 :使用此参数指定一个文件,当指定的文件不存在时,就不执行对应命令
- creates参数 :使用此参数指定一个文件,当指定的文件存在时,就不执行对应命令
- free_form参数 :必须参数,指定需要远程执行的命令,但是并没有具体的一个参数名叫
free_form
,
copy
将文件复制到远程主机
[root@ops ~]# ansible all -m copy -a "src=ArmsAgent.tar.gz dest=/tmp/"
192.168.1.103 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "0b0fed4f40a4bf83fe174309e17273cdeedb9c2e",
"dest": "/tmp/ArmsAgent.tar.gz",
"gid": 0,
"group": "root",
"md5sum": "08dcb6dbe63eeeb42628dfe9cc14e4e9",
"mode": "0644",
"owner": "root",
"size": 46325347,
"src": "/root/.ansible/tmp/ansible-tmp-1637724228.32-26808-199044113552898/source",
"state": "file",
"uid": 0
}
192.168.1.102 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "0b0fed4f40a4bf83fe174309e17273cdeedb9c2e",
"dest": "/tmp/ArmsAgent.tar.gz",
"gid": 0,
"group": "root",
"md5sum": "08dcb6dbe63eeeb42628dfe9cc14e4e9",
"mode": "0644",
"owner": "root",
"secontext": "unconfined_u:object_r:admin_home_t:s0",
"size": 46325347,
"src": "/root/.ansible/tmp/ansible-tmp-1637724228.61-26806-205389838720285/source",
"state": "file",
"uid": 0
}
192.168.1.101 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "0b0fed4f40a4bf83fe174309e17273cdeedb9c2e",
"dest": "/tmp/ArmsAgent.tar.gz",
"gid": 0,
"group": "root",
"md5sum": "08dcb6dbe63eeeb42628dfe9cc14e4e9",
"mode": "0644",
"owner": "root",
"size": 46325347,
"src": "/root/.ansible/tmp/ansible-tmp-1637724228.5-26804-266077367101765/source",
"state": "file",
"uid": 0
}
[root@ops ~]# ansible all -m copy -a "src=ArmsAgent.tar.gz dest=/tmp/ owner=root group=root mode=777"
192.168.1.102 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "0b0fed4f40a4bf83fe174309e17273cdeedb9c2e",
"dest": "/tmp/ArmsAgent.tar.gz",
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"path": "/tmp/ArmsAgent.tar.gz",
"secontext": "unconfined_u:object_r:admin_home_t:s0",
"size": 46325347,
"state": "file",
"uid": 0
}
192.168.1.103 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "0b0fed4f40a4bf83fe174309e17273cdeedb9c2e",
"dest": "/tmp/ArmsAgent.tar.gz",
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"path": "/tmp/ArmsAgent.tar.gz",
"size": 46325347,
"state": "file",
"uid": 0
}
192.168.1.101 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "0b0fed4f40a4bf83fe174309e17273cdeedb9c2e",
"dest": "/tmp/ArmsAgent.tar.gz",
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"path": "/tmp/ArmsAgent.tar.gz",
"size": 46325347,
"state": "file",
"uid": 0
}
参数说明:
- src参数 :用于指定需要copy的文件或目录
- dest参数 :用于指定文件将被拷贝到远程主机的哪个目录中,dest为必须参数
- content参数 :当不使用src指定拷贝的文件时,可以使用content直接指定文件内容,src与content两个参数必有其一,否则会报错
- force参数 : 当远程主机的目标路径中已经存在同名文件,并且与ansible主机中的文件内容不同时,是否强制覆盖,可选值有yes和no,默认值为yes,表示覆盖,如果设置为no,则不会执行覆盖拷贝操作,远程主机中的文件保持不变
- backup参数 : 当远程主机的目标路径中已经存在同名文件,并且与ansible主机中的文件内容不同时,是否对远程主机的文件进行备份,可选值有yes和no,当设置为yes时,会先备份远程主机中的文件,然后再将ansible主机中的文件拷贝到远程主机
- owner参数 : 指定文件拷贝到远程主机后的属主,但是远程主机上必须有对应的用户,否则会报错
- group参数 : 指定文件拷贝到远程主机后的属组,但是远程主机上必须有对应的组,否则会报错
- mode参数 : 指定文件拷贝到远程主机后的权限,如果你想将权限设置为”
rw-r--r--
“,则可以使用mode=0644
表示,如果你想要在user对应的权限位上添加执行权限,则可以使用mode=u+x
表示
file
管理文件和文件属性
# 创建文件
[root@ops ~]# ansible all -m file -a "path=/tmp/kubesre state=touch"
192.168.1.103 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/tmp/kubesre",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"size": 0,
"state": "file",
"uid": 0
}
192.168.1.102 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/tmp/kubesre",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"secontext": "unconfined_u:object_r:user_tmp_t:s0",
"size": 0,
"state": "file",
"uid": 0
}
192.168.1.101 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/tmp/kubesre",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"size": 0,
"state": "file",
"uid": 0
}
[root@ops ~]# ansible all -m shell -a "ls -l /tmp/kubesre"
192.168.1.102 | CHANGED | rc=0 >>
-rw-r--r--. 1 root root 0 Nov 24 11:37 /tmp/kubesre
192.168.1.103 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 Nov 24 11:37 /tmp/kubesre
192.168.1.101 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 Nov 24 11:37 /tmp/kubesre
# 创建目录
[root@ops ~]# ansible all -m file -a "path=/tmp/test state=directory"
192.168.1.103 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/tmp/test",
"size": 6,
"state": "directory",
"uid": 0
}
192.168.1.102 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/tmp/test",
"secontext": "unconfined_u:object_r:user_tmp_t:s0",
"size": 6,
"state": "directory",
"uid": 0
}
192.168.1.101 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/tmp/test",
"size": 6,
"state": "directory",
"uid": 0
}
[root@ops ~]# ansible all -m shell -a "ls -l /tmp"
192.168.1.102 | CHANGED | rc=0 >>
total 45240
drwx------. 2 root root 41 Nov 24 11:48 ansible_command_payload_ceyqUR
-rwxrwxrwx. 1 root root 46325347 Nov 24 11:23 ArmsAgent.tar.gz
-rw-r--r--. 1 root root 0 Nov 24 11:37 kubesre
drwxr-xr-x. 2 root root 6 Nov 24 11:48 test
192.168.1.103 | CHANGED | rc=0 >>
total 45240
drwx------ 2 root root 41 Nov 24 11:48 ansible_command_payload_IyoZG8
-rwxrwxrwx 1 root root 46325347 Nov 24 11:23 ArmsAgent.tar.gz
-rw-r--r-- 1 root root 0 Nov 24 11:37 kubesre
drwxr-xr-x 2 root root 6 Nov 24 11:48 test
192.168.1.101 | CHANGED | rc=0 >>
total 45240
drwx------ 2 root root 41 Nov 24 11:48 ansible_command_payload_guMhZe
-rwxrwxrwx 1 root root 46325347 Nov 24 11:23 ArmsAgent.tar.gz
-rw-r--r-- 1 root root 0 Nov 24 11:37 kubesre
drwxr-xr-x 2 root root 6 Nov 24 11:48 test
# 删除目录
[root@ops ~]# ansible all -m file -a "path=/tmp/test state=absent"
192.168.1.103 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/tmp/test",
"state": "absent"
}
192.168.1.102 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/tmp/test",
"state": "absent"
}
192.168.1.101 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/tmp/test",
"state": "absent"
}
# 修改属性
[root@ops ~]# ansible all -m file -a "path=/tmp/kubesre mode=777"
192.168.1.103 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"path": "/tmp/kubesre",
"size": 0,
"state": "file",
"uid": 0
}
192.168.1.102 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"path": "/tmp/kubesre",
"secontext": "unconfined_u:object_r:user_tmp_t:s0",
"size": 0,
"state": "file",
"uid": 0
}
192.168.1.101 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"path": "/tmp/kubesre",
"size": 0,
"state": "file",
"uid": 0
}
参数说明:
- path:要操作的文件或目录
- state:此参数非常灵活,此参数对应的值需要根据情况设定,比如,当我们需要在远程主机中创建一个目录的时候,我们需要使用path参数指定对应的目录路径,假设,我想要在远程主机上创建/testdir/a/b目录,那么我则需要设置path=/testdir/a/b,但是,我们无法从"/testdir/a/b"这个路径看出b是一个文件还是一个目录,ansible也同样无法单单从一个字符串就知道你要创建文件还是目录,所以,我们需要通过state参数进行说明,当我们想要创建的/testdir/a/b是一个目录时,需要将state的值设置为directory,"directory"为目录之意,当它与path结合,ansible就能知道我们要操作的目标是一个目录,同理,当我们想要操作的/testdir/a/b是一个文件时,则需要将state的值设置为touch,当我们想要创建软链接文件时,需将state设置为link,想要创建硬链接文件时,需要将state设置为hard,当我们想要删除一个文件时(删除时不用区分目标是文件、目录、还是链接),则需要将state的值设置为absent,"absent"为缺席之意,当我们想让操作的目标"缺席"时,就表示我们想要删除目标
- src:当state设置为link或者hard时,表示我们想要创建一个软链或者硬链,所以,我们必须指明软链或硬链链接的哪个文件,通过src参数即可指定链接源。
- force : 当state=link的时候,可配合此参数强制创建链接文件,当force=yes时,表示强制创建链接文件,不过强制创建链接文件分为两种情况,情况一:当你要创建的链接文件指向的源文件并不存在时,使用此参数,可以先强制创建出链接文件。情况二:当你要创建链接文件的目录中已经存在与链接文件同名的文件时,将force设置为yes,回将同名文件覆盖为链接文件,相当于删除同名文件,创建链接文件。情况三:当你要创建链接文件的目录中已经存在与链接文件同名的文件,并且链接文件指向的源文件也不存在,这时会强制替换同名文件为链接文件。
- owner :用于指定被操作文件的属主,属主对应的用户必须在远程主机中存在,否则会报错。
- group :用于指定被操作文件的属组,属组对应的组必须在远程主机中存在,否则会报错。
- mode:用于指定被操作文件的权限,比如,如果想要将文件权限设置为"rw-r-x---",则可以使用mode=650进行设置,或者使用mode=0650,效果也是相同的,如果你想要设置特殊权限,比如为二进制文件设置suid,则可以使用mode=4700,很方便吧。
- recurse:当要操作的文件为目录,将recurse设置为yes,可以递归的修改目录中文件的属性。
- absent:表示卸载
yum
软件包管理
# 安装Nginx
[root@ops ~]# ansible all -m yum -a "name=http://nginx.org/packages/rhel/7/x86_64/RPMS/nginx-1.16.1-1.el7.ngx.x86_64.rpm state=present"
# 卸载Nginx
[root@ops ~]# ansible all -m yum -a "name=nginx state=absent"
# 更新所有包
[root@ops ~]# ansible all -m yum -a "name=''*'' state=latest"
service/systemd
管理服务
[root@ops ~]# ansible all -m systemd -a "name=nginx state=restarted enabled=yes"
unarchive
解压到远程机器指定目录
[root@ops ~]# ansible all -m unarchive -a "src=ArmsAgent.tar.gz dest=/tmp"
192.168.1.103 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/tmp",
"extract_results": {
"cmd": [
"/usr/bin/gtar",
"--extract",
"-C",
"/tmp",
"-z",
"-f",
"/root/.ansible/tmp/ansible-tmp-1637734297.88-28601-94567791333261/source"
],
"err": "",
"out": "",
"rc": 0
},
"gid": 0,
"group": "root",
"handler": "TgzArchive",
"mode": "01777",
"owner": "root",
"size": 240,
"src": "/root/.ansible/tmp/ansible-tmp-1637734297.88-28601-94567791333261/source",
"state": "directory",
"uid": 0
}
192.168.1.102 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/tmp",
"extract_results": {
"cmd": [
"/usr/bin/gtar",
"--extract",
"-C",
"/tmp",
"-z",
"-f",
"/root/.ansible/tmp/ansible-tmp-1637734298.15-28599-160150628668658/source"
],
"err": "",
"out": "",
"rc": 0
},
"gid": 0,
"group": "root",
"handler": "TgzArchive",
"mode": "01777",
"owner": "root",
"secontext": "system_u:object_r:tmp_t:s0",
"size": 240,
"src": "/root/.ansible/tmp/ansible-tmp-1637734298.15-28599-160150628668658/source",
"state": "directory",
"uid": 0
}
192.168.1.101 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/tmp",
"extract_results": {
"cmd": [
"/usr/bin/gtar",
"--extract",
"-C",
"/tmp",
"-z",
"-f",
"/root/.ansible/tmp/ansible-tmp-1637734298.01-28597-226262773743899/source"
],
"err": "",
"out": "",
"rc": 0
},
"gid": 0,
"group": "root",
"handler": "TgzArchive",
"mode": "01777",
"owner": "root",
"size": 240,
"src": "/root/.ansible/tmp/ansible-tmp-1637734298.01-28597-226262773743899/source",
"state": "directory",
"uid": 0
}
debug
执行过程中打印语句
- debug:
msg: System {{ inventory_hostname }} has uuid {{ ansible_product_uuid }}
- name: 显示主机已知的所有变量
debug:
var: hostvars[inventory_hostname]
verbosity: 4
变量
变量是应用于多个主机的便捷方式,际在主机执行之前,变量会对每个主机添加,然后在执行中引用。
主机变量与组变量
[webservers] # 主机变量
192.168.1.101 hostname=web1
192.168.1.102 hostname=web2
192.168.1.103 hostname=web3
[webservers:vars] # 组变量
group=webservers
Register变量
- shell: /usr/bin/uptime
register: result
- debug:
var: result
verbosity: 2
Playbook
Playbooks是Ansible的配置,部署和编排语言。他们可以描述您希望在远程机器做哪些事或者描述IT流程中一系列步骤。使用易读的YAML格式组织Playbook文件。
如果Ansible模块是您工作中的工具,那么Playbook就是您的使用说明书,而您的主机资产文件就是您的原材料。
与adhoc任务执行模式相比,Playbooks使用ansible是一种完全不同的方式,并且功能特别强大。
https://docs.ansible.com/ansi...
---
- hosts: webservers
vars:
http_port: 80
server_name: www.kubesre.com
remote_user: root
gather_facts: false
tasks:
- name: 安装nginx最新版
yum: pkg=nginx state=latest
- name: 写入nginx配置文件
template: src=/srv/httpd.j2 dest=/etc/nginx/nginx.conf
notify:
- restart nginx
- name: 确保nginx正在运行
service: name=httpd state=started
handlers:
- name: restart nginx
service: name=nginx state=reloaded
主机和用户
- hosts: webservers
remote_user: root
become: yes
become_user: nginx
解释说明:
- become: 是否进行提权操作。如果需要,设置为
yes
- become_user:设置为具有所需特权的用户-您想要成为的用户,而不是您登录时使用的用户
- become_method : 权限工具,如
sudo
,su
,pfexec
,doas
,pbrun
,dzdo
,ksu
,runas
,machinectl
- become_flags :
play
或task
级别上,允许为任务或角色使用特定的标志。一种常见的用法是,当shell
设置为no login
时,将用户更改为nobody
。此指令是在Ansible 2.2中添加。
定义变量
Ansible中的首选做法是不将变量存储在Inventory中。
除了将变量直接存储在Inventory文件之外,主机和组变量还可以存储在相对于Inventory文件的单个文件中。
- hosts: webservers
vars:
http_port: 80
server_name: www.kubesre.com
任务列表
每个play包含一系列任务。这些任务按照顺序执行,在play中,所有主机都会执行相同的任务指令。play目的是将选择的主机映射到任务。
tasks:
- name: 安装nginx最新版
yum: pkg=nginx state=latest
语法检查与调试
语法检查:ansible-playbook --check /path/to/playbook.yaml
测试运行,不实际操作:ansible-playbook -C /path/to/playbook.yaml
debug模块在执行期间打印语句,对于调试变量或表达式,而不必停止play。与''when:''指令一起调试更佳。
- hosts: webserver
tasks:
- debug:
msg: {{group_names}}
- debug:
msg: {{inventory_hostname}}
- debug:
msg: {{ansible_hostname}}
任务控制
如果你有一个大的剧本,那么能够在不运行整个剧本的情况下运行特定部分可能会很有用。
tasks:
- name: 安装nginx最新版
yum: pkg=nginx state=latest
tags: install
- name: 写入nginx配置文件
template: src=/srv/httpd.j2 dest=/etc/nginx/nginx.conf
tags: config
使用:
ansible-playbook example.yml --tags "install"
ansible-playbook example.yml --tags "install,config"
ansible-playbook example.yml --skip-tags "install"
流程控制
条件:
tasks:
- name: 只在192.168.1.100运行任务
debug: msg="{{ansible_default_ipv4.address}}"
when: ansible_default_ipv4.address == ''192.168.1.100''
循环:
tasks:
- name: 批量创建用户
user: name={{ item }} state=present groups=wheel
with_items:
- testuser1
- testuser2
- name: 解压
copy: src={{ item }} dest=/tmp
with_fileglob:
- "*.txt"
常用循环语句:
语句 | 描述 |
---|---|
with_items | 标准循环 |
with_fileglob | 遍历目录文件 |
with_dict | 遍历字典 |
模板
tasks:
- name: 写入nginx配置文件
template: src=/srv/httpd.j2 dest=/etc/nginx/nginx.conf
定义变量
{% set local_ip = inventory_hostname %}
条件和循环:
{% set list=[''one'', ''two'', ''three''] %}
{% for i in list %}
{% if i == ''two'' %}
-> two
{% elif loop.index == 3 %}
-> 3
{% else %}
{{i}}
{% endif %}
{% endfor %}
例如:生成连接etcd字符串
{% for host in groups[''etcd''] %}
https://{{ hostvars[host].inventory_hostname }}:2379
{% if not loop.last %},{% endif %}
{% endfor %}
里面也可以用ansible的变量。
Roles
Roles是基于已知文件结构自动加载某些变量文件,任务和处理程序的方法。按角色对内容进行分组,适合构建复杂的部署环境。
定义Roles
Roles目录结构:
site.yml
webservers.yml
fooservers.yml
roles/
common/
tasks/
handlers/
files/
templates/
vars/
defaults/
meta/
webservers/
tasks/
defaults/
meta/
tasks
-包含角色要执行的任务的主要列表。handlers
-包含处理程序,此角色甚至在此角色之外的任何地方都可以使用这些处理程序。defaults
-角色的默认变量vars
-角色的其他变量files
-包含可以通过此角色部署的文件。templates
-包含可以通过此角色部署的模板。meta
-为此角色定义一些元数据。请参阅下面的更多细节。
通常的做法是从tasks/main.yml
文件中包含特定于平台的任务:
# roles/webservers/tasks/main.yml
- name: added in 2.4, previously you used ''include''
import_tasks: redhat.yml
when: ansible_facts[''os_family'']|lower == ''redhat''
- import_tasks: debian.yml
when: ansible_facts[''os_family'']|lower == ''debian''
# roles/webservers/tasks/redhat.yml
- yum:
name: "httpd"
state: present
# roles/webservers/tasks/debian.yml
- apt:
name: "apache2"
state: present
使用角色
# site.yml
- hosts: webservers
roles:
- common
- webservers
定义多个:
- name: 0
gather_facts: false
hosts: all
roles:
- common
- name: 1
gather_facts: false
hosts: all
roles:
- webservers
角色控制
- name: 0.系统初始化
gather_facts: false
hosts: all
roles:
- common
tags: common
定义变量
组变量:
group_vars 存放的是组变量
group_vars/all.yml 表示所有主机有效,等同于[all:vars]
grous_vars/etcd.yml 表示etcd组主机有效,等同于[etcd:vars]
点击 "阅读原文" 获取更好的阅读体验!
Ansible 运维自动化 ( 配置管理工具 )
本文转自:Ansible 运维自动化 ( 配置管理工具 )
当下有许多的运维自动化工具( 配置管理 ),例如:Ansible、SaltStack、Puppet、Fabric 等。
Ansible 一种集成 IT 系统的配置管理、应用部署、执行特定任务的开源平台,是 AnsibleWorks 公司名下的项目,该公司由 Cobbler 及 Func 的作者于 2012 年创建成立。
Ansible 基于 Python 语言实现,由 Paramiko 和 PyYAML 两个关键模块构建。
一、ansible 简介
1.1 主要特点
- 部署简单,只需在主控端部署 Ansible 环境,被控端无需做任何操作。
- 默认使用 SSH(Secure Shell)协议对设备进行管理。
- 主从集中化管理。
- 配置简单、功能强大、扩展性强。
- 支持 API 及自定义模块,可通过 Python 轻松扩展。
- 通过 Playbooks 来定制强大的配置、状态管理。
- 对云计算平台、大数据都有很好的支持。
- 提供一个功能强大、操作性强的 Web 管理界面和 REST API 接口 ---- AWX 平台。
1.2 与 SaltStack 对比
- 最大的区别是 Ansible 无需在被监控主机部署任何客户端代理,默认通过 SSH 通道进行远程命令执行或下发配置。
- 相同点是都具备功能强大、灵活的系统管理、状态配置,都使用 YAML 格式来描述配置,两者都提供丰富的模板及 API,对云计算平台、大数据都有很好的支持。
二、安装与配置
准备两台服务器或者虚拟机,一台(V1)作为管理机,一台(V2)作为被管理机
2.1 安装 Ansible
shell > yum -y install ansible
··· ···
Installed:
ansible.noarch 0:2.6.0-1.el7
Dependency Installed:
python-cffi.x86_64 0:1.6.0-5.el7 python-enum34.noarch 0:1.0.4-1.el7
python-httplib2.noarch 0:0.9.2-1.el7
python-idna.noarch 0:2.4-1.el7 python-keyczar.noarch 0:0.71c-2.el7
python-paramiko.noarch 0:2.1.1-4.el7
python-ply.noarch 0:3.4-11.el7 python-pycparser.noarch 0:2.14-1.el7
python2-cryptography.x86_64 0:1.7.2-2.el7
python2-jmespath.noarch 0:0.9.0-3.el7 python2-pyasn1.noarch 0:0.1.9-7.el7
Complete!
2.2 基本配置
shell > ls /etc/ansible
ansible.cfg hosts roles
# ansible.cfg 是 Ansible 工具的配置文件;hosts 用来配置被管理的机器;roles 是一个目录,playbook 将使用它
1)密钥认证
shell > ssh-keygen # 生成秘钥
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory ''/root/.ssh''.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
ea:11:72:ea:d2:d1:fa:1c:e0:df:4f:b0:98:31:be:fe root@localhost.localdomain
The key''s randomart image is:
+--[ RSA 2048]----+
| |
| |
| |
| |
| o.= S |
| ..*.B o |
| .ooB . . |
| ..o+ = . |
| ..oB.E.. |
+-----------------+
shell > ssh-copy-id -i ~/.ssh/id_rsa.pub "-p 22 root@192.168.12.129" # 将公钥写入被管理机
The authenticity of host ''192.168.12.129 (192.168.12.129)'' can''t be established.
RSA key fingerprint is f0:9e:01:73:a4:bf:14:10:ac:46:a9:48:cd:c5:d8:1c.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added ''192.168.12.129'' (RSA) to the list of known hosts.
root@192.168.12.129''s password:
Now try logging into the machine, with "ssh ''-p 22 root@192.168.12.129''", and check in:
.ssh/authorized_keys
to make sure we haven''t added extra keys that you weren''t expecting.
2)添加被管理机
Ansible 通过 hosts 文件添加被管理机
shell > > /etc/ansible/hosts
shell > vim /etc/ansible/hosts
[Client]
192.168.12.129
2.3 测试 Ansible
shell > ansible Client -m ping # 操作 Client 组 ( all 为操作 hosts 文件中所有主机 ),-m 指定执行 ping 模块,下面是返回结果
192.168.12.129 | SUCCESS => {
"changed": false,
"ping": "pong"
}
# -i 指定 hosts 文件位置
# -u username 指定 SSH 连接的用户名
# -k 指定远程用户密码
# -f 指定并发数
# -s 如需要 root 权限执行时使用 ( 连接用户不是 root 时 )
# -K -s 时,-K 输入 root 密码
三、常用模块
shell > ansible-doc -l # 列出 Ansible 支持的模块
shell > ansible-doc ping # 查看该模块帮助信息
3.1 远程命令模块
1)command 作为 Ansible 的默认模块,可以运行远程权限范围所有的 shell 命令,不支持管道符。
shell > ansible Client -m command -a "free -m" # 查看 Client 分组主机内存使用情况
2)script 的功能是在远程主机执行主控端存储的 shell 脚本文件,相当于 scp + shell 组合。
shell > ansible Client -m script -a "/home/test.sh 12 34" # 远程执行本地脚本
3)shell 的功能是执行远程主机上的 shell 脚本文件,支持管道符。
shell > ansible Client -m shell -a "/home/test.sh" # 执行远程脚本
3.2 copy 模块
实现主控端向目标主机拷贝文件,类似于 scp 功能。
shell > ansible Client -m copy -a "src=/home/test.sh desc=/tmp/ owner=root group=root mode=0755" # 向 Client 组中主机拷贝 test.sh 到 /tmp 下,属主、组为 root ,权限为 0755
3.3 stat 模块
获取远程文件状态信息,atime/ctime/mtime/md5/uid/gid 等信息
[root@V1 ~]# ansible client -m stat -a "path=/etc/syctl.conf"
xxx.xxx.xxx.xxx | SUCCESS => {
"changed": false,
"stat": {
"exists": false
}
}
3.4 get_url 模块
实现在远程主机下载指定 URL 到本地,支持 sha256sum 文件校验
[root@V1 ~]# ansible client -m get_url -a "url=http://www.baidu.com dest=/tmp/index.html mode=0440 force=yes"
xxx.xxx.xxx.xx | SUCCESS => {
"changed": true,
"checksum_dest": null,
"checksum_src": "2aedf2e39680af1b3117968b873f3bff4689aa3c",
"dest": "/tmp/index.html",
"gid": 0,
"group": "root",
"md5sum": "65f8aa88646bf193e366f14cbccad52a",
"mode": "0440",
"msg": "OK (unknown bytes)",
"owner": "root",
"size": 117103,
"src": "/tmp/tmpg7OMdb",
"state": "file",
"status_code": 200,
"uid": 0,
"url": "http://www.baidu.com"
}
3.5 yum 模块
该模块用于软件包管理
[root@V1 ~]# ansible client -m yum -a "name=curl state=latest"
xxx.xxx.xxx.xxx | SUCCESS => {
"changed": true,
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package curl.x86_64 0:7.29.0-42.el7_4.1 will be updated\n---> Package curl.x86_64 0:7.29.0-46.el7 will be an update\n--> Processing Dependency: libcurl = 7.29.0-46.el7 for package: curl-7.29.0-46.el7.x86_64\n--> Running transaction check\n---> Package libcurl.x86_64 0:7.29.0-42.el7_4.1 will be updated\n---> Package libcurl.x86_64 0:7.29.0-46.el7 will be an update\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nUpdating:\n curl x86_64 7.29.0-46.el7 base 268 k\nUpdating for dependencies:\n libcurl x86_64 7.29.0-46.el7 base 220 k\n\nTransaction Summary\n================================================================================\nUpgrade 1 Package (+1 Dependent package)\n\nTotal download size: 488 k\nDownloading packages:\nDelta RPMs disabled because /usr/bin/applydeltarpm not installed.\n--------------------------------------------------------------------------------\nTotal 1.6 MB/s | 488 kB 00:00 \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Updating : libcurl-7.29.0-46.el7.x86_64 1/4 \n Updating : curl-7.29.0-46.el7.x86_64 2/4 \n Cleanup : curl-7.29.0-42.el7_4.1.x86_64 3/4 \n Cleanup : libcurl-7.29.0-42.el7_4.1.x86_64 4/4 \n Verifying : curl-7.29.0-46.el7.x86_64 1/4 \n Verifying : libcurl-7.29.0-46.el7.x86_64 2/4 \n Verifying : curl-7.29.0-42.el7_4.1.x86_64 3/4 \n Verifying : libcurl-7.29.0-42.el7_4.1.x86_64 4/4 \n\nUpdated:\n curl.x86_64 0:7.29.0-46.el7 \n\nDependency Updated:\n libcurl.x86_64 0:7.29.0-46.el7 \n\nComplete!\n"
]
}
3.6 cron 模块
远程主机 crontab 配置
shell > ansible Client -m cron -a "name=''check dirs'' hour=''5,2'' job=''ls -alh > /dev/null''"
效果:
#Ansible: check dirs
* 5,2 * * * ls -alh > /dev/null
3.7 mount 模块
远程主机分区挂载
shell > ansible Client -m mount -a "name=/mnt/data src=/dev/sd0 fstype=ext4 opts=ro state=present"
3.8 service 模块
远程主机系统服务管理
shell > ansible Client -m service -a "name=nginx state=stoped"
shell > ansible Client -m service -a "name=nginx state=restarted"
shell > ansible Client -m service -a "name=nginx state=reloaded"
3.9 user 服务模块
远程主机用户管理
shell > ansible Client -m user -a "name=wang comment=''user wang''"
shell > ansible Client -m user -a "name=wang state=absent remove=yes" # 添加删除用户
四、应用与拓展
4.1 /etc/ansible/hosts 文件
# Ansible 定义主机、组规则的配置文件
shell > vim /etc/ansible/hosts
www.abc.com # 定义域名
192.168.1.100 # 定义 IP
192.168.1.150:37268 # 指定端口号
[WebServer] # 定义分组
192.168.1.10
192.168.1.20
192.168.1.30
[DBServer] # 定义多个分组
192.168.1.50
192.168.1.60
Monitor ansible_ssh_port=12378 ansible_ssh_host=192.168.1.200 # 定义别名
# ansible_ssh_host 连接目标主机的地址
# ansible_ssh_port 连接目标主机的端口,默认 22 时无需指定
# ansible_ssh_user 连接目标主机默认用户
# ansible_ssh_pass 连接目标主机默认用户密码
# ansible_ssh_connection 目标主机连接类型,可以是 local 、ssh 或 paramiko
# ansible_ssh_private_key_file 连接目标主机的 ssh 私钥
# ansible_*_interpreter 指定采用非 Python 的其他脚本语言,如 Ruby 、Perl 或其他类似 ansible_python_interpreter 解释器
[webservers] # 主机名支持正则描述
www[01:50].example.com
[dbservers]
db-[a:f].example.com
五、Ansible-playbook
# 使用 Ansible-playbook 可以完成一组复杂的动作,例如部署环境、搭建服务、修改配置等。
简单示例:
shell > vim /etc/ansible/playbook.yml # 将远程主机IP地址写入文件中保存
---
- hosts: Client
remote_user: root
tasks:
- name: Save IP To info.txt
shell: "ifconfig eth0 | awk -F ''[ :]''+ ''/inet addr/{print $4}'' > ~/info.txt"
# hosts 指定执行操作主机
# remote_user 指定执行用户
# tasks 指明有哪些动作
# name 动作描述
# shell 模块,后面为具体指令
5.1 Playbook 实战
一、目录结构
shell > cd /etc/ansible/ ; tree .
.
├── ansible.cfg
├── delete_zabbix_agent.yml
├── hosts
├── install_zabbix_agent.yml
└── roles
├── delete_zabbix_agent
│ ├── tasks
│ │ └── main.yml
│ └── vars
│ └── main.yml
└── install_zabbix_agent
├── files
│ └── zabbix-2.4.5.tar.gz
├── tasks
│ └── main.yml
├── templates
│ ├── zabbix_agentd
│ └── zabbix_agentd.conf
└── vars
└── main.yml
## ansible.cfg 此文件为 ansible 的主配置文件
## hosts 用于定义主机组
## roles 定义不同的角色
## install_zabbix_agent.yml 用于安装 zabbix_agent 的引导文件
## delete_zabbix_agent.yml 删除已安装的 zabbix_agent 的引导文件
└── install_zabbix_agent
├── files
│ └── zabbix-2.4.5.tar.gz
├── tasks
│ └── main.yml
├── templates
│ ├── zabbix_agentd
│ └── zabbix_agentd.conf
└── vars
└── main.yml
## 其中,install_zabbix_agent 为一个角色,用于安装 zabbix_agent
## file 目录:用于存放将要拷贝到远程主机的安装包等
## tasks 目录:将要执行的所有任务,如果比较复杂,可以单独定义不同的任务,最后在 main.yml 文件中引用即可
## templates 目录:模板目录,这里存放着一些可变的文件,即:每台主机上的这些文件中的内容都不完全相同
## vars 目录:用于存放变量
## 这是一个比较简单的结构,其实一个角色中还可以有 meta 、handlers 等
5.2 Playbook 安装软件需要的步骤
1)定义 hosts( 给哪些主机安装软件 )
shell > vim /etc/ansible/hosts
[mini]
129.139.153.78:16283
155.139.190.94:12573
2)定义入口文件 install_zabbix_agent.yml
shell > vim /etc/ansible/install_zabbix_agent.yml
---
- hosts: mini
roles:
- install_zabbix_agent
## 可以看到将要安装的主机组为 mini 组,角色为 install_zabbix_agent
3)定义角色 install_zabbix_agent
shell > tree /etc/ansible/roles/install_zabbix_agent/
├── files
│ └── zabbix-2.4.5.tar.gz
├── tasks
│ └── main.yml
├── templates
│ ├── zabbix_agentd
│ └── zabbix_agentd.conf
└── vars
└── main.yml
## 建立 files 目录,存放编译安装过的 zabbix_agent 目录的压缩文件,用于拷贝到远程主机
## 建立 tasks 目录,用于编写将要执行的任务
## 建立 templates 目录,用于存放可变的模板文件
## 建立 vars 目录,用于存放变量信息
shell > cat /etc/ansible/roles/install_zabbix_agent/tasks/main.yml
---
- name: Install Software
yum: name={{ item }} state=latest
with_items:
- libcurl-devel
- name: Create Zabbix User
user: name={{ zabbix_user }} state=present createhome=no shell=/sbin/nologin
- name: Copy Zabbix.tar.gz
copy: src=zabbix-{{ zabbix_version }}.tar.gz dest={{ zabbix_dir }}/src/zabbix-{{ zabbix_version }}.tar.gz owner=root group=root
- name: Uncompression Zabbix.tar.gz
shell: tar zxf {{ zabbix_dir }}/src/zabbix-{{ zabbix_version }}.tar.gz -C {{ zabbix_dir }}/
- name: Copy Zabbix Start Script
template: src=zabbix_agentd dest=/etc/init.d/zabbix_agentd owner=root group=root mode=0755
- name: Copy Zabbix Config File
template: src=zabbix_agentd.conf dest={{ zabbix_dir }}/zabbix/etc/zabbix_agentd.conf owner={{ zabbix_user }} group={{ zabbix_user }} mode=0644
- name: Modify Zabbix Dir Permisson
file: path={{ zabbix_dir }}/zabbix owner={{ zabbix_user }} group={{ zabbix_user }} mode=0755 recurse=yes
- name: Start Zabbix Service
shell: /etc/init.d/zabbix_agentd start
- name: Add Boot Start Zabbix Service
shell: chkconfig --level 35 zabbix_agentd on
shell > cat /etc/ansible/roles/install_zabbix_agent/vars/main.yml
zabbix_dir: /usr/local
zabbix_version: 2.4.5
zabbix_user: zabbix
zabbix_port: 10050
zabbix_server_ip: 131.142.101.120
shell > cat /etc/ansible/roles/install_zabbix_agent/templates/zabbix_agentd
#!/bin/bash
#
# chkconfig: - 90 10
# description: Starts and stops Zabbix Agent using chkconfig
# Tested on Fedora Core 2 - 5
# Should work on all Fedora Core versions
#
# @name: zabbix_agentd
# @author: Alexander Hagenah <hagenah@topconcepts.com>
# @created: 18.04.2006
#
# Modified for Zabbix 2.0.0
# May 2012, Zabbix SIA
#
# Source function library.
. /etc/init.d/functions
# Variables
# Edit these to match your system settings
# Zabbix-Directory
BASEDIR={{ zabbix_dir }}/zabbix
# Binary File
BINARY_NAME=zabbix_agentd
# Full Binary File Call
FULLPATH=$BASEDIR/sbin/$BINARY_NAME
# PID file
PIDFILE=/tmp/$BINARY_NAME.pid
# Establish args
ERROR=0
STOPPING=0
#
# No need to edit the things below
#
# application checking status
if [ -f $PIDFILE ] && [ -s $PIDFILE ]
then
PID=`cat $PIDFILE`
if [ "x$PID" != "x" ] && kill -0 $PID 2>/dev/null && [ $BINARY_NAME == `ps -e | grep $PID | awk ''{print $4}''` ]
then
STATUS="$BINARY_NAME (pid `pidof $APP`) running.."
RUNNING=1
else
rm -f $PIDFILE
STATUS="$BINARY_NAME (pid file existed ($PID) and now removed) not running.."
RUNNING=0
fi
else
if [ `ps -e | grep $BINARY_NAME | head -1 | awk ''{ print $1 }''` ]
then
STATUS="$BINARY_NAME (pid `pidof $APP`, but no pid file) running.."
else
STATUS="$BINARY_NAME (no pid file) not running"
fi
RUNNING=0
fi
# functions
start() {
if [ $RUNNING -eq 1 ]
then
echo "$0 $ARG: $BINARY_NAME (pid $PID) already running"
else
action $"Starting $BINARY_NAME: " $FULLPATH
touch /var/lock/subsys/$BINARY_NAME
fi
}
stop() {
echo -n $"Shutting down $BINARY_NAME: "
killproc $BINARY_NAME
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$BINARY_NAME
RUNNING=0
}
# logic
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status $BINARY_NAME
;;
restart)
stop
sleep 10
start
;;
help|*)
echo $"Usage: $0 {start|stop|status|restart|help}"
cat <<EOF
start - start $BINARY_NAME
stop - stop $BINARY_NAME
status - show current status of $BINARY_NAME
restart - restart $BINARY_NAME if running by sending a SIGHUP or start if not running
help - this screen
EOF
exit 1
;;
esac
exit 0
shell > cat /etc/ansible/roles/install_zabbix_agent/templates/zabbix_agentd.conf
# This is a config file for the Zabbix agent daemon (Unix)
# To get more information about Zabbix, visit http://www.zabbix.com
############ GENERAL PARAMETERS #################
### Option: PidFile
# Name of PID file.
#
# Mandatory: no
# Default:
# PidFile=/tmp/zabbix_agentd.pid
### Option: LogFile
# Name of log file.
# If not set, syslog is used.
#
# Mandatory: no
# Default:
# LogFile=
LogFile=/tmp/zabbix_agentd.log
### Option: LogFileSize
# Maximum size of log file in MB.
# 0 - disable automatic log rotation.
#
# Mandatory: no
# Range: 0-1024
# Default:
# LogFileSize=1
### Option: DebugLevel
# Specifies debug level
# 0 - basic information about starting and stopping of Zabbix processes
# 1 - critical information
# 2 - error information
# 3 - warnings
# 4 - for debugging (produces lots of information)
#
# Mandatory: no
# Range: 0-4
# Default:
# DebugLevel=3
### Option: SourceIP
# Source IP address for outgoing connections.
#
# Mandatory: no
# Default:
# SourceIP=
### Option: EnableRemoteCommands
# Whether remote commands from Zabbix server are allowed.
# 0 - not allowed
# 1 - allowed
#
# Mandatory: no
# Default:
# EnableRemoteCommands=0
### Option: LogRemoteCommands
# Enable logging of executed shell commands as warnings.
# 0 - disabled
# 1 - enabled
#
# Mandatory: no
# Default:
# LogRemoteCommands=0
##### Passive checks related
### Option: Server
# List of comma delimited IP addresses (or hostnames) of Zabbix servers.
# Incoming connections will be accepted only from the hosts listed here.
# If IPv6 support is enabled then ''127.0.0.1'', ''::127.0.0.1'', ''::ffff:127.0.0.1'' are treated equally.
#
# Mandatory: no
# Default:
# Server=
Server={{ zabbix_server_ip }}
### Option: ListenPort
# Agent will listen on this port for connections from the server.
#
# Mandatory: no
# Range: 1024-32767
# Default:
# ListenPort=10050
ListenPort={{ zabbix_port }}
### Option: ListenIP
# List of comma delimited IP addresses that the agent should listen on.
# First IP address is sent to Zabbix server if connecting to it to retrieve list of active checks.
#
# Mandatory: no
# Default:
# ListenIP=0.0.0.0
### Option: StartAgents
# Number of pre-forked instances of zabbix_agentd that process passive checks.
# If set to 0, disables passive checks and the agent will not listen on any TCP port.
#
# Mandatory: no
# Range: 0-100
# Default:
# StartAgents=3
##### Active checks related
### Option: ServerActive
# List of comma delimited IP:port (or hostname:port) pairs of Zabbix servers for active checks.
# If port is not specified, default port is used.
# IPv6 addresses must be enclosed in square brackets if port for that host is specified.
# If port is not specified, square brackets for IPv6 addresses are optional.
# If this parameter is not specified, active checks are disabled.
# Example: ServerActive=127.0.0.1:20051,zabbix.domain,[::1]:30051,::1,[12fc::1]
#
# Mandatory: no
# Default:
# ServerActive=
#ServerActive=127.0.0.1:10051
### Option: Hostname
# Unique, case sensitive hostname.
# Required for active checks and must match hostname as configured on the server.
# Value is acquired from HostnameItem if undefined.
#
# Mandatory: no
# Default:
# Hostname=
Hostname={{ ansible_all_ipv4_addresses[1] }}
### Option: HostnameItem
# Item used for generating Hostname if it is undefined. Ignored if Hostname is defined.
# Does not support UserParameters or aliases.
#
# Mandatory: no
# Default:
# HostnameItem=system.hostname
### Option: HostMetadata
# Optional parameter that defines host metadata.
# Host metadata is used at host auto-registration process.
# An agent will issue an error and not start if the value is over limit of 255 characters.
# If not defined, value will be acquired from HostMetadataItem.
#
# Mandatory: no
# Range: 0-255 characters
# Default:
# HostMetadata=
### Option: HostMetadataItem
# Optional parameter that defines an item used for getting host metadata.
# Host metadata is used at host auto-registration process.
# During an auto-registration request an agent will log a warning message if
# the value returned by specified item is over limit of 255 characters.
# This option is only used when HostMetadata is not defined.
#
# Mandatory: no
# Default:
# HostMetadataItem=
### Option: RefreshActiveChecks
# How often list of active checks is refreshed, in seconds.
#
# Mandatory: no
# Range: 60-3600
# Default:
# RefreshActiveChecks=120
### Option: BufferSend
# Do not keep data longer than N seconds in buffer.
#
# Mandatory: no
# Range: 1-3600
# Default:
# BufferSend=5
### Option: BufferSize
# Maximum number of values in a memory buffer. The agent will send
# all collected data to Zabbix Server or Proxy if the buffer is full.
#
# Mandatory: no
# Range: 2-65535
# Default:
# BufferSize=100
### Option: MaxLinesPerSecond
# Maximum number of new lines the agent will send per second to Zabbix Server
# or Proxy processing ''log'' and ''logrt'' active checks.
# The provided value will be overridden by the parameter ''maxlines'',
# provided in ''log'' or ''logrt'' item keys.
#
# Mandatory: no
# Range: 1-1000
# Default:
# MaxLinesPerSecond=100
############ ADVANCED PARAMETERS #################
### Option: Alias
# Sets an alias for an item key. It can be used to substitute long and complex item key with a smaller and simpler one.
# Multiple Alias parameters may be present. Multiple parameters with the same Alias key are not allowed.
# Different Alias keys may reference the same item key.
# For example, to retrieve the ID of user ''zabbix'':
# Alias=zabbix.userid:vfs.file.regexp[/etc/passwd,^zabbix:.:([0-9]+),,,,\1]
# Now shorthand key zabbix.userid may be used to retrieve data.
# Aliases can be used in HostMetadataItem but not in HostnameItem parameters.
#
# Mandatory: no
# Range:
# Default:
### Option: Timeout
# Spend no more than Timeout seconds on processing
#
# Mandatory: no
# Range: 1-30
# Default:
Timeout=20
### Option: AllowRoot
# Allow the agent to run as ''root''. If disabled and the agent is started by ''root'', the agent
# will try to switch to the user specified by the User configuration option instead.
# Has no effect if started under a regular user.
# 0 - do not allow
# 1 - allow
#
# Mandatory: no
# Default:
# AllowRoot=0
### Option: User
# Drop privileges to a specific, existing user on the system.
# Only has effect if run as ''root'' and AllowRoot is disabled.
#
# Mandatory: no
# Default:
# User=zabbix
### Option: Include
# You may include individual files or all files in a directory in the configuration file.
# Installing Zabbix will create include directory in /usr/local/etc, unless modified during the compile time.
#
# Mandatory: no
# Default:
# Include=
# Include=/usr/local/etc/zabbix_agentd.userparams.conf
# Include=/usr/local/etc/zabbix_agentd.conf.d/
# Include=/usr/local/etc/zabbix_agentd.conf.d/*.conf
####### USER-DEFINED MONITORED PARAMETERS #######
### Option: UnsafeUserParameters
# Allow all characters to be passed in arguments to user-defined parameters.
# 0 - do not allow
# 1 - allow
#
# Mandatory: no
# Range: 0-1
# Default:
UnsafeUserParameters=1
### Option: UserParameter
# User-defined parameter to monitor. There can be several user-defined parameters.
# Format: UserParameter=<key>,<shell command>
# See ''zabbix_agentd'' directory for examples.
#
# Mandatory: no
# Default:
# UserParameter=
####### LOADABLE MODULES #######
### Option: LoadModulePath
# Full path to location of agent modules.
# Default depends on compilation options.
#
# Mandatory: no
# Default:
# LoadModulePath=${libdir}/modules
### Option: LoadModule
# Module to load at agent startup. Modules are used to extend functionality of the agent.
# Format: LoadModule=<module.so>
# The modules must be located in directory specified by LoadModulePath.
# It is allowed to include multiple LoadModule parameters.
#
# Mandatory: no
# Default:
# LoadModule=
4)执行安装
shell > ansible-playbook /etc/ansible/install_zabbix_agent.yml
PLAY [mini] *******************************************************************
GATHERING FACTS ***************************************************************
ok: [129.139.153.78]
ok: [155.139.190.94]
TASK: [install_zabbix_agent | Install Software] *******************************
changed: [155.139.190.94] => (item=libcurl-devel)
changed: [129.139.153.78] => (item=libcurl-devel)
TASK: [install_zabbix_agent | Create Zabbix User] *****************************
changed: [129.139.153.78]
changed: [155.139.190.94]
TASK: [install_zabbix_agent | Copy Zabbix.tar.gz] *****************************
changed: [129.139.153.78]
changed: [155.139.190.94]
TASK: [install_zabbix_agent | Uncompression Zabbix.tar.gz] ********************
changed: [129.139.153.78]
changed: [155.139.190.94]
TASK: [install_zabbix_agent | Copy Zabbix Start Script] ***********************
changed: [155.139.190.94]
changed: [129.139.153.78]
TASK: [install_zabbix_agent | Copy Zabbix Config File] ************************
changed: [129.139.153.78]
changed: [155.139.190.94]
TASK: [install_zabbix_agent | Modify Zabbix Dir Permisson] ********************
changed: [155.139.190.94]
changed: [129.139.153.78]
TASK: [install_zabbix_agent | Start Zabbix Service] ***************************
changed: [129.139.153.78]
changed: [155.139.190.94]
TASK: [install_zabbix_agent | Add Boot Start Zabbix Service] ******************
changed: [129.139.153.78]
changed: [155.139.190.94]
PLAY RECAP ********************************************************************
155.139.190.94 : ok=10 changed=9 unreachable=0 failed=0
129.139.153.78 : ok=10 changed=9 unreachable=0 failed=0
## 关注一下,启动脚本跟配置文件中变量的引用。
## 完成安装,可以去客户机检查效果了 !
附上:delete_zabbix_agent.yml 相关内容
shell > vim /etc/ansible/delete_zabbix_agent.yml
---
- hosts: mini
roles:
- delete_zabbix_agent
shell > vim /etc/ansible/roles/delete_zabbix_agent/tasks/main.yml
---
- name: Stop Zabbix_agent
shell: pgrep zabbix_agentd | xargs kill
ignore_errors: yes
- name: Delete Boot Start
shell: chkconfig --del zabbix_agentd
- name: Delete Start Script
shell: rm -rf /etc/init.d/zabbix_agentd
- name: Delete Install Dir
shell: rm -rf {{ zabbix_dir }}/zabbix
- name: Delete Software
shell: rm -rf {{ zabbix_dir }}/src/zabbix-{{ zabbix_version }}.tar.gz
- name: Delete Log File
shell: rm -rf /tmp/zabbix_agentd.log
- name: Delete Zabbix User
user: name={{ zabbix_user }} state=absent remove=yes
shell > vim /etc/ansible/roles/delete_zabbix_agent/vars/main.yml
zabbix_dir: /usr/local
zabbix_version: 2.4.5
zabbix_user: zabbix
Ansible运维自动化
Ansible运维自动化
一、Ansible-playbook的初步使用
playbook的使用,playbook可以把ansible的模块进行组合
ln -s /usr/local/python/bin/ansible-playbook /usr/local/bin/
1、playbook的简单shell模块使用
- [root@ansible scripts]# cat test_shell.yaml #playbook的执行模板
- --- #开头三个小-开头
- - hosts: webB
- tasks:
- - name: test
- shell: echo "welcome to yunjisaun" >> /tmp/username
- - name: test2
- shell: echo "welcome to yunjisuan" >> /tmp/username
- 模板说明:
- --- #开头必须有三个小-,顶格写
- - hosts: #正文配置代码的第一级,必须有两个空格(-占一个空格位)
- - host: webB #webB是host参数的值,值和hosts:之间要有一个空格
- tasks: #tasks:表示接下来要执行的具体任务
- - name: #相对于tasks再多缩进两个格(-占一个空格位),表示属于tasks的下一级
- - name: test #test只是要执行的具体命令的名字可以随便写。name:后还是有一个空格要注意
- shell: #表示调用shell模块执行命令相对于tasks仍旧要多缩进两个空格
- shell: echo "xxx" >> xxx #shell:后边还是要有个空格,需要注意。
执行playbook配置文件
- [root@ansible scripts]# ansible-playbook test_shell.yaml #执行playbook配置文件
- PLAY [webB] ********************************************************************************************************
- TASK [Gathering Facts] *********************************************************************************************
- ok: [webB]
- TASK [test] ********************************************************************************************************
- changed: [webB]
- TASK [test2] *******************************************************************************************************
- changed: [webB]
- PLAY RECAP *********************************************************************************************************
- webB : ok=3 changed=2 unreachable=0 failed=0
2、playbook的简单copy模块的使用
- [root@ansible scripts]# echo "welcom to yunjisuan" >> /tmp/test_copy
- [root@ansible scripts]# cat test_copy.yaml
- ---
- - hosts: all
- tasks:
- - name: test copy
- copy: src=/tmp/copy_test dest=/tmp/
- [root@ansible scripts]# ansible-playbook /service/scripts/test_copy.yaml
- PLAY [all] *********************************************************************************************************
- TASK [Gathering Facts] *********************************************************************************************
- ok: [webA]
- ok: [webB]
- TASK [test copy] ***************************************************************************************************
- changed: [webA]
- changed: [webB]
- PLAY RECAP *********************************************************************************************************
- webA : ok=2 changed=1 unreachable=0 failed=0
- webB : ok=2 changed=1 unreachable=0 failed=0
3、playbook使用register输出命令运行结果
我们在用playbook进行ansible模块操作的时候,并没有命令的执行结果输出,默认被隐藏了。
我们可以通过register模块追加输出命令的执行结果。
- [root@ansible scripts]# cat test_register.yaml
- ---
- - hosts: all
- tasks:
- - name: test register
- shell: echo "welcome to yunjisuan"
- register: print_result #将之前命令的输出结果保存在变量print_result里
- - debug: var=print_result #将变量的值作为debug输出出来。
- [root@ansible scripts]# ansible-playbook test_register.yaml
- PLAY [all] *********************************************************************************************************
- TASK [Gathering Facts] *********************************************************************************************
- ok: [webA]
- ok: [webB]
- TASK [test register] ***********************************************************************************************
- changed: [webA]
- changed: [webB]
- TASK [debug] *******************************************************************************************************
- ok: [webA] => { #命令的执行结果有输出了
- "print_result": {
- "changed": true,
- "cmd": "echo \"welcome to yunjisuan\"",
- "delta": "0:00:00.002269",
- "end": "2018-06-15 10:28:14.693883",
- "failed": false,
- "rc": 0,
- "start": "2018-06-15 10:28:14.691614",
- "stderr": "",
- "stderr_lines": [],
- "stdout": "welcome to yunjisuan",
- "stdout_lines": [
- "welcome to yunjisuan"
- ]
- }
- }
- ok: [webB] => {
- "print_result": {
- "changed": true,
- "cmd": "echo \"welcome to yunjisuan\"",
- "delta": "0:00:00.002633",
- "end": "2018-06-15 10:28:14.710242",
- "failed": false,
- "rc": 0,
- "start": "2018-06-15 10:28:14.707609",
- "stderr": "",
- "stderr_lines": [],
- "stdout": "welcome to yunjisuan",
- "stdout_lines": [
- "welcome to yunjisuan"
- ]
- }
- }
- PLAY RECAP *********************************************************************************************************
- webA : ok=3 changed=1 unreachable=0 failed=0
- webB : ok=3 changed=1 unreachable=0 failed=0
4、nginx配置下发并检测
- [root@ansible scripts]# cat test_nginx_conf.yaml
- ---
- - hosts: all
- tasks:
- - name: copy nginx.conf
- copy: src=/tmp/nginx.conf dest=/usr/local/nginx/conf/ backup=yes
- - name:
- shell: /usr/local/nginx/sbin/nginx -t
- register: nginx_result
- - debug: var=nginx_result
二、playbook的自定义变量和内置变量
1、在playbook中使用自定义变量
- [root@localhost scripts]# cat test_vars.yaml
- ---
- - hosts: all
- vars: #定义变量
- - name: "yunjisuan" #第一个name变量
- age: "3" #第二个age变量
- tasks:
- - name: "{{ name }}" #{{}}两对大括号引用变量,变量名两头空格
- shell: echo "myname {{ name }},myage {{ age }}"
- register: var_result
- - debug: var=var_result
- 特别提示:
- 引用变量需要在双引号中引用。
- [root@localhost scripts]# ansible-playbook /service/scripts/test_vars.yaml
- [WARNING]: Found variable using reserved name: name #这里提示,name是一个保留的内置变量,我们在自定义时不能用
- PLAY [all] *********************************************************************************************************
- TASK [Gathering Facts] *********************************************************************************************
- ok: [webA]
- ok: [webB]
- TASK [yunjisuan] ***************************************************************************************************
- changed: [webA]
- changed: [webB]
- TASK [debug] *******************************************************************************************************
- ok: [webA] => {
- "var_result": {
- "changed": true,
- "cmd": "echo \"myname yunjisuan,myage 3\"",
- "delta": "0:00:00.002320",
- "end": "2018-06-19 10:45:16.175728",
- "failed": false,
- "rc": 0,
- "start": "2018-06-19 10:45:16.173408",
- "stderr": "",
- "stderr_lines": [],
- "stdout": "myname yunjisuan,myage 3",
- "stdout_lines": [
- "myname yunjisuan,myage 3"
- ]
- }
- }
- ok: [webB] => {
- "var_result": {
- "changed": true,
- "cmd": "echo \"myname yunjisuan,myage 3\"",
- "delta": "0:00:00.002518",
- "end": "2018-06-19 10:45:10.552331",
- "failed": false,
- "rc": 0,
- "start": "2018-06-19 10:45:10.549813",
- "stderr": "",
- "stderr_lines": [],
- "stdout": "myname yunjisuan,myage 3",
- "stdout_lines": [
- "myname yunjisuan,myage 3"
- ]
- }
- }
- PLAY RECAP *********************************************************************************************************
- webA : ok=3 changed=1 unreachable=0 failed=0
- webB : ok=3 changed=1 unreachable=0 failed=0
- #我们修改一下name这个变量再发送,就不会出警告了
- [root@localhost scripts]# cat test_vars.yaml
- ---
- - hosts: all
- vars:
- - names: "yunjisuan"
- age: "3"
- tasks:
- - name: "{{ names }}"
- shell: echo "myname {{ names }},myage {{ age }}"
- register: var_result
- - debug: var=var_result
在使用自定义变量时,我们要特别注意不要和系统的内置保留变量同名,容易引发问题
2、在playbook中使用Ansible内置变量
我们可以使用ansible all -m setup | less查看ansible内置变量
- [root@localhost scripts]# cat test_setupvars.yaml
- ---
- - hosts: all
- gather_facts: True #使用ansible内置变量
- tasks:
- - name: setup var
- shell: echo "ip {{ ansible_all_ipv4_addresses[0] }} cpu {{ ansible_processor_count }}"
- register: var_result
- - debug: var=var_result
- [root@localhost scripts]# ansible-playbook test_setupvars.yaml
- PLAY [all] *********************************************************************************************************
- TASK [Gathering Facts] *********************************************************************************************
- ok: [webA]
- ok: [webB]
- TASK [setup var] ***************************************************************************************************
- changed: [webA]
- changed: [webB]
- TASK [debug] *******************************************************************************************************
- ok: [webA] => {
- "var_result": {
- "changed": true,
- "cmd": "echo \"ip 192.168.200.132 cpu 1\"",
- "delta": "0:00:00.002408",
- "end": "2018-06-19 11:32:44.540658",
- "failed": false,
- "rc": 0,
- "start": "2018-06-19 11:32:44.538250",
- "stderr": "",
- "stderr_lines": [],
- "stdout": "ip 192.168.200.132 cpu 1",
- "stdout_lines": [
- "ip 192.168.200.132 cpu 1"
- ]
- }
- }
- ok: [webB] => {
- "var_result": {
- "changed": true,
- "cmd": "echo \"ip 192.168.200.138 cpu 1\"",
- "delta": "0:00:00.002102",
- "end": "2018-06-19 11:32:44.526875",
- "failed": false,
- "rc": 0,
- "start": "2018-06-19 11:32:44.524773",
- "stderr": "",
- "stderr_lines": [],
- "stdout": "ip 192.168.200.138 cpu 1",
- "stdout_lines": [
- "ip 192.168.200.138 cpu 1"
- ]
- }
- }
- PLAY RECAP *********************************************************************************************************
- webA : ok=3 changed=1 unreachable=0 failed=0
- webB : ok=3 changed=1 unreachable=0 failed=0
简单演示一下ansible内置变量的取用方法ansible all -m setup | less
- [root@localhost scripts]# cat test_setupvars.yaml
- ---
- - hosts: all
- gather_facts: True
- tasks:
- - name: setup var
- shell: echo "ip {{ ansible_all_ipv4_addresses[0] }} cpu {{ ansible_processor_count }}" >> /tmp/test
- - name: setup var2
- shell: echo "time {{ ansible_date_time["date"] }}" >> /tmp/test
- register: var_result
- - debug: var=var_result
三、Playbook下发可变配置文件
配置文件如果使用copy模块去下发的话,那配置都是一样的;
如果下发的配置文件里有可变的配置,需要用到template模块。
1、利用template模块下发可变的配置文件
- [root@localhost scripts]# cat /tmp/test
- my name is {{ myname }} #自定义变量
- my name is {{ ansible_all_ipv4_addresses[0] }} #系统变量
- [root@localhost scripts]# cat test_filevars.yaml
- ---
- - hosts: all
- gather_facts: True #开启系统变量
- vars:
- - myname: "yunjisuan" #自定义变量
- tasks:
- - name: template test
- template: src=/tmp/test dest=/root/test #使用template下发可变配置文件
- [root@localhost scripts]# ansible-playbook test_filevars.yaml
2、下发配置文件里面使用判断语法
- [root@localhost scripts]# cat /tmp/if.j2
- {% if PORT %} #if PORT存在
- ip=0.0.0.0:{{ PORT }}
- {% else %} #否则的话
- ip=0.0.0.0:80
- {% endif %} #结尾
- [root@localhost scripts]# cat test_ifvars.yaml
- ---
- - hosts: all
- gather_facts: True #开启系统内置变量
- vars:
- - PORT: 90 #自定义变量
- tasks:
- - name: jinja2 if test
- template: src=/tmp/if.j2 dest=/root/test
- [root@localhost scripts]# ansible-playbook test_ifvars.yaml
如果我们将变量PORT值为空的话,就会是另外的结果
- [root@localhost scripts]# cat test_ifvars.yaml
- ---
- - hosts: all
- gather_facts: True
- vars:
- - PORT: #置空
- tasks:
- - name: jinja2 if test
- template: src=/tmp/if.j2 dest=/root/test
- [root@localhost scripts]# ansible-playbook test_ifvars.yaml
四、Playbook的notify通知和下发nginx配置
- #实战下发可执行动作的可变的nginx配置文件
- [root@localhost scripts]# head -1 /tmp/nginx.j2
- worker_processes {{ ansible_processor_count }}; #可变的参数
- [root@localhost scripts]# cat test_nginxvars.yaml
- ---
- - hosts: all
- gather_facts: True #开启系统内置变量
- tasks:
- - name: nginx conf
- template: src=/tmp/nginx.j2 dest=/usr/local/nginx/conf/nginx.conf
- notify:
- - reload nginx #下发通知给handlers模块执行名字叫做reload nginx的动作
- handlers: #定义动作
- - name: reload nginx #动作的名字
- shell: /usr/local/nginx/sbin/nginx -s reload
- [root@localhost scripts]# ansible-playbook test_nginxvars.yaml
关于Centos7安装配置ansible运维自动化工具和centos7 ansible的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于ansible 自动化运维工具 9 (ansible角色的安装及使用)、Ansible 运维自动化、Ansible 运维自动化 ( 配置管理工具 )、Ansible运维自动化的相关知识,请在本站寻找。
本文标签: