Category: Ansible

  • ansible 不 check host key

    初始化的时候,要批量用密码登一遍执行初始化,不想 check host key

    ANSIBLE_HOST_KEY_CHECKING=False ansible all -i my_inventory -m ping -k
    
    
  • ansible sed替换

    使用 shell 模块时,有时为了偷懒 lineinfile,用 sed 替换,涉及到使用 sed 自己变量时,会报错

    例:将最后一行注释掉

    ansible all -i 172.28.128.3, -m shell -a "sed -e '$s/^/#/g' /etc/hosts" -u vagrant -s
    172.28.128.3 | FAILED | rc=1 >>
    sed: -e expression #1, char 4: comments don't accept any addresses

    由于 $s 代表最后一行,需要转义一下

    ansible all -i 172.28.128.3, -m shell -a "sed -i '\$s/#//g' /etc/hosts" -u vagrant -s
  • ansible lineinfile 改文件某一行

    添加

    ansible all -i jpuyy-com-lan -m lineinfile -a "dest=/etc/hosts line='115.239.28.20 api.jpuyy.com'" -s

    删除

    ansible all -i jpuyy-com-lan -m lineinfile -a "dest=/etc/hosts line='115.239.28.20 api.jpuyy.com' state=absent" -s 

    更改某一行

    ansible all -i jpuyy-com-lan -m lineinfile -a "dest=/etc/env.yaml line='idc: sh' regexp='idc: qcloud'" -s
  • python打乱列表顺序

    主要用到了 random 的 shuffle 方法

    一个 resolv 的列表,每一次执行都输出不同的顺序

    #!/usr/bin/env python
    import random
    
    resolv_servers = ['192.168.1.1', '192.168.1.2', '192.168.1.3']
    random.shuffle(resolv_servers)
    print resolv_servers
    

    同样,ansible 的 jinja2 模板里,定义了 resolv_servers,在不同机器下发时输出不同的顺序,使多台服务器均衡。

    {% for server in resolv_servers|shuffle %}
     nameserver {{ server }}
     {% endfor %}
    
  • 使用 etcd 做为 ansible inventory 数据源

    etcd 文档

    https://coreos.com/etcd/docs/0.4.7/etcd-api/
    https://github.com/oreh/simpletcd

    结构

    hostvars/12.34.56.78/redis_maxmemory => 4GB
    hostvars/12.34.56.78/hostname => abc.jpuyy.com

    输出

    [abc.jpuyy.com]
    12.34.56.78

    对应的变量是 redis_maxmemory = 4GB

  • ansible script module

    如果需要 shell 执行一些任务,可以写个脚本,直接使用

    ansible all -i inventory.py -l 192.168.1.3 -m script -a show_ip.sh