Category: Ops

  • ansible jinja2模板使用

    在j2中可以很方便的使用 ansible setup 模块中的变量

    如以下是一个bind的配置文件

      {% if ansible_bond0.ipv4.address %}
      bind {{ ansible_bond0.ipv4.address }}
      {% elif ansible_eth0.ipv4.address %}
      bind {{ ansible_eth0.ipv4.address }}
      {% else %}
      bind 0.0.0.0
      {% endif %}
    

    以下是一个snmp磁盘分区的设定

    {% for i in ansible_mounts %}
    {% if i['mount']  != '/boot' %}
    disk {{ i['mount'] }} 10% 
    {% endif %}
    {% endfor %}
  • ansible中的变量

    用ansible也有一段时间了,在使用模板和写playbook的时候变量很重要,整理一些常用的变量。

    #写到hosts文件中的主机名

    inventory_hostname

    ansible自带的setup模块检测出来的变量都可以直接使用,写几个常用的

    #系统发行分支

    ansible_distribution

    # 主机名

    ansible_hostname

    # 所有的cpu

    ansible_processor

    # 硬件型号

    ansible_product_name

    # 系统时间,会是一组不同方式表示的值

    ansible_date_time

    主机的fqdn,即 hostname -f ,得到的方法是

    ansible_fqdn
    python -c "import socket; print socket.gethostname()"
    python -c "import socket; print socket.gethostbyaddr('whatever_we_got_from_last_command')"

    主机名即 hostname

    ansible_nodename
    python -c "import platform; print platform.node()"

    item变量,配合with_items使用

    - name: install rpms
    yum: name={{ item }} disable_gpg_check=yes state=present
    
    with_items:
    - gcc
    - zlib
    

    #eth0的值

     ansible_eth0.ipv4.address
  • ansible-fetch获取服务器上的文件

    目标是获取两台服务器下root,www用户的crontab文件,并保存在本地的fetched目录。

    main.yml文件如下

    – hosts: all
    tasks:
    – fetch: src=/var/spool/cron/www dest=fetched/cron-www-{{ ansible_hostname }} flat=yes

    – fetch: src=/var/spool/cron/root dest=fetched/cron-root-{{ ansible_hostname }} flat=yes

    执行完之后的目录结构如下

    [[email protected] fetch-crontab]# tree
    .
    ├── fetched
    │   ├── cron-root-2.jpuyy.com
    │   └── cron-www-1.jpuyy.com
    ├── hosts
    └── main.yml

  • 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