个性化阅读
专注于IT技术分析

ansible命令模块用法

点击下载

本文概述

Ansible命令模块用于在远程目标计算机上运行任何命令或运行任何脚本。或用于在远程节点上执行命令。

命令模块用于在远程节点或服务器上运行简单的Linux命令,该节点或服务器是主机组中提到的主机组或独立服务器的一部分。

Ansible命令模块和Shell模块

当我们需要在你选择的shell中在远程服务器中执行命令时,将使用shell模块。默认情况下,这些命令在/ bin / sh shell上运行。你可以使用各种操作,例如’|’,'<‘,’>’等,以及环境变量,例如$ HOME。

命令模块不会通过外壳处理命令。因此它不支持上述操作。

与在UNIX shell上提供命令的方式相同,你要提供要执行的命令,命令名称后跟参数。

- name: Executing a command using the shell module 
  shell: ls -lrt > temp.txt

第一个命令列出当前文件夹中的所有文件,并将其写入文件temp.txt。

- name: Executing a command using the command module
  command: hello.txt

上面的示例显示hello.txt文件的内容。

更改默认目录

该命令将始终在默认目录中执行。你可以使用chdir参数更改并指定要在其中运行命令的目录路径。此参数可用于命令和外壳模块。

你还可以通过在可执行参数中指定require Shell的绝对路径来更改默认Shell。

- - hosts: loc
  tasks:
  - name: ansible command with chdir and executable parameters
    command: ls -lrt
    args:
      chdir: /home/Ansible/command_chdir_example
      executable: /bin/bash

在上面的示例中,通过给过时的路径/ bin / bash使用“ Bourne Again Shell”。并将目录更改为/ home / Ansible / command_chdir_example。

执行多个命令

如果需要运行多个命令,则可以使用“ with_items”将它们分配给Shell和命令模块。

范例1:

- hosts: loc 
  tasks: 
  - name: Ansible command module multiple commands 
    command: "touch {{ item }}"
    with_items: 
      - hello.txt 
      - hello1.txt 
      - hello2.txt 
    args: chdir: /root/ansible

范例2:

- hosts: loc
  tasks:
  - name: Ansible shell module multiple commands
    shell: "cat {{ item }} | grep ansible"
    with_items:
      - hello.txt
      - hello1.txt
      - hello2.txt
    args:
      chdir: /root/ansible

在上面的示例中,我们要执行三个文件。 hello.txt,hello1.txt和hello2.txt。由于我在命令中输入了{{item}}关键字,因此在每次迭代中它将被列表中的元素替换。确保“ with_item”的缩进级别与模块名称处于同一级别。


赞(0)
未经允许不得转载:srcmini » ansible命令模块用法

评论 抢沙发

评论前必须登录!