Category: Ansible

  • ansible tasks判断一个主机是不是在某group

    hosts文件里是这样写的

    [backup_tar]
    host1
    host2

    [backup_notar]
    host3
    host4

    针对 backup_tar 中的 hosts 只执行某条 task

    - cron: name="backup" minute=0 hour=4
            user="root" job="/bin/sh /root/mysql_backup.sh full >> /dev/null 2>&1" backup=yes
      when: inventory_hostname in groups['backup_tar']
    

    参考:https://groups.google.com/forum/#!topic/ansible-project/lr7nXyGw0UY

  • ansible直接通过ip操作机器

    如果要了解一两个 ip 的一些简单的情况如 ls -l /data0/ | wc -l,以前是要写到文件里的。

    ansible -i hosts all -m shell -a "ls -l /data0/ | wc -l"

    也可以这样,一台机器最后面要有一个逗号

    ansible all -i 192.168.1.1, -m shell -a "ls -l /data0/ | wc -l"

    两台机器用逗号隔开,并且不能有空格

    ansible all -i 192.168.1.1,192.168.1.2 -m shell -a "ls -l /data0/ | wc -l"

    参考: http://stackoverflow.com/questions/17188147/how-to-run-ansible-without-specifying-the-inventory-but-the-host-directly?answertab=votes#tab-top

    题外话:

    除了上面的 shell 模块,还有 command, script 可以在被管理机器上方便执行 shell.

    ansible all -i hosts -l 192.168.1.183 -m script -a uptime.sh
  • centos4机器被ansible管理

    使用 ansible 管理 centos4 的机器会报错, 默认安装的 python 是 2.3.4 ,需要在 centos4 上的机器添加 python2.7 的环境,以便于被 ansible 管理。

    下载安装

    wget http://python.org/ftp/python/2.7.5/Python-2.7.5.tgz --no-check-certificate
    tar xzf Python-2.7.5.tgz 
    cd Python-2.7.5
    ./configure --enable-shared
    make
    make altinstall

    接下来创建一个记录 python lib 目录的配置文件,/etc/ld.so.conf.d/python27.conf 里记录

    /usr/local/lib

    并用 ldconfig 加载到系统

    ldconfig -v -f /etc/ld.so.conf.d/python27.conf

    保证 yum 可用

    cp /usr/bin/python /usr/bin/python2.3.4
    vim /usr/bin/yum 第一行改为
    #!/usr/bin/python2.3.4
    

    系统级别

    ln -nfs /usr/local/bin/python2.7 /usr/bin/python

    参考:
    http://stivesso.blogspot.jp/2014/08/ansible-hosts-install-alternate.html

  • ansible添加公钥

    tasks:
    – name: Add RSA key to the remote host
    authorized_key: user=’root’ key=”{{ lookup(‘file’, ‘~/.ssh/id_rsa.pub’) }}”

  • ansible使用笔记-改主机名

    针对所有主机修改主机名

    - hosts: all
     hostname: name={{ hostname }}
  • python安装simplejson

    没有安装simplejson时报错

    >>> import simplejson

    Traceback (most recent call last):

      File “<stdin>”, line 1, in <module>

    ImportError: No module named simplejson

    simplejson是ansible一个很重要的依赖,经测试在python 2.4.3及以上版本都可以用python setup.py install 安装成功。

    方法一:

    yum install python-simplejson -y

    方法二:

    wget https://pypi.python.org/packages/source/s/simplejson/simplejson-3.5.2.tar.gz#md5=10ff73aa857b01472a51acb4848fcf8b --no-check-certificate
    tar vxzf simplejson-3.5.2.tar.gz
    cd simplejson-3.5.2
    python setup.py install

    方法三:

    pip install simplejson

    方法四:

    easy_install simplejson