为了防止使用过时的剧本,我想确保在Ansible被允许修改服务器上的任何内容之前我有一个git checkout的更新副本.
这就是我试图这样做的方式.此操作位于所有剧本包含的文件中:
- name: Ensure local git repository is up-to-date
local_action: git pull
register: command_result
failed_when: "'Updating' in command_result.stdout"
Run Code Online (Sandbox Code Playgroud)
问题是这个命令对Ansible连接的每个节点运行一次,而不是每个playbook运行一次.我怎么能避免这种情况?
Mar*_*ang 21
当我写下我的答案时(2014-02-27),Ansible没有内置支持每个剧本只运行一次任务,而不是每个受影响的主机运行该剧本.但是,正如tlo所写,run_once: true在Ansible版本1.7.0(2014-08-06发布)中引入了对此的支持.使用此功能,应将问题中的示例任务定义更改为
- name: Ensure local git repository is up-to-date
local_action: git pull
run_once: true
register: command_result
failed_when: "'Updating' in command_result.stdout"
Run Code Online (Sandbox Code Playgroud)
完成所要求的.
[以下答案是我建议的解决方案,用于确保在Ansible运行剧本任务之前更新本地git分支.]
我写了下面的Ansible回调插件,如果当前的git分支与远程分支不同步(落后或已经分歧),将避免播放本执行.要使用它,请将以下代码放在callback_plugins/require_updated_git_branch.py顶级Ansible playbook目录中的文件中:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import subprocess
import sys
from ansible.callbacks import display, banner
class CallbackModule(object):
"""Makes Ansible require that the current git branch is up to date.
"""
env_var_name = 'IGNORE_OUTDATED_GIT_BRANCH'
msg = 'OUTDATED GIT BRANCH: Your git branch is out of sync with the ' \
'remote branch. Please update your branch (git pull) before ' \
'continuing, or skip this test by setting the environment ' \
'variable {0}=yes.'.format(env_var_name)
out_of_sync_re = re.compile(r'Your branch (is behind|and .* have diverged)',
re.MULTILINE)
def __init__(self, *args, **kwargs):
if os.getenv(self.env_var_name, 'no') == 'yes':
self.disabled = True
def playbook_on_start(self):
subprocess.call(['git', 'fetch'])
if self.out_of_sync_re.search(subprocess.check_output([
'git', 'status', '--untracked-files=no'])):
display(banner(self.msg), color='bright purple')
sys.exit(1)
Run Code Online (Sandbox Code Playgroud)
例如,当本地分支位于远程分支后面时,命令会ansible-playbook site.yml提前停止,并显示以下输出:
__________________________________________________________
/ OUTDATED GIT BRANCH: Your git branch is out of sync with \
| the remote branch. Please update your branch (git pull) |
| before continuing, or skip this test by setting the |
\ environment variable IGNORE_OUTDATED_GIT_BRANCH=yes. /
----------------------------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
Run Code Online (Sandbox Code Playgroud)
并且,正如牛所建议的那样,要关闭此检查,您可以运行以下命令:
$ IGNORE_OUTDATED_GIT_BRANCH=yes ansible-playbook site.yml
Run Code Online (Sandbox Code Playgroud)
无论涉及多少主机,此解决方案都无法解决避免多次运行任何Ansible任务的一般问题,但它确保不会执行过时的Playbooks,并且它会处理您提到的有关基于别名的建议的问题.