Ansible 入门 2 (Ansible管理docker的容器)

Submitted by Lizhe on Tue, 06/06/2017 - 14:27

对于上一章节中我们提到的 /etc/ansible/hosts 配置文件可以通过 -i 参数指定, 如果不指定默认查找/etc/ansible/hosts 路径

ansible dockers -a "hostname"

等价于

ansible -i /etc/ansible/hosts dockers -a "hostname"

在这个hosts文件中还可以通过 ansible_ssh_host和ansible_ssh_port 单独指定目标机器的ip和端口

下面是这次的重点, 如果你需要多个hosts文件的话,你需要使用ansible.cfg文件

这个文件可以用来配置一些默认值

Ansible 按照如下 位置和顺序 来查找 ansible.cfg

1. ANSIBLE_CONFIG 环境变量指定的文件

2. ./ansible.cfg 当前工作目录下的文件

3. ~/.ansible.cfg 用户home路径下的文件

4. /etc/ansible/ansible.cfg 目录下的文件

这里我创建一个/ansible目录作为工作目录

[defaults]
inventory=/ansible/config/hosts
log_path=/ansible/log/ansible.log

然后在/ansible/config/hosts创建一个hosts文件

直接调用出现了错误

[root@vagrant ansible]# ansible dockers -a "hostname" 
Traceback (most recent call last):
  File "/usr/bin/ansible", line 36, in <module>
    from ansible.runner import Runner
  File "/usr/lib/python2.7/site-packages/ansible/runner/__init__.py", line 37, in <module>
    import ansible.inventory
  File "/usr/lib/python2.7/site-packages/ansible/inventory/__init__.py", line 26, in <module>
    from ansible.inventory.ini import InventoryParser
  File "/usr/lib/python2.7/site-packages/ansible/inventory/ini.py", line 21, in <module>
    from ansible.inventory.host import Host
  File "/usr/lib/python2.7/site-packages/ansible/inventory/host.py", line 19, in <module>
    from ansible import utils
  File "/usr/lib/python2.7/site-packages/ansible/utils/__init__.py", line 29, in <module>
    from ansible.utils.display_functions import *
  File "/usr/lib/python2.7/site-packages/ansible/utils/display_functions.py", line 22, in <module>
    from ansible.callbacks import display
  File "/usr/lib/python2.7/site-packages/ansible/callbacks.py", line 42, in <module>
    logging.basicConfig(filename=path, level=logging.DEBUG, format='%(asctime)s %(name)s %(message)s')
  File "/usr/lib64/python2.7/logging/__init__.py", line 1529, in basicConfig
    hdlr = FileHandler(filename, mode)
  File "/usr/lib64/python2.7/logging/__init__.py", line 902, in __init__
    StreamHandler.__init__(self, self._open())
  File "/usr/lib64/python2.7/logging/__init__.py", line 925, in _open
    stream = open(self.baseFilename, self.mode)
IOError: [Errno 2] No such file or directory: '/ansible/log/ansible.log'

原来这家伙笨到不会自己创建文件夹

mkdir /ansible/log 之后工作正常

243