Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.



Note

未经允许不得转载

Info
iconfalse

Table of Contents
maxLevel2



定义主机和主机组

在默认的 Inventory 文件中定义主机和主机组:

Code Block
languagebash
linenumberstrue
10.0.0.4  ansible_ssh_pass='password'
10.0.0.7  ansible_ssh_pass='password'
[docker]
10.0.0.10[1:3]
[docker:vars]
ansible_ssh_pass='password'
[ansible:children]
docker

说明:

  • 第一行与第二行,定义了主机 IP ,然后使用 Inventory 内置变量定义了 SSH 登入密码。
  • 第三行定义了一个组叫 docker。
  • 第四行定义了 docker 组下面 3 台主机从 10.0.0.101 ~ 10.0.0.103 。
  • 第五行与第六行针对 docker 组使用 Inventory 内置变量定义 SSH 登入密码。
  • 第七行与第八行定义了一个组 ansible,这个组下面包含 docker 组。

如果出现以下错误,则需要安装 sshpass:

Code Block
languagebash
172.17.0.5 | FAILED! => {"msg": "to use the 'ssh' connection type with passwords, you must install the sshpass program"}

安装系统程序:

Code Block
languagebash
$ apt install sshpass

定义一组 Inventory 表

默认的 Inventory 是使用对应单个文件的,在 ansible.cfg 配置文件中:

它只对应了 /etc/ansible/hosts 这个文件而不是目录,可以使用目录来进行主机组的管理,首先把修改 Inventory 的配置:

Code Block
languagebash
inventory = /root/inventory

在对应目录里面分类管理服务名称:

Code Block
languagebash
$ mkdir /root/inventory
$ cat > /root/inventory/hosts << EOF
10.0.0.4  ansible_ssh_pass='password'
10.0.0.7  ansible_ssh_pass='password'
EOF
$ cat > /root/inventory/docker << EOF
[docker]
10.0.0.10[1:3]
[docker:vars]
ansible_ssh_pass='password'
[ansible:children]
docker
EOF

查阅目录:

Code Block
languagebash
$ tree /root/inventory
/root/inventory
├── docker
└── hosts

进行验证:

Code Block
languagebash
$ ansible 10.0.0.4:10.0.0.7 --list-hosts
10.0.0.4
10.0.0.7
$ ansible docker --list-hosts
10.0.0.101
10.0.0.102
10.0.0.103
$ ...

Inventory 内置参数

Code Block
languagebash
ansible_ssh_host
      将要连接的远程主机名.与你想要设定的主机的别名不同的话,可通过此变量设置.

ansible_ssh_port
      ssh端口号.如果不是默认的端口号,通过此变量设置.

ansible_ssh_user
      默认的 ssh 用户名

ansible_ssh_pass
      ssh 密码(这种方式并不安全,我们强烈建议使用 --ask-pass 或 SSH 密钥)

ansible_sudo_pass
      sudo 密码(这种方式并不安全,我们强烈建议使用 --ask-sudo-pass)

ansible_sudo_exe (new in version 1.8)
      sudo 命令路径(适用于1.8及以上版本)

ansible_connection
      与主机的连接类型.比如:local, ssh 或者 paramiko. Ansible 1.2 以前默认使用 paramiko.1.2 以后默认使用 'smart','smart' 方式会根据是否支持 ControlPersist, 来判断'ssh' 方式是否可行.

ansible_ssh_private_key_file
      ssh 使用的私钥文件.适用于有多个密钥,而你不想使用 SSH 代理的情况.

ansible_shell_type
      目标系统的shell类型.默认情况下,命令的执行使用 'sh' 语法,可设置为 'csh' 或 'fish'.

ansible_python_interpreter
      目标主机的 python 路径.适用于的情况: 系统中有多个 Python, 或者命令路径不是"/usr/bin/python",比如  \*BSD, 或者 /usr/bin/python
      不是 2.X 版本的 Python.我们不使用 "/usr/bin/env" 机制,因为这要求远程用户的路径设置正确,且要求 "python" 可执行程序名不可为 python以外的名字(实际有可能名为python26).

      与 ansible_python_interpreter 的工作方式相同,可设定如 ruby 或 perl 的路径....

Windows

Windows 的配置如下:

Code Block
languagebash
[win]
10.0.1.11 ansible_ssh_user="Administrator" ansible_ssh_pass="pass" ansible_ssh_port=5985 ansible_connection="winrm" ansible_winrm_server_cert_validation=ignore