部署Ansible

中心: 配置ansible以管理主机和运行临时 ansible 命令

构建Ansible清单

定义清单文件

1 在清单文件中定义一批 ansible将要管理的主机

2 这些主机 可以分配到组中,进行集中管理, 组可以包含子组, 主机也可以写到多个组中

3 清单也可以设置 应用到它所定义的主机和组的变量

主机清单分为:静态主机清单 和 动态主机清单

静态主机清单:可以通过文本文件来定义

动态主机清单:需要使用外部信息 通过脚本或其他程序生成

静态清单是指定ansible目标受管控主机的文件,支持多种格式 INI 和 YAML 

静态清单文件:(可以写主机名或IP) 一个主机可以使用多个分组
db1.example.com db2.example.com
192.168.0.1 192.168.0.2

也可以写成分组

[db-server]

db1.example.com

db2.example.com

[web-server]

192.168.0.1

192.168.0.2

[all-nodes]

db1.example.com

db2.example.com

192.168.0.1

192.168.0.2

all (默认的主机组)包含了清单中明确列出的每一个主机

ungrouped  列出不属于主机分组中的

# ansible ungrouped --list-hosts

列出 webservers 分组中的主机有哪些

# ansible webservers --list-hosts

 

定义嵌套组:
[servers:children]
db-server
web-server
ftp-server
范围值:

[
START:END] db[1:10].example.com [a:f].example.com

192.168.[2:6].[0:255] 代表着 192.168.2.0到 192.168.6.255

验证分组:

# ansible  db-server --list-hosts

主配置文件中定义清单文件位置

/etc/ansible/ansible.cfg 

Ansible 本身没有服务的概念,所以配置文件修改立即生效

当有多个清单文件时,指明清单文件的位置

 --inventory 或者 -i 

  

inventory清单文件介绍

可以根据 /etc/ansible/ansible.cfg来写

[devops@workstationansible]$ vim ansible.cfg /etc/ansible/ansible.cfg -O
[defaults]
Inventory=/home/devops/ansible/inventory
remote_user=devops
roles_path=/home/devops/ansible/roles:/usr/share/ansible/roles

[privilege_escalation]
become=True
becomemethod=sudo
become_user=root
becomeaskpass=False

[devops@workstationansible]$vim inventory
[dev]
servera
[test]
serverb
[prod]
serverc
serverd
[webservers:children]
prod

一般情况都会定义不同的工作目录,在不同的工作目录中有 自己的 配置文件(ansible.cfg/inventory/playbook剧本文件)

运行临时命令:

直接使用ansible命令运行临时命令(测试/一次性)

ansible host-pattern -m module [-a 'modeule arguments'] [-i inventory]

host-pattern:  分组/all

module: 模块(强大的功能模块)

-a : 模块的参数(如:命令)

-i:指定静态清单位置

查询模块的用法:

列出系统上安装的模块

# ansible-doc -l      ( -l: list )

# ansible-doc $module (如:ansible-doc copy)  里面有对应的 模版 很人性化

- name: Another symbolic mode example, adding some permissions and removing others
  copy:
    src: /srv/myfiles/foo.conf
    dest: /etc/foo.conf
    owner: foo
    group: foo
    mode: u+rw,g-wx,o-rwx

Ansible 常用模块

command:默认的模块,不指定-m,使用command模块,命令执行不是通过shell执行,所以像 > | & 都是不能使用的(shell的内部命令不能执行)

  ansible all -m command -a "pwd" == ansible all -a "pwd"

shell: 执行被管理节点上的shell/python脚本

用法基本上和command模块一样,通过shell执行,所以shell模块可以执行任何命令,和本地执行是一样的

  ansible all -m command -a "set"    失败(set是shell的内部命令)

  ansible all -m shell -a "set"

 raw:管道(不常用)

script:在远程的主机执行控制节点上的shell/python脚本 

练习:

检查更改是否生效

# ansible all -m command -a "cat /etc/motd"

原文地址:https://www.cnblogs.com/leading-net/p/12891864.html