2016-04-13 42 views
0

我想通过避免调用某些不需要每天多次调用的部分来加速剧本的执行速度。如何使用可靠的事实来跳过某些部分的执行?

我知道事实应该可以让我们实现这一点,但似乎几乎不可能找到一些基本的例子:设置一个事实,阅读它并做某件事,如果它有一个特定的值,设置一个默认值为事实。

- name: "do system update" 
    shell: echo "did it!" 
- set_fact: 
    os_is_updated: true 

如果我的印象或事实无非是可以在执行之间保存,加载和缓存的变量吗?

我们假设帽子ansible.cfg已配置为启用事实缓存两个小时。

[defaults] 
gathering = smart 
fact_caching = jsonfile 
fact_caching_timeout = 7200 
fact_caching_connection = /tmp/facts_cache 

回答

0

由于其作为工作站CLI工具的性质,Ansible没有任何内置的持久性机制(几乎没有设计)。有一些事实缓存插件会使用外部存储(例如,Redis, jsonfile),但我通常不是粉丝。

如果您希望在目标机器上运行自己之间的东西,您可以将它们作为本地事实存储在/etc/ansible/facts.d中(如果您自己调用setup,则可以将它们存储为任意位置) ,他们会从ansible_local字典var下的gather_facts回来。假设你在* nix口味的平台上运行,是这样的:

- hosts: myhosts 
    tasks: 
    - name: do update no more than every 24h 
    shell: echo "doing updates..." 
    when: (lookup('pipe', 'date +%s') | int) - (ansible_local.last_update_run | default(0) | int) > 86400 
    register: update_result 

    - name: ensure /etc/ansible/facts.d exists 
    become: yes 
    file: 
     path: /etc/ansible/facts.d 
     state: directory 

    - name: persist last_update_run 
    become: yes 
    copy: 
     dest: /etc/ansible/facts.d/last_update_run.fact 
     content: "{{ lookup('pipe', 'date +%s') }}" 
    when: not update_result | skipped 

显然facts.d DIR存在的东西是建立样板,但我想告诉你一个完全正常的工作样本。

+0

对不起,如果我不清楚,但我认为我已经配置了缓存,所以我看到的是一个“如果x还没有在最近2小时内完成(缓存超时)的示例。 – sorin

+0

出于某种原因,set_fact显式不持久化到事实缓存(不知道为什么)。https://github.com/ansible/ansible/blob/26209342a28ad70775fa303035a12f4ff77c5f2e/lib/ansible/plugins/strategy/__init__.py#L328 – nitzmahone