简体   繁体   English

Ansible Playbook运行Shell命令

[英]Ansible Playbook to run Shell commands

I recently dived into Ansible for one of my servers, and found it really interesting and time saving. 我最近潜入了Ansible的一台服务器,发现它真的很有趣,省时省力。 I am running an Ubuntu dedicated server and have configured number of web applications written on Python and a few on PHP. 我正在运行一个Ubuntu专用服务器,并配置了许多用Python编写的Web应用程序和一些用PHP编写的Web应用程序。 For Python I am using uwsgi as the HTTP gateway. 对于Python,我使用uwsgi作为HTTP网关。 I have written shell scripts to start/restart a few processes in order to run the instance of a specific web application. 我编写了shell脚本来启动/重启几个进程,以便运行特定Web应用程序的实例。 What I have to do everytime is, connect ssh and navigate to that specific application and run the script. 我每次都要做的是,连接ssh并导航到该特定应用程序并运行脚本。

WHAT I NEED 我需要的

I've been trying to find a way to write Ansible playbook to do all that from my personal computer with one line of command, but I have no clue how to do that. 我一直试图找到一种方法来编写Ansible playbook,用一行命令从我的个人计算机上做所有这些,但我不知道如何做到这一点。 I have'nt found a very explanatory (for a beginner) documentation or help on the internet. 我没有在互联网上找到一个非常解释性的(初学者)文档或帮助。

QUESTION

How can I restart Nginx with Ansible playbook? 如何使用Ansible playbook重新启动Nginx? How can I kill a process by process id? 如何通过进程ID杀死进程?

You don't even need a playbook to do this : 你甚至不需要一本剧本来做到这一点:

  • Restarting nginx : 重启nginx:

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

(see service module ) (见服务模块

  • Kill a process by process id 按进程ID终止进程

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

(adjust signal, and use pkill/killall if you need to match a name; see command module ) (调整信号,如果需要匹配名称,请使用pkill / killall;参见命令模块

However, I wouldn't say that ansible shines if you're just using it for ad-hoc commands. 但是,如果您只是将它用于ad-hoc命令,我不会说ansible会发光。

If you need a tutorial to get you started with playbooks, there is one over here . 如果你需要一个教程来开始使用playbooks,那么这里有一个。

Now if you can to put these (the official name for service, commands, etc.. are modules ) in a playbook (let's call it playbook.yml), you can just : 现在,如果您可以将这些(服务的正式名称,命令等等都是模块 )放在一个剧本中(我们称之为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

Create an inventory file ( hosts ) containing : 创建包含以下内容的清单文件( hosts ):

# webappserver should resolve !
webappserver

Invoke with : 调用:

ansible playbook.yml -i hosts

and it should work. 它应该工作。

This is all very basic and can be grasped easily reading the docs or any tutorial out there. 这一切都非常基础,可以轻松阅读文档或任何教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM