四、ansible各个模块组件介绍与使用

一、inventory模块

inventory文件中填写需要被管理主机与主机信息(逻辑上定义)。

默认inventory文件在:/etc/ansible/hosts

可以自定义 使用-i 选项指定inventory组件的文件位置。

配置invertoy文件

场景1

基于密码连接(方式1,主机+端口+密码)

固定的格式为:

  1. 主机 :在最前10.0.0.10
  2. 端口 :ansible_ssh_port=22
  3. 用户 :ansible_ssh_user=root
  4. 密码 ;ansible_ssh_pass=’123456’
  5. [webservers] :是项目名称

写法如下:

写法1(常用)

1
2
3
[webservers]
10.0.0.10 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass=’123456’
10.0.0.11 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass=’123456’

写法2

1
2
3
[webservers]
Web[1:2].oldboy.com ansible_ssh_pass=’123456’[webservers]
Web[1:2].oldboy.com ansible_ssh_pass=’123456’

写法3

1
2
3
4
[webservers]
Web[1:2].oldboy.com
[webservers:vars] # 意为把web....这个组设置为变量 连接时直接使用下方密码
ansible_ssh_pass=’123456’

演示:在刚才新建的项目下面新建自定义inventory清单

注:此种方法不是很安全不常用需要先给被控端安装python。

新建文件hosts

1
2
3
4
[fruit]
192.168.31.165 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='123'
#10.0.0.11 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='123'
~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/bin/bash
#python2.7.5安装
sudo apt update
sudo apt install -y build-essential zlib1g-dev libssl-dev \
libncurses5-dev libncursesw5-dev libreadline-dev libsqlite3-dev \
libgdbm-dev libdb5.3-dev libbz2-dev libffi-dev wget

cd /usr/src
sudo wget https://www.python.org/ftp/python/2.7.5/Python-2.7.5.tgz
sudo tar xzf Python-2.7.5.tgz
cd /usr/src/Python-2.7.5

sudo ./configure --prefix=/usr/local/python2.7.5
sudo make
sudo make install

/usr/local/python2.7.5/bin/python2.7 -V

sudo ln -s /usr/local/python2.7.5/bin/python2.7 /usr/local/bin/python2.7.5

python2.7.5