![](/img/trans.png)
[英]Make ansible-playbook run the playbook for the given host only once
[英]How to get an Ansible check to run only once in a playbook?
為了防止使用過時的劇本,我想確保在 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"
問題是這個命令為 Ansible 連接的每個節點運行一次,而不是每個 playbook 運行只運行一次。 我怎樣才能避免這種情況?
當我開始寫我的答案 (2014-02-27) 時,Ansible 沒有內置支持每個劇本只運行一次任務,而不是每個運行劇本的受影響主機一次。 然而,正如tlo 所寫,在 Ansible 1.7.0 版(2014 年 8 月 6 日發布)中通過run_once: true
引入了run_once: true
支持。 使用此功能,問題中的示例任務定義應更改為
- 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"
完成所要求的事情。
[對於確保在 Ansible 運行劇本任務之前更新本地 git 分支的特定問題,以下答案是我建議的解決方案。]
我編寫了以下 Ansible 回調插件,如果當前 git 分支與遠程分支不同步(落后於或已經發散),它將避免劇本執行。 要使用它,請將以下代碼放入頂級 Ansible 劇本目錄中的callback_plugins/require_updated_git_branch.py
文件中:
#! /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)
例如,當本地分支在遠程分支后面時,命令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 |
|| ||
而且,正如牛建議的那樣,要關閉此檢查,您可以運行以下命令:
$ IGNORE_OUTDATED_GIT_BRANCH=yes ansible-playbook site.yml
此解決方案不能解決避免多次運行任何 Ansible 任務而不管所涉及的主機數量如何的一般問題,但它確保不執行過時的劇本,並且它處理了您提到的關於我的基於別名的建議的問題.
從 Ansible 1.7 版開始,您可以使用run_once: true
僅在一台主機上運行一次任務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.