ansible常用模块之 -- command模块 -- 在目标上执行命令
command模块 – 在目标上执行命令
一、摘要
- command 模块接受命令名后面跟着一列以空格分隔的参数。
- 给定的命令将在所有选定的节点上执行。
- 命令不会通过shell进行处理,因此像 $HOME 这样的变量和像 “<”,“>”,“|”,“;” 和 “&” 这样的操作符将不起作用。如果需要这些特性,请使用shell模块。
- 要创建比使用空格分隔参数的命令任务更容易阅读的 command 任务,可以使用 args 任务关键字或 cmd 参数传递参数。
- 需要一个 free form 命令或 cmd 参数,参见示例。
- 对于Windows目标,请使用win_command模块。
二、参数
参数 | 选项/默认值 | 描述 |
---|---|---|
argv list | 以列表而不是字符串的形式传递命令。 使用argv可以避免引用可能被错误解释的值(例如“用户名”)。 只能提供字符串或列表形式,不能同时提供两者。必须提供其中之一。 | |
chdir path | 执行命令前,请切换到此目录。 | |
cmd string | 要运行的命令。 | |
creates path | 文件名或(从2.0开始)glob模式。如果它已经存在,则不会运行此步骤。 | |
free_form | 命令模块使用一个自由形式的命令来运行。 实际上没有名为“free form”的参数。 | |
removes path | 文件名或(从2.0开始)glob模式。如果它已经存在,将运行此步骤。 | |
stdin | 将命令的stdin直接设置为指定的值。 | |
stdin_add_newline boolean | · yes ← · no | 如果设置为yes,则向stdin数据追加换行符。 |
strip_empty_ends boolean | · yes ← · no | 从result中stdout/stderr的末尾剥离空行。 |
warn boolean | · yes ← · no | 启用或禁用任务警告。 |
三、示例
# 返回motd内容并将其注册到var
- name: return motd to registered var
command: cat /etc/motd
register: mymotd
# 如果/path/to/database不存在(不带'args'关键字),则执行命令。
- name: Run command if /path/to/database does not exist (without 'args' keyword).
command: /usr/bin/make_database.sh db_user db_name creates=/path/to/database
# 'args'是一个任务关键字,与模块在同一层传递
# 如果/path/to/database不存在(带'args'关键字),则运行命令。
- name: Run command if /path/to/database does not exist (with 'args' keyword).
command: /usr/bin/make_database.sh db_user db_name
args:
creates: /path/to/database
# 'cmd'是模块参数
# 如果/path/to/database不存在(带'cmd'参数),则执行命令。
- name: Run command if /path/to/database does not exist (with 'cmd' parameter).
command:
cmd: /usr/bin/make_database.sh db_user db_name
creates: /path/to/database
# 如果“/path/to/database”不存在,则修改工作目录为“somedir/”,并以“db_owner”身份执行命令。
- name: Change the working directory to somedir/ and run the command as db_owner if /path/to/database does not exist.
command: /usr/bin/make_database.sh db_user db_name
become: yes
become_user: db_owner
args:
chdir: somedir/
creates: /path/to/database
# 'argv'是一个参数,从模块上缩进一层
# 使用'argv'以列表形式发送命令—'command'为空
- name: Use 'argv' to send a command as a list - leave 'command' empty
command:
argv:
- /usr/bin/make_database.sh
- Username with whitespace
- dbname with whitespace
# 安全使用模板变量运行命令。总是使用引用过滤器来避免注入问题。
- name: safely use templated variable to run command. Always use the quote filter to avoid injection issues.
command: cat {{ myfile|quote }}
register: myoutput
官方文档:https://docs.ansible.com/ansible/2.9/modules/command_module.html#command-module