如何将 ansible playbook 作为 cron 作业运行?

问题描述

我是一个新的 ansible 用户。我想将 ansible playbook 用作 cron 作业,即在特定日期/日期运行 ansible-playbook site.yml 命令。我使用 crontab -e 设置了命令,这似乎工作正常。

不幸的是,我收到以下错误:

fatal: [localhost]: FAILED! => {
  "ansible_facts": {},  "changed": false,  "failed_modules": {
    "ansible.legacy.setup": {
      "cmd": "sysctl hw.model",      "failed": true,      "invocation": {
        "module_args": {
          "fact_path": "/etc/ansible/facts.d",          "filter": "*",          "gather_subset": ["all"],          "gather_timeout": 10}},          "msg": "[Errno 2] No such file or directory: b'sysctl'","rc": 2
        }
      },      "msg": "The following modules failed to execute: ansible.legacy.setup"
    }

扩展错误堆栈:

PLAY [First Playbook] ansible.cfg inventory site.yml TASK [Gathering Facts] fatal: [localhost]: FAILED! => {"ansible_facts": {},"changed": false,"failed_modules": {"ansible.legacy.setup": {"cmd": "sysctl hw.model","failed": true,"invocation": {"module_args": {"fact_path": "/etc/ansible/facts.d","filter": "*","gather_subset": ["all"],"gather_timeout": 10}},"msg": "[Errno 2] No such file or directory: b'sysctl'","rc": 2}},"msg": "The following modules failed to execute: ansible.legacy.setup
"}  
localhost : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0

site.yaml 文件内容:

- name: First Playbook
  hosts: all
  tasks:
    - name: Debug
      debug:
        msg: "1 2"

库存文件内容:

---
all:
  hosts:
    localhost:
      ansible_connection: local
      ansible_python_interpreter: "/usr/local/bin/python3"

ansible.cfg 文件内容:

[defaults]
inventory=inventory

我使用的是 macOS。我使用 brew(不是 pip)安装了 ansible,我的目标是 localhost。

如果我对错误信息的理解是正确的,ansible 正在寻找默认的 fact.d 位置 /etc/ansible/facts.d。我尝试在项目目录中创建 ansible.cfg,但是 我不确定是否还需要创建和/或指定事实文件。

解决方法

这是因为从 cron 运行时,$PATH 没有更新为 sysctl 的路径。

要么在调用时指定 sysctl 二进制文件的完整路径,要么在 crontab 调用之前传递 $PATH 变量。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...