ansible企业实战

ansible最佳实践

优化ansible速度
开启SSH长连接

修改 /etc/ansible/ansible.cfg里面的参数

ssh_args = -C -o ControlMaster=auto -o ControlPersist=5d

ControlPersist=5d这个参数是设置整个长连接保持时间设置为5天,如果开启,通过SSH连接过的设备都会在/ansible/cp目录下生成一个socket文件

开启pipelining

修改 /etc/ansible/ansible.cfg里面的参数pipelining=True

pipelining=True

需要修改被控制主机的/etc/sudoers

sed -i '/Defaults.*requiretty/a\Defaults:\ test\ !requiretty' /etc/sudoers #添加用户test !requiretty
sed -i "$a Defaults\:\ test\ \!requiretty" /etc/sudoers   #添加用户test !requiretty
编辑当前SSH用户配置为requiretty
开启ansible加速模式accelerate
1)  需要开启时首先要在远端机器安装 python-keyczar软件包
2)  需要在ansible-playbook的剧本文件中加入 accelerate: true
还需加入:

[accelerate]
accelerate_port = 5099
accelerate_timeout = 30
accelerate_connect_timeout = 5.0
设置facts缓存
1)需要在ansible-playbook的剧本文件中加入 gather_facts: False  #可以直接关闭facts不收集远程主机信息

2)设置facts缓存: /etc/ansible/ansible.cfg

     第一种方式:使用文件缓存

     gathering = smart
     facts_caching_timeout = 86400  #  设置缓存过期时间86400秒
     facts_caching = jsonfile              #  cache文件是json格式
     facts_caching_connection = /tmp/ansible/ansible_facts_cache   #缓存文件的存储路径
	 
     第二种方式:使用redis存储facts文件需安装redis;yum install redis ;还需要安装pip install redis的python库
     gathering = smart
     facts_caching_timeout = 86400  #  设置缓存过期时间86400秒
     facts_caching = redis              # 使用redis          或者        facts_caching = memcached              #使用memcached
     #查看redis存储情况
        redis-cli               #登陆redis
        keyd *                 #找到所有键
        select 0              #切换库
        get   键的名字    #查看值

常用模块

  1. ping 模块: 检查指定节点机器是否还能连通,用法很简单,不涉及参数,主机如果在线,则回复pong 。
  2. raw 模块: 执行原始的命令,而不是通过模块子系统。
  3. yum 模块: RedHat和CentOS的软件包安装和管理工具。
  4. apt 模块: Ubuntu/Debian的软件包安装和管理工具。
  5. pip 模块 : 用于管理Python库依赖项,为了使用pip模块,必须提供参数name或者requirements。
  6. synchronize 模块: 使用rsync同步文件,将主控方目录推送到指定节点的目录下。
  7. template 模块: 基于模板方式生成一个文件复制到远程主机(template使用Jinjia2格式作为文件模版,进行文档内变量的替换的模块。
  8. copy 模块: 在远程主机执行复制操作文件。
  9. user 模块 与 group 模块: user模块是请求的是useradd, userdel, usermod三个指令,goup模块请求的是groupadd, groupdel, groupmod 三个指令。
  10. service 或 systemd 模块: 用于管理远程主机的服务。
  11. get_url 模块: 该模块主要用于从http、ftp、https服务器上下载文件(类似于wget)。
  12. fetch 模块: 它用于从远程机器获取文件,并将其本地存储在由主机名组织的文件树中。
  13. file 模块: 主要用于远程主机上的文件操作。
  14. lineinfile 模块: 远程主机上的文件编辑模块
  15. unarchive模块: 用于解压文件。
  16. command模块 和 shell模块: 用于在各被管理节点运行指定的命令. shell和command的区别:shell模块可以特殊字符,而command是不支持
  17. hostname模块: 修改远程主机名的模块。
  18. script模块: 在远程主机上执行主控端的脚本,相当于scp+shell组合。
  19. stat模块: 获取远程文件的状态信息,包括atime,ctime,mtime,md5,uid,gid等信息。
  20. cron模块: 远程主机crontab配置。
  21. mount模块: 挂载文件系统。
  22. find模块: 帮助在被管理主机中查找符合条件的文件,就像 find 命令一样。
  23. selinux模块:远程管理受控节点的selinux的模块

环境变量

环境变量不生效

ansible-playbook register

---- hosts: all
  gather_facts: no
  tasks:
    - name: register vars
      shell: hostname
      register: info
    - name: display vars
      debug: msg="{{info.stdout}}"
     - shell: "uptime | awk '{print $5}' | awk -F',' '{print $1}'"
       register: temp_var 
     - shell: "echo {{ temp_var.stdout_lines[0] }} >> /tmp/test.txt"

高版本兼容

版本内容

[root@l-opsmanager1 ~]# ansible --version
ansible 2.9.6
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Aug  7 2019, 00:51:29) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]
  
