Ansible Playbook运行Shell命令

Rai*_*ham 10 shell nginx uwsgi ansible ansible-playbook

我最近潜入了Ansible的一台服务器,发现它真的很有趣,省时省力.我正在运行一个Ubuntu专用服务器,并配置了许多用Python编写的Web应用程序和一些用PHP编写的Web应用程序.对于Python,我使用uwsgi作为HTTP网关.我编写了shell脚本来启动/重启几个进程,以便运行特定Web应用程序的实例.我每次都要做的是,连接ssh并导航到该特定应用程序并运行脚本.

我需要的

我一直试图找到一种方法来编写Ansible playbook,用一行命令从我的个人计算机上做所有这些,但我不知道如何做到这一点.我没有在互联网上找到一个非常解释性的(初学者)文档或帮助.

如何使用Ansible playbook重新启动Nginx?如何通过进程ID杀死进程?

leu*_*cos 13

你甚至不需要一本剧本来做到这一点:

  • 重启nginx:

ansible your_host -m service -a 'name=nginx state=restarted'

(见服务模块)

  • 按进程ID终止进程

ansible your_host -m command -a 'kill -TERM your_pid'

(调整信号,如果需要匹配名称,请使用pkill/killall;参见命令模块)

但是,如果您只是将它用于ad-hoc命令,我不会说ansible会发光.

如果你需要一个教程来开始使用playbooks,那么这里有一个.

现在,如果您可以将这些(服务的官方名称,命令等等都是模块)放在剧本中(我们称之为playbook.yml),您可以:

- hosts: webappserver
  tasks:
    - name: Stops whatever
      command: kill -TERM your_pid
      notify:
        - Restart nginx

    - name: Another task
      command: echo "Do whatever you want to"

  handlers:
    - name: Restart nginx
      service: name=nginx state=restarted
Run Code Online (Sandbox Code Playgroud)

创建hosts包含以下内容的库存文件():

# webappserver should resolve !
webappserver
Run Code Online (Sandbox Code Playgroud)

调用:

ansible playbook.yml -i hosts
Run Code Online (Sandbox Code Playgroud)

它应该工作.

这一切都非常基础,可以轻松阅读文档或任何教程.