02-Ansible 基本使用
与command模块不同的是, 这些命令将通过受管节点上的shell进行处理。这些主机也可以分配到组中,以进行集中管理 组可以包含子组,主机也可以是多个组的成员。ansible命令通过–inventory PATHNAME或-i PATHNAME选项在命令行中指定清单文件的位置,其中PATHNAME是所需清单文件的路径。您可以使用另一个临时命令在许多不同的计算机上高效重启一项服务,或者确保特定的软
Ansible 清单
Ansible 软件包中文件
[laoma@controller ~]# rpm -ql ansible
- 配置文件目录 /etc/ansible
- 执行文件目录/usr/bin
- lib依赖库目录/usr/lib/python2.7/site-packages/ansible
- 插件/usr/share/ansible/plugins
- Help文档目录/usr/share/doc/ansible
- Man文档目录/usr/share/man/
主机清单
Inventory 定义Ansible将要管理的一批主机。这些主机也可以分配到组中,以进行集中管理 组可以包含子组,主机也可以是多个组的成员。清单还可以设置应用到它所定义的主机和组的变量。
通过以下方式定义主机清单:
- 静态主机清单:以文本文件的方式来定义。
- 动态主机清单:使用外部信息提供程序通过脚本或其他程序来自动生成。目的是从启动环境中获取主机清单,例如openstack、kubernetes、zabbix等。
静态主机清单
主机清单支持多种格式,例如ini、yaml、脚本等。
本次课程使用 ini 格式。
最简单的静态清单
受管节点的主机名或IP地址的列表,每行一个。
示例:
[laoma@controller ~]$ vim inventory
web1.example.com
web2.example.com
db1.example.com
db2.example.com
192.0.2.42
验证主机是否在inventory中
[laoma@controller ~]$ ansible --list-hosts -i inventory web1.example.com
hosts (1):
web1.example.com
[laoma@controller ~]$ ansible --list-hosts -i inventory 192.0.2.42
hosts (1):
192.0.2.42
ansible命令通过–inventory PATHNAME或-i PATHNAME选项在命令行中指定清单文件的位置,其中PATHNAME是所需清单文件的路径。
主机组
还可以将受管节点组织为主机组。通过主机组,更加有效地对一系列系统运行Ansible。
格式:
[groupname]
hostname
hostip
示例:
app1.example.com
[webservers]
web1.example.com
web2.example.com
[dbservers]
db1.example.com
db2.example.com
192.0.2.42
192.0.2.43
验证:
[laoma@controller ~]$ ansible --list-hosts -i inventory webservers
hosts (2):
web1.example.com
web2.example.com
# 注意:192.0.2.43属于dbservers组
[laoma@controller ~]$ ansible --list-hosts -i inventory dbservers
hosts (4):
db1.example.com
db2.example.com
192.0.2.42
192.0.2.43
有两个组总是存在的:
- all:包含inventory中所有主机。
- ungrouped:inventory中列出的,但不属于任何组的主机。
验证:
[laoma@controller ~]$ ansible --list-hosts -i inventory all
hosts (7):
app1.example.com
web1.example.com
web2.example.com
db1.example.com
db2.example.com
192.0.2.42
192.0.2.43
[laoma@controller ~]$ ansible --list-hosts -i inventory ungrouped
hosts (1):
app1.example.com
根据需要,将主机分配在多个组中,例如根据主机的角色、其物理位置以及是否在生产环境中等因素。
[webservers]
web1.example.com
web2.example.com
192.168.3.7
[dbservers]
db1.example.com
db2.example.com
192.0.2.42
[eastdc]
web1.example.com
db1.example.com
[westdc]
web2.example.com
db2.example.com
验证:
[laoma@controller ~]$ ansible --list-hosts -i inventory webservers
hosts (3):
web1.example.com
web2.example.com
192.168.3.7
[laoma@controller ~]$ ansible --list-hosts -i inventory eastdc
hosts (2):
web1.example.com
db1.example.com
主机组嵌套
一个主机组还可以属于另外一个主机组。
示例:
[eastdc]
web1.example.com
db1.example.com
[westdc]
web2.example.com
db2.example.com
[dc:children]
eastdc
westdc
验证:
[laoma@controller ~]$ ansible --list-hosts -i inventory dc
hosts (4):
web1.example.com
db1.example.com
web2.example.com
db2.example.com
子组中的主机组必须定义,否则会出现语法上的报错。
示例:
[eastdc]
web1.example.com
db1.example.com
[westdc]
web2.example.com
db2.example.com
[dc:children]
eastdc
westdc
node1
验证:
[laoma@controller ~]$ ansible --list-hosts -i inventory dc
[WARNING]: * Failed to parse /home/laoma/inventory with yaml plugin:
Syntax
Error while loading YAML. did not find expected <document start> The
error
appears to be in '/home/laoma/inventory': line 2, column 1, but may be
elsewhere
in the file depending on the exact syntax problem. The offending line
appears to
be: [eastdc] web1.example.com ^ here
[WARNING]: * Failed to parse /home/laoma/inventory with ini plugin:
/home/laoma/inventory:12: Section [dc:children] includes undefined
group:
node1
[WARNING]: Unable to parse /home/laoma/inventory as an inventory
source
[WARNING]: No inventory was parsed, only implicit localhost is
available
[WARNING]: provided hosts list is empty, only localhost is available.
Note that
the implicit localhost does not match 'all'
hosts (4):
web1.example.com
db1.example.com
web2.example.com
db2.example.com
范围简写
通过指定主机名称或IP地址的范围来简化Ansible主机清单。您可以指定数字或字母范围。
语法:[start:end]
示例:
# 代表192.168.4.0-192.168.7.255
[priv]
192.168.[4:7].[0:255]
#代表01,02...20
[hosts]
host[01:20].example.com
# 代表a b c
[servers]
server[a:c].example.com
验证:
[laoma@controller ~]$ ansible --list-hosts -i inventory hosts
hosts (20):
host01.example.com
host02.example.com
......
host19.example.com
host20.example.com
[laoma@controller ~]$ ansible --list-hosts -i inventory priv
hosts (1024):
192.168.4.0
192.168.4.1
192.168.4.2
......
192.168.7.253
192.168.7.254
192.168.7.255
[laoma@controller ~]$ ansible --list-hosts -i inventory servers
hosts (3):
node1.example.com
node2.example.com
serverc.example.com
以下是错误的范围示例:
[servers]
server[0a:2c].example.com
验证:
[laoma@controller ~]$ ansible --list-hosts -i inventory all
[WARNING]: * Failed to parse /home/laoma/inventory with yaml plugin:
Syntax
Error while loading YAML. did not find expected <document start> The
error
appears to be in '/home/laoma/inventory': line 2, column 1, but may be
elsewhere
in the file depending on the exact syntax problem. The offending line
appears to
be: [servers] server[0a:2c].example.com ^ here
[WARNING]: * Failed to parse /home/laoma/inventory with ini plugin:
invalid
literal for int() with base 10: '0a'
[WARNING]: Unable to parse /home/laoma/inventory as an inventory
source
[WARNING]: No inventory was parsed, only implicit localhost is
available
[WARNING]: provided hosts list is empty, only localhost is available.
Note that
the implicit localhost does not match 'all'
hosts (0):
动态主机清单
使用外部数据提供的信息动态生成Ansible清单信息。
本课程内容不做进一步讨论。
ansible-inventory 命令
通过不同的格式查看清单文件。
[laoma@controller ~]$ ansible-inventory --help
Usage: ansible-inventory [options] [host|group]
Options:
--ask-vault-pass ask for vault password
--export When doing an --list, represent in a way that
is
optimized for export,not as an accurate
representation
of how Ansible has processed it
-h, --help show this help message and exit
-i INVENTORY, --inventory=INVENTORY, --inventory-file=INVENTORY
specify inventory host path or comma separated
host
list. --inventory-file is deprecated
--output=OUTPUT_FILE When doing an --list, send the inventory to a
file
instead of of to screen
--playbook-dir=BASEDIR
Since this tool does not use playbooks, use
this as a
substitute playbook directory.This sets the
relative
path for many features including roles/
group_vars/
etc.
--toml Use TOML format instead of default JSON,
ignored for
--graph
--vars Add vars to graph display, ignored unless used
with
--graph
--vault-id=VAULT_IDS the vault identity to use
--vault-password-file=VAULT_PASSWORD_FILES
vault password file
-v, --verbose verbose mode (-vvv for more, -vvvv to enable
connection debugging)
--version show program's version number, config file
location,
configured module search path, module location,
executable location and exit
-y, --yaml Use YAML format instead of default JSON,
ignored for
--graph
Actions:
One of following must be used on invocation, ONLY ONE!
--list Output all hosts info, works as inventory
script
--host=HOST Output specific host info, works as inventory
script
--graph create inventory graph, if supplying pattern it
must
be a valid group name
Show Ansible inventory information, by default it uses the inventory
script
JSON format
示例清单:
app1.example.com
[webservers]
web1.example.com
web2.example.com
192.168.3.7
[dbservers]
db1.example.com
db2.example.com
192.0.2.42
[eastdc]
web1.example.com
db1.example.com
[westdc]
web2.example.com
db2.example.com
[dc:children]
eastdc
westdc
验证:
# 树形结构显示
[laoma@controller ~]$ ansible-inventory -i inventory --graph
@all:
|--@dbservers:
| |--192.0.2.42
| |--db1.example.com
| |--db2.example.com
|--@dc:
| |--@eastdc:
| | |--db1.example.com
| | |--web1.example.com
| |--@westdc:
| | |--db2.example.com
| | |--web2.example.com
|--@ungrouped:
| |--app1.example.com
|--@webservers:
| |--192.168.3.7
| |--web1.example.com
| |--web2.example.com
# yaml格式显示
[laoma@controller ~]$ ansible-inventory -i inventory --list -y
all:
children:
dbservers:
hosts:
192.0.2.42: {}
db1.example.com: {}
db2.example.com: {}
dc:
children:
eastdc:
hosts:
db1.example.com: {}
web1.example.com: {}
westdc:
hosts:
db2.example.com: {}
web2.example.com: {}
ungrouped:
hosts:
app1.example.com: {}
webservers:
hosts:
192.168.3.7: {}
web1.example.com: {}
web2.example.com: {}
管理 ANSIBLE 配置文件
配置文件位置和优先级
- 环境变量 ANSIBLE_CONFIG
- ./ansible.cfg,当前位置中的 ansible.cfg,当前位置一般是项目目录。
- ~/.ansible.cfg
- /etc/ansible/ansible.cfg
从上到下,优先级越来越低。
**建议:**在当前目录下定义ansible.cfg文件。
验证优先级:
# 环境准备
[laoma@controller ~]$ mkdir web && cd web
# 查看ansible命令当前使用的配置文件
[laoma@controller web]$ ansible --version
ansible 2.9.27
config file = /opt/ansible.cfg
configured module search path =
[u'/home/laoma/.ansible/plugins/modules',
u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-
packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Jun 28 2022, 15:30:04) [GCC 4.8.5
20150623 (Red Hat 4.8.5-44)]
# 或者
[laoma@controller web]$ ansible --version |grep 'config file'
config file = /etc/ansible/ansible.cfg
[laoma@controller web]$ touch ~/.ansible.cfg
[laoma@controller web]$ ansible --version |grep 'config file'
config file = /home/laoma/.ansible.cfg
[laoma@controller web]$ touch ansible.cfg
[laoma@controller web]$ ansible --version |grep 'config file'
config file = /home/laoma/laoma/ansible.cfg
[laoma@controller web]$ export ANSIBLE_CONFIG=/opt/ansible.cfg
[laoma@controller web]$ sudo touch /opt/ansible.cfg
[laoma@controller web]$ ansible --version |grep 'config file'
config file = /opt/ansible.cfg
配置文件解析
ansible 默认配置文件 /etc/ansible/ansible.cfg。
Ansible 配置文件包括以下部分:
[laoma@controller ~]$ grep "^\[" /etc/ansible/ansible.cfg
[defaults]
[inventory]
[privilege_escalation]
[paramiko_connection]
[ssh_connection]
[persistent_connection]
[accelerate]
[selinux]
[colors]
[diff]
常用参数解析如下:
[defaults]
# inventory 指定清单文件路径
inventory = /etc/ansible/hosts
# 并发执行同一个任务的主机数量
forks = 5
# ansible检查任务是否执行完成的时间间隔
poll_interval = 15
# 连接登录到受管主机时是否提示输入密码
ask_pass = True
# 控制facts如何收集
# smart - 如果facts已经收集过了,就不收集了。
# implicit - facts收集,剧本中使用gather_facts: False关闭facts收集。
# explicit - facts不收集,剧本中使用gather_facts: True关闭facts收集。
gathering = implicit
# 收集facts范围
# all - gather all subsets
# network - gather min and network facts
# hardware - gather hardware facts (longest facts to retrieve)
# virtual - gather min and virtual facts
# facter - import facts from facter
# ohai - import facts from ohai
# You can combine them using comma (ex: network,virtual)
# You can negate them using ! (ex: !hardware,!facter,!ohai)
# A minimal set of facts is always gathered.
gather_subset = all
# 收集facts超时时间
gather_timeout = 10
# 变量注入,通过ansible_facts引用
inject_facts_as_vars = True
# 定义角色路径,以冒号分隔
roles_path = /etc/ansible/roles
# SSH是否检验 host key
host_key_checking = False
# 连接登录到受管主机时使用的用户身份
remote_user = root
# ansible 命令和ansible-playbook 命令输出内容存放位置
log_path = /var/log/ansible.log
# ansible 命令默认模块
module_name = command
# ssh 私钥文件位置
private_key_file = /path/to/file
# 默认ansible-vault命令的密码文件
vault_password_file = /path/to/vault_password_file
# 定义ansible_managed变量值
ansible_managed = Ansible managed
# 剧本执行过程中,遇到未定义的变量不报错
error_on_undefined_vars = False
# 系统告警启用
system_warnings = True
# 下架告警启用
deprecation_warnings = True
# 使用command和shell模块时,是否提示告警
command_warnings = False
# facts保存在哪里,例如redis
fact_caching = memory
[inventory]
# 启用的清单插件, 默认为: 'host_list', 'script', 'auto', 'yaml', 'ini',
'toml'
#enable_plugins = host_list, virtualbox, yaml, constructed
# 当清单源是一个目录的时候,忽略这些后缀的清单文件
#ignore_extensions = .pyc, .pyo, .swp, .bak, ~, .rpm, .md, .txt, ~,
.orig, .ini, .cfg, .retry
[privilege_escalation]
# 连接到受管主机后是否需要进行权限提升或切换用户
become=True
# 使用何种方式进行用户切换或提权
become_method=sudo
# 用户切换或提权后的对应用户
become_user=root
# 进行用户切换或提权时是否提示输入密码
become_ask_pass=False
说明:“#” 和 ";"开头的行,作为注释。
配置文件示例
对于基本操作, 使用 [defaults] 和 [privilege_escalation] 即可。
配置文件示例
[defaults]
inventory = ./inventory
remote_user = laoma
[privilege_escalation]
become = True
become_user = root
become_method = sudo
become_ask_pass = False
最终效果:
[laoma@controller webapp]$ ansible all -a id
node3 | CHANGED | rc=0 >>
uid=0(root) gid=0(root) groups=0(root)
node2 | CHANGED | rc=0 >>
uid=0(root) gid=0(root) groups=0(root)
node1 | CHANGED | rc=0 >>
uid=0(root) gid=0(root) groups=0(root)
node4 | CHANGED | rc=0 >>
uid=0(root) gid=0(root) groups=0(root)
ansible-config 命令
用于分析ansible命令的配置。
[laoma@controller ~]$ ansible-config -h
usage: ansible-config [-h] [--version] [-v] {list,dump,view} ...
View ansible configuration.
positional arguments:
{list,dump,view}
list Print all config options
dump Dump configuration
view View configuration file
optional arguments:
--version show program's version number, config file
location,
configured module search path, module location,
executable
location and exit
-h, --help show this help message and exit
-v, --verbose verbose mode (-vvv for more, -vvvv to enable
connection
debugging)
ansible-config view
查看当前ansible配合文件内容。
[laoma@controller web]$ ansible --version|grep file
config file = /home/laoma/web/ansible.cfg
[laoma@controller web]$ ansible-config view
[defaults]
remote_user = laoma
inventory = ./inventory
[privilege_escalation]
become = True
become_user = root
become_method = sudo
become_ask_pass = False
ansible-config dump
当前ansible生效的所有配置,包括所有默认值。
[laoma@controller web]$ ansible-config dump
ACTION_WARNINGS(default) = True
AGNOSTIC_BECOME_PROMPT(default) = True
ALLOW_WORLD_READABLE_TMPFILES(default) = False
......
DEFAULT_HOST_LIST(/home/laoma/web/ansible.cfg) =
['/home/laoma/web/inventory']
......
HOST_KEY_CHECKING(default) = True
......
ansible-config list
查看所有配置参数用途,配置位置等。
DEFAULT_HOST_LIST:
default: /etc/ansible/hosts
description: Comma separated list of Ansible inventory sources
env:
- {name: ANSIBLE_INVENTORY}
expand_relative_paths: true
ini:
- {key: inventory, section: defaults}
name: Inventory Source
type: pathlist
yaml: {key: defaults.inventory}
localhost 连接
默认Ansible连接到受管主机的协议为 smart (通常采用最有效的方式 - SSH)。如本地清单中并未指定localhost,Ansible会隐式设置localhost,并使用local连接类型连接localhost。
- local连接类型会忽略remote_user的设置,并且直接在本地系统上运行命令。
- 如果使用了特权提升,此时ansible将会在运行sudo时使用运行Ansible命令的账户的身份进行提权,而非remote_user所指定的账户。
更改 localhost 连接方式:清单中包涵 localhost。
运行 AD HOC 命令
实验环境
[laoma@controller ~]$ mkdir web && cd web
[laoma@controller web]$ cat > ansible.cfg <<'EOF'
[defaults]
remote_user = laoma
inventory = ./inventory
[privilege_escalation]
become = True
become_user = root
become_method = sudo
become_ask_pass = False
EOF
[laoma@controller web]$ cat > inventory <<'EOF'
node1
EOF
ansible AD HOC 命令
命令作用:
-
快速执行单个Ansible任务,而不需要将它保存下来供以后再次运行。它们是简单的在线操
作,无需编写playbook即可运行。
-
快速测试和更改很有用。例如,您可以使用临时命令确保一组服务器上的/ etc/hosts文件中
存在某一特定的行。您可以使用另一个临时命令在许多不同的计算机上高效重启一项服务,或者确保特定的软件包为最新版本。
命令语法:
ansible host-pattern -m module [-a 'module arguments'] [-i inventory]
-
host-pattern,是inventory中定义的主机或主机组,可以为ip、hostname、inventory中
的group组名、具有“,”或“*”或“:”等特殊字符的匹配型字符串,是必选项。
-
-m module,module是一个小程序,用于实现具体任务。
-
-a ‘module arguments’,是模块的参数。
-
-i inventory,指定inventory文件。
命令执行结果颜色说明:
Ansible的返回结果都非常友好,用3种颜色来表示执行结果:
- 红色:表示执行过程有异常,一般会中止剩余所有的任务。
- 绿色:表示目标主机已经是预期状态,不需要更改 。
- 黄色:表示命令执行结束后目标有状态变化,并设置为预期状态,所有任务均正常执行。
Ansible 部分模块
Ansible 模块存放位置:/usr/lib/python*/site-packages/ansible
官网:模块清单。
-
文件模块
- copy: 将控制主机上的文件复制到受管节点,类似于scp
- file: 设置文件的权限和其他属性
- lineinfile: 确保特定行是否在文件中
- synchronize: 使用 rsync 将控制主机上的文件同步到受管节点
-
软件包模块
-
package: 自动检测操作系统软件包管理器
-
yum: 使用 YUM 软件包管理器管理软件包
-
apt: 使用 APT 软件包管理器管理软件包
-
gem: 管理 Rubygem
-
pip: 从 PyPI 管理 Python 软件包
-
-
系统模块
- firewalld: 使用firewalld管理任意端口和服务
- reboot: 重新启动计算机
- service: 管理服务
- user、group: 管理用户和组帐户
-
NetTools模块
- get_url: 通过HTTP、HTTPS或FTP下载文件
- nmcli: 管理网络
- uri: 与 Web 服务交互
ansible-doc 命令
[laoma@controller ~]$ ansible-doc -h
Usage: ansible-doc [-l|-F|-s] [options] [-t <plugin type> ] [plugin]
plugin documentation tool
Options:
-h, --help show this help message and exit
-j, --json **For internal testing only** Dump json
metadata for
all plugins.
-l, --list List available plugins
-F, --list_files Show plugin names and their source files
without
summaries (implies --list)
-M MODULE_PATH, --module-path=MODULE_PATH
prepend colon-separated path(s) to module
library
(default=~/.ansible/plugins/modules:/usr/share/ansible/plugins/modules)
-s, --snippet Show playbook snippet for specified plugin(s)
-t TYPE, --type=TYPE Choose which plugin type (defaults to
"module").
Available plugin types are : ('become',
'cache',
'callback', 'cliconf', 'connection', 'httpapi',
'inventory', 'lookup', 'shell', 'module',
'strategy','vars')
-v, --verbose verbose mode (-vvv for more, -vvvv to enable
connection debugging)
--version show program's version number, config file
location,
configured module search path, module location,
executable location and exit
See man pages for Ansible CLI options or website for tutorials
https://docs.ansible.com
示例:
# 查看模块清单及说明
[laoma@controller ~]$ ansible-doc -l
fortios_router_community_list Configure community lists
i...
azure_rm_devtestlab_info Get Azure DevTest Lab
facts
......
# 查看模块清单及位置
[laoma@controller ~]$ ansible-doc -F
fortios_router_community_list /usr/lib/python2.7/site-
packages/ansibl....
azure_rm_devtestlab_info /usr/lib/python2.7/site-
packages/ansibl....
......
# 查看特定模块说明文档
[laoma@controller ~]$ ansible-doc user
> USER (/usr/lib/python3.6/site-
packages/ansible/modules/system/user.py)
Manage user accounts and user attributes. For Windows targets, use
the
[win_user] module instead.
* This module is maintained by The Ansible Core Team
# 模块选项,=开头是必选选项
OPTIONS (= is mandatory):
- append
If `yes', add the user to the groups specified in `groups'.
If `no', user will only be added to the groups specified in
`groups',
removing them from all other groups.
[Default: False]
type: bool
... ...
# 提示信息
NOTES:
* There are specific requirements per platform on user management
utilities. However they generally come pre-installed with the
system and Ansible will require they are present at runtime. If
they are not, a descriptive error message will be shown.
... ...
# 参考信息
SEE ALSO:
* Module authorized_key
The official documentation on the authorized_key module.
https://docs.ansible.com/ansible/latest/modules/authorized_key
_module.html
... ...
# 作者
AUTHOR: Stephen Fromm (@sfromm)
# METADATA描述了谁在维护该模块。
# status记录了模块开发状态。
# stableinterface: 模块的关键字稳定,将尽力确保不删除关键字或更改其含
义。
# preview: 模块处于技术预览阶段,可能不稳定,其关键字可能会更改,或者它可
能需要本身会受到不兼容更改的库或Web服务。
# deprecated: 未来某一发行版中将不再提供。
# removed: 模块已从发行版中移除,但因文档需要存在存根,以帮助之前的用户迁
移到新的模块。
METADATA:
status:
- stableinterface
# supported_by记录了哪些社区在维护该模块:
# core:Ansible核心开发人员维护,始终随Ansible提供。
# curated:模块由社区中的合作伙伴或公司提交并维护。这些模块的维护者必须留
意报告的任何问题,或者调取针对该模块提出的请求。在社区维护人员批准了更改后,
上游 “core” 开发人员审核对策划模块提出的更改。核心提交者也确保因为Ansible引
擎中的变化而对这些模块造成的任何问题得到修正。这些模块目前随Ansible提供,但是
可能会在未来某个时候另外打包。
# community:模块不受到core上游开发人员、合作伙伴或公司的支持,完全由一般
开源社区维护。此类别中的模块仍然完全可用,但对问题的响应速度完全取决于社区。
这些模块目前也随Ansible提供,但是可能会在未来某个时候另外打包。
supported_by: core
... ...
# 模块使用示例
EXAMPLES:
- name: Add the user 'johnd' with a specific uid and a primary group of
'admin'
user:
name: johnd
comment: John Doe
uid: 1040
group: admin
... ...
# 模块返回值说明
RETURN VALUES:
append:
description: Whether or not to append the user to groups
returned: When state is 'present' and the user exists
type: bool
sample: True
... ...
如果现有的模块无法实现现有需求,用户也可以自行编写模块:
- Ansible会从变量ANSIBLE_LIBRARY中查找模块
- 如果该变量未设置,将会从ansible.cfg配置文件library设置的位置查找模块
command 模块
command 模块允许管理员在受管节点的命令行中运行任意命令。要运行的命令通过-a选项指定为该模块的参数。
[laoma@controller web]$ ansible node1 -m command -a 'hostname'
node1 | CHANGED | rc=0 >>
node1.laoma.cloud
[laoma@controller web]$ ansible node1 -m command -a 'hostname' -o
node1 | CHANGED | rc=0 | (stdout) node1.laoma.cloud
说明:
- command 模块执行的远程命令不受受管节点上的shell处理,无法访问shell环境变量,也不能执行重定向和传送等shell操作。
- 如果临时命令没有指定模块,Ansible默认使用command模块。
shell 模块
shell模块允许您将要执行的命令作为参数传递给该模块。 Ansible随后对受管节点远程执行该命令。与command模块不同的是, 这些命令将通过受管节点上的shell进行处理。因此,可以访问shell环境变量,也可使用重定向和管道等shell操作。
[laoma@controller web]$ ansible node1 -m command -a set
node1 | FAILED | rc=2 >>
[Errno 2] No such file or directory: 'set': 'set'
[laoma@controller web]$ ansible node1 -m shell -a set
node1 | CHANGED | rc=0 >>
BASH=/bin/sh
BASHOPTS=cmdhist:complete_fullquote:extquote:force_fignore:hostcomplete
:interactive_comments:progcomp:promptvars:sourcepath
BASH_ALIASES=()
BASH_ARGC=()
BASH_ARGV=()
......
注意:command和shell模块要求被管理主机安装Python。
raw 模块
raw 模块,可以直接在远端主机shell中执行命令,远端主机不需要安装Python(特别是针对网
络设备)。在大部分场景中,不推荐使用command、shell、raw模块执行命令,因为这些模块不具有幂等性。
[laoma@controller web]$ ansible node1 -m raw -a 'echo "hello ansible" >
/tmp/hello.txt'
node1 | CHANGED | rc=0 >>
Shared connection to node1 closed.
# 此处多了一个现实:断开连接,相当于通过ssh连接到受管节点执行命令。
[laoma@controller web]$ ansible node1 -a 'cat /tmp/hello.txt'
node1 | CHANGED | rc=0 >>
hello ansible
# 对比shell模块
[laoma@controller web]$ ansible node1 -m shell -a 'echo "hello ansible"
> /tmp/hello.txt'
node1 | CHANGED | rc=0 >>
ansible AD HOC 命令选项
临时命令选项优先级高于配置文件中配置。
| 配置文件指令 | 配置文件指令 命令行选项 |
|---|---|
| inventory | -i |
| inventory remote_user | -u |
| ask_pass | -k, --ask-pass |
| become | –become, -b |
| become_method | –become_method |
| become_user | –become-user |
| become_ask_pass | –ask-become-pass, -K |
更多推荐
所有评论(0)