[root@l-opsmanager1 ~]# ansible-playbook --version
ansible-playbook 2.9.6
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible-playbook
  python version = 2.7.5 (default, Aug  7 2019, 00:51:29) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]

ansible-playbook参数变化: -s参数变化
ansible-playbook 1.9.6
  -S, --su              run operations with su (deprecated, use become)
  -R SU_USER, --su-user=SU_USER
                        run operations with su as this user (default=root)
                        (deprecated, use become)
  -s, --sudo            run operations with sudo (nopasswd) (deprecated, use
                        become)
  -U SUDO_USER, --sudo-user=SUDO_USER
                        desired sudo user (default=root) (deprecated, use
                        become)
ansible-playbook 2.9.6参数
Privilege Escalation Options:
  control how and which user you become as on target hosts

  --become-method BECOME_METHOD
                        privilege escalation method to use (default=sudo), use
                        `ansible-doc -t become -l` to list valid choices.
  --become-user BECOME_USER
                        run operations as this user (default=root)
  -K, --ask-become-pass
                        ask for privilege escalation password
  -b, --become          run operations with become (does not imply password
                        prompting)

范例
ansible-playbook 1.9.6

ansible-playbook -u root -k -s

ansible-playbook 2.9.6
Invalid characters were found in group names but not replaced, use -vvvv to see details
解决办法
pip install -i https://pypi.douban.com/simple --upgrade pip
pip install -i https://pypi.douban.com/simple  --upgrade setuptools
pip install -i https://pypi.douban.com/simple  chardet
pip install -i https://pypi.douban.com/simple urllib3
高版本 include_tasks替代了include
[WARNING]: While constructing a mapping from /data/ansible/playbooks/account/db/users.yml, line 2, column 3, found a duplicate dict key (dev). Using last defined value
only.
with_dict 变化: 值必须要 “{{}}” 这么处理
注意上面with_dict所提供的变量,使用引号包围起来。 如果直接写with_dict: files,会报"msg": "with_dict expects a dict", ansible版本2.6.x。对于1.9之前版本的应该可以。
key变化 相同/不同等级也不能有相同的key
[WARNING]: While constructing a mapping from /data/ansible/playbooks/account/db/users.yml, line 2, column 3, found a duplicate dict key (dev). Using last defined value
only.
group名 不能出现中横杆"-",警告如下
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
shell/command模块使用rm 会有警告信息,如下
[WARNING]: Consider using the file module with state=absent rather than running 'rm'.  If you need to use command because file is insufficient you can add 'warn: false'
to this command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.

官网地址:
https://docs.ansible.com/ansible/latest/modules/shell_module.html#shell-module

范例
- name: rm -f repo
  shell: "rm -f $(find /etc/yum.repos.d/ -name '*.repo')"
  args:
    warn: no
主机组名
Invalid characters were found in group names but not replaced

警告如下

[DEPRECATION WARNING]: The TRANSFORM_INVALID_GROUP_CHARS settings is set to allow bad characters in group names by default, this will change, but still be user configurable on deprecation. This feature will be removed
 in version 2.10. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
主机组名 规范: 主机名内不能包含中横杆"-"

需要将 [bj4-k8s] 变更为 [bj4_k8s]

yum模块变更

原来的配置

- name: Install the monitor item dependency package
  yum:
    name: "{{ item }}"
    state: latest
  with_items:
    - 'sysstat'
    - 'php-cli'
    - 'php-mysql'

警告信息如下

[DEPRECATION WARNING]: Invoking "yum" only once while using a loop via squash_actions is deprecated. Instead of using a loop to supply multiple items and specifying `name: "{{ item }}"`, please use `name: 
['sysstat', 'php-cli', 'php-mysql']` and remove the loop. This feature will be removed in version 2.11. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.

解决办法

- name: Install the monitor item dependency package
  yum:
    name: ['sysstat', 'php-cli', 'php-mysql']
    state: latest

内置变量
获取主机组的长度
- debug: msg={{ groups['ops'] | length }}
获取
{{ hostvars[groups['webservers'][0]]['ansible_eth0']['ipv4']['address'] }} 
ansible playbook Loops

loops循环使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值