首页 > 解决方案 > Ansible 模块停止和启动 `ssh` 服务

问题描述

问题:

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

为此,您必须停止并启动一个名为ssh.

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

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

笔记:

我的代码:

- hosts: localhost
  become: yes
  tasks:
  - name: Stop and Start ssh
    service:
      name: ssh
      state: "{{ item }}"
    with_items:
      - stopped
      - started

输出:

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   

问题:该服务在 Ansible 停止后已经在运行,看起来 sshd 从一开始就没有停止过。

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

标签: ansibleansible-inventory

解决方案


嗨 Vivek,欢迎来到社区!

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

以下代码应该可以工作:

- hosts: localhost
  become: yes
  tasks:
  - name: Stop and Start ssh
    service:
      name: ssh
      state: restarted

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


推荐阅读