Ansible:无法重新启动 apache2.service:连接超时

问题描述

我正在使用 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 上实现此目的,另一种方法是勾选作业模板中的权限提升选项。

enter image description here

如果启用,这将在作业模板中以管理员身份运行选定的剧本。

仅此而已。

我希望这会有所帮助