Ansible:重启失败apache2.service:连接超时

Ansible: Failed to restart apache2.service: Connection timed out

我正在使用 Ansible AWX 发出重启命令以重启主机上的 apache2 服务。 restart 命令包含在剧本中。

---
- name: Manage Linux Services
  hosts: all
  tasks:
  - name: Restart a linux service
    command: systemctl restart '{{ service_name }}'
    register: result
    ignore_errors: yes

  - name: Show result of task
    debug:
     var: result

---
- name: Manage Linux Services
  hosts: all
  tasks:
  - name: Restart a linux service
    ansible.builtin.service:
      name: '{{ service_name }}'
      state: restarted
    register: result
    ignore_errors: yes

  - name: Show result of task
    debug:
     var: result

但是,当我 运行 命令时,出现以下错误:

"Failed to restart apache2.service: Connection timed out",
"See system logs and 'systemctl status apache2.service' for details."

我试图找出问题所在,但还没有成功。

后来我想出了问题的原因。

这是我修复它的方法:

重新启动命令需要 sudo 访问 运行,而我的命令中没有。

我所要做的就是添加become: true命令,这样我就可以以root权限执行命令。

所以我的剧本之后看起来像这样:

---
- name: Manage Linux Services
  hosts: all
  tasks:
  - name: Restart a linux service
    command: systemctl restart '{{ service_name }}'
    become: true
    register: result
    ignore_errors: yes

  - name: Show result of task
    debug:
     var: result

---
- name: Manage Linux Services
  hosts: all
  tasks:
  - name: Restart a linux service
    ansible.builtin.service:
      name: '{{ service_name }}'
      state: restarted
    become: true
    register: result
    ignore_errors: yes

  - name: Show result of task
    debug:
     var: result

如果您想在 Ansible AWX 上实现此目的,另一种方法是勾选作业模板中的 权限升级 选项。

如果启用,这 运行 作为管理员在作业模板中选择的剧本。

就这些了。

希望对您有所帮助

重新启动服务需要 sudo 权限。除了添加 'become' 指令外,如果你想提示输入密码,你可以通过传递 -K 标志(注意: 大写 K)

$ ansible-playbook myplay.yml -i hosts -u myname --ask-pass -K