Ansible教程

Ansible Shell

Ansible Shell

Ansible shell 模块旨在针对基于 UNIX 的目标主机执行 shell 命令。 Ansible 可以运行,除了任何带有管道、重定向的复杂命令。并且您还可以使用 Ansible shell 模块执行 shell 脚本。
Ansible shell 的主要优点是除了任何带有管道和分号的复杂命令从安全角度来看都是一个缺点,因为它是一个单一的错误可能会花费很多并破坏系统完整性。
Ansible shell 模块仅适用于基于 LINUX 的机器,不适用于 Windows。对于 Windows,您应该使用 win_shell Ansible shell 模块可用于执行 shell 脚本。 Ansible 有一个名为 script 的专用模块,用于将 shell 脚本从中控机复制到远程服务器。
让我们看看如何在剧本和 Adhoc 中使用 Ansible shell 模块的语法:

剧本中 Ansible shell 模块的语法

剧本的美妙之处在于它的外观和书写方式。剧本是用 YAML 编写的,因此易于理解。
下图演示了如何将 Adhoc 命令转换为 Ansible 剧本的剧本。
Ansible Shell

Adhoc 中 Ansible shell 模块的语法

下图以 Adhoc 方式显示了 Ansible shell 模块的快速语法。
Ansible Shell

示例

使用 Shell 或命令模块在单个任务中执行单个命令。假设您想获取远程服务器的日期。远程服务器在名称为 testservers 的主机组下。
第 1 步: 登录 Ansible 服务器。
第 2 步: 下面是一个使用以下命令执行单个命令的示例远程主机中的 Shell 模块。
---
-name: Shell command example 
Hosts: testservers
tasks:
-name: check date with the shell command
shell:
"date"
register: datecmd
tags: datecmd
-debug: msg= "{{datecmd.stdout}}"
在上面的示例中,我们针对名为 testservers 的主机组运行我们的 playbook,并执行一个简单的 date 命令并将该命令的输出保存到 Register 变量中名为 datecmd。
在最后一行,我们检索注册的变量并仅打印存储在 的 stdout 属性中的日期命令输出datecmd.

示例2: 在单个shell 中执行多个命令:

Shell 可以在单个shell 播放中同时接受各种命令。此外,您可以使用 Ansible shell 模块编写 shell 脚本。
在下面的示例中,我们将一些 shell 命令分组以执行受控且干净的 tomcat 重启。
剧本是旨在按顺序执行以下步骤,例如:
停止 tomcatServer 清除缓存 截断日志文件 启动实例
---
 -name: Shell Examples
    hosts: testservers
    tasks:
   -name: Clear Cache and Restart tomcat
      become: yes
      delay: 10
      async: 10
      poll: 50
      shell: |
        echo-e "\n Change directory to the Tomcat"
        cd tomcat8/
        echo-e "\n Present working directory is" `pwd`
        
        echo-e "\n Stopping the tomcat instance"
        bin/shutdown.sh
        echo-e "\n Clearning the tmp and work directory of tomcat"
        rm-rfv tmp/*
        rm-rfv work/*
        echo-e "\nTruncate the log file"
        > logs/catalina.out
        echo-e "\nDirectory listing"
        ls-lrtd logs/catalina.out
        echo-e "\nStarting the instance"
        bin/startup.sh    
      args:
        chdir: "/apps/tomcat/"
      register: fileout
      tags: fileout 
   -debug: msg="{{ fileout.stdout_lines }}"
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4