• Post author:
  • Post category:ansible
  • Post comments:0评论

1、查找变量的优先顺序

    •  通过执行命令传递的变量
    •  在playbook中定义的vars_files
    •  在playbook中定义的vars变量
    •  在host_vars中定义变量
    •  在group_vars中定义的变量
        - 主机组
        - all
    •   主机清单中定义的变量

2、使用 redis 缓存facts 信息

  默认情况下,在使用 Ansible 对远程主机执行任何一个 playbook 之前,会先通过 setup 模块获取 facts信息,并暂存在内存中,直至该 playbook 执行结束。这意味着我们每执行一次都要去获取一次,而获取这么多数据是非常耗时的。
  而关闭facts信息收集,我们就不能在playbook中引用facts变量,所以这里使用redis缓存facts信息来解决这个问题。

[root@m1 ansible-role]# vim ansible.cfg
[defaults]
inventory = ./hosts

gathering = smart                                   //表示默认收集facts,但facts已有的情况下不会收集,即使用缓存facts;
fact_caching_timeout = 86400                        //缓存超时时间
fact_caching = redis                                //方式,还支持json文件、memcache方式等
fact_caching_connection = 127.0.0.1:6379            //连接地址

[root@m1 ansible-role]# curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py   //pip是Python包管理工具,该工具提供了对
[root@m1 ansible-role]# python get-pip.py                                         //Python包的查找、下载、安装、卸载的功能
[root@m1 ansible-role]# pip install redis           //安装python的redis模块

3、判断文件是否存在

- name: stat foo
  stat: path=/path/to/foo
  register: foo_stat

- name: Move foo to bar
  shell: mv /path/to/foo /path/to/bar
  when: foo_stat.stat.exists

4、获取循环中的任务结果的输出信息

[root@m1 test]# vim test2.yml
- hosts: test
  tasks:
    - name: shell
      shell: "{{ item }}"
      with_items:
        - "ls /opt"
        - "ls /home"
      register: re

    - name: get
      debug:
        msg: "{{item.stdout}}"
      with_items: "{{ re.results }}"

5、创建多重嵌套目录

[root@m1 test]# vim test3.yml
- hosts: test
  tasks:
    - name: Create multiple nested directories
      file:
        path: /root/test_dir/{{ item.0 }}/{{ item.1 }}
        state: directory
      with_cartesian:
        - [ test1, test2, test3, ]
        - [ a, b, ]

[root@test ~]# tree root
root [error opening dir]

0 directories, 0 files
[root@test ~]# tree /root
/root
└── test_dir
    ├── test1
    │   ├── a
    │   └── b
    ├── test2
    │   ├── a
    │   └── b
    └── test3
        ├── a
        └── b

发表回复

验证码: + 88 = 93