用于停止和启动 `ssh` 服务的 Ansible 模块

VIV*_*AUR 6 ansible ansible-inventory

问题:

该场景用于解释Ansible中模块的使用。

为此,您必须停止并启动名为 的服务ssh

要完成的任务:- 在 fresco_module\tasks 文件夹中的 main.yml 文件中编写任务。

任务是停止和启动ssh使用 Ansible 中的服务模块命名的服务。

笔记:

  • 运行项目安装以安装提供给 ansible-playbook 的 ansible.mainplaybook.yml 文件。
  • 使用 localhost 作为 ansible-playbook 的清单。

我的代码:

- hosts: localhost
  become: yes
  tasks:
  - name: Stop and Start ssh
    service:
      name: ssh
      state: "{{ item }}"
    with_items:
      - stopped
      - started
Run Code Online (Sandbox Code Playgroud)

输出:

PLAY [localhost] *******************************************************************************

TASK [Gathering Facts] *************************************************************************
[DEPRECATION WARNING]: Distribution Ubuntu 16.04 on host localhost should use /usr/bin/python3,
 but is using /usr/bin/python for backward compatibility with prior Ansible releases. A future 
Ansible release will default to using the discovered platform python for this host. See 
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more 
information. This feature will be removed in version 2.12. Deprecation warnings can be disabled
 by setting deprecation_warnings=False in ansible.cfg.
ok: [localhost]

TASK [Stop and Start ssh] **********************************************************************
changed: [localhost] => (item=stopped)
ok: [localhost] => (item=started)

PLAY RECAP *************************************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
Run Code Online (Sandbox Code Playgroud)

问题:该服务在 Ansible 停止后已经在运行,看起来 sshd 从未停止过。

用于检查状态的命令:service ssh status。我也使用了这个命令,state:stopped但它sshd仍在运行。我已经面对这个问题很久了。我也尝试过state:restarted

小智 10

您好,Vivek,欢迎来到社区!

这应该是一件容易的事。您可以告诉 Ansible 直接重新启动服务,而无需通过两个单独的步骤停止和启动它。

以下代码应该可以工作:

- hosts: localhost
  become: yes
  tasks:
  - name: Stop and Start ssh
    service:
      name: ssh
      state: restarted
Run Code Online (Sandbox Code Playgroud)

这样 Ansible 可确保 ssh 服务已停止并启动 - 简而言之:重新启动。你甚至不需要with_items循环。