当前位置: 首页 > news >正文

【网络运维】Linux和自动化: Ansible基础实践

Ansible 基础实践

Ansible 清单

Ansible 软件包中文件

查看Ansible 软件包中所有文件:

[furongwang@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/man1/
主机清单

Inventory 定义Ansible将要管理的一批主机。这些主机也可以分配到组中,以进行集中管理 组可以包含子组,主机也可以是多个组的成员。清单还可以设置应用到它所定义的主机和组的变量。

通过以下方式定义主机清单:

  • 静态主机清单: 以文本文件的方式来定义。
  • 动态主机清单: 使用外部信息提供程序通过脚本或其他程序来自动生成。目的是从启动环境中获取主机清单,例如openstack、kubernetes、zabbix等。
静态主机清单

主机清单支持多种格式,例如ini、yaml、脚本等。

本次课程使用 ini 格式。

最简单的静态清单

受管节点的主机名或IP地址的列表,每行一个。

示例:

[furongwang@controller ~]$ vim inventory # 配置新文件
controller
node1
node2
node3
node4

验证主机是否在inventory中

[furongwang@controller ~]$ ansible --list-hosts -i inventory node1hosts (1):node1
[furongwang@controller ~]$ ansible --list-hosts -i inventory node[2.3.4]hosts (3):node3node2node4

ansible命令通过–inventory PATHNAME或-i PATHNAME选项在命令行中指定清单文件的位置,其中PATHNAME是所需清单文件的路径。

主机组

还可以将受管节点组织为主机组。通过主机组,更加有效地对一系列系统运行Ansible。

格式:

[groupname]
hostname
hostip

示例:

app1.furongwang.com[webservers]
web1.furongwang.com
web2.furongwang.com[dbservers]
db1.furongwang.com
db2.furongwang.com
192.0.2.42192.0.2.43

验证:

[furongwang@controller ~]$ ansible --list-hosts -i inventory webservershosts (2):web1.furongwang.comweb2.furongwang.com# 注意:192.0.2.43属于dbservers组
[furongwang@controller ~]$ ansible --list-hosts -i inventory dbservershosts (4):db1.furongwang.comdb2.furongwang.com192.0.2.42192.0.2.43

有两个组总是存在的:

  • all:包含inventory中所有主机。
  • ungrouped:inventory中列出的,但不属于任何组的主机。

验证:

[furongwang@controller ~]$ ansible --list-hosts -i inventory allhosts (7):app1.furongwang.comweb1.furongwang.comweb2.furongwang.comdb1.furongwang.comdb2.furongwang.com192.0.2.42192.0.2.43
[furongwang@controller ~]$ ansible --list-hosts -i inventory ungroupedhosts (1):app1.furongwang.com

根据需要,将主机分配在多个组中,例如根据主机的角色、其物理位置以及是否在生产环境中等因素。

[webservers]
web1.furongwang.com
web2.furongwang.com
192.168.1.5[dbservers]
db1.furongwang.com
db2.furongwang.com
192.0.2.5[eastdc]
web1.furongwang.com
db1.furongwang.com[westdc]
web2.furongwang.com
db2.furongwang.com

验证:

[furongwang@controller ~]$ ansible --list-hosts -i inventory webservershosts (3):web1.furongwang.comweb2.furongwang.com192.168.1.5
[furongwang@controller ~]$ ansible --list-hosts -i inventory eastdchosts (2):web1.furongwang.comdb1.furongwang.com
主机组嵌套

一个主机组还可以属于另外一个主机组。

示例:

[eastdc]
web1.furongwang.com
db1.furongwang.com[westdc]
web2.furongwang.com
db2.furongwang.com[dc:children]
eastdc
westdc

验证:

[furongwang@controller ~]$ ansible --list-hosts -i inventory dchosts (4):web1.furongwang.comdb1.furongwang.comweb2.furongwang.comdb2.furongwang.com

子组中的主机组必须定义,否则会出现语法上的报错。

示例:

[eastdc]
web1.furongwang.com
db1.furongwang.com[westdc]
web2.furongwang.com
db2.furongwang.com[dc:children]
eastdc
westdc
node1

验证:

[furongwang@controller ~]$ ansible --list-hosts -i inventory dc[WARNING]:  * Failed to parse /home/furongwang/inventory with yaml plugin: Syntax
Error while loading YAML.   did not find expected <document start>  The error
appears to be in '/home/furongwang/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.furongwang.com ^ here[WARNING]:  * Failed to parse /home/furongwang/inventory with ini plugin:
/home/furongwang/inventory:12: Section [dc:children] includes undefined group:
node1[WARNING]: Unable to parse /home/furongwang/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.furongwang.comdb1.furongwang.comweb2.furongwang.comdb2.furongwang.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].furongwang.com# 代表a b c
[servers]
server[a:c].furongwang.com

验证:

[furongwang@controller ~]$ ansible --list-hosts -i inventory hostshosts (20):host01.furongwang.comhost02.furongwang.com
......host19.furongwang.comhost20.furongwang.com[furongwang@controller ~]$ ansible --list-hosts -i inventory privhosts (1024):192.168.4.0192.168.4.1192.168.4.2
......192.168.7.253192.168.7.254192.168.7.255[furongwang@controller ~]$ ansible --list-hosts -i inventory servershosts (3):node1.furongwang.comnode2.furongwang.comserverc.furongwang.com

以下是错误的范围示例:

[servers]
server[0a:2c].furongwang.com

验证:

[furongwang@controller ~]$ ansible --list-hosts -i inventory all[WARNING]:  * Failed to parse /home/furongwang/inventory with yaml plugin: Syntax
Error while loading YAML.   did not find expected <document start>  The error
appears to be in '/home/furongwang/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].furongwang.com ^ here[WARNING]:  * Failed to parse /home/furongwang/inventory with ini plugin: invalid
literal for int() with base 10: '0a'[WARNING]: Unable to parse /home/furongwang/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 命令

通过不同的格式查看清单文件。

[furongwang@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 isoptimized for export,not as an accurate representationof how Ansible has processed it-h, --help            show this help message and exit-i INVENTORY, --inventory=INVENTORY, --inventory-file=INVENTORYspecify inventory host path or comma separated hostlist. --inventory-file is deprecated--output=OUTPUT_FILE  When doing an --list, send the inventory to a fileinstead of of to screen--playbook-dir=BASEDIRSince this tool does not use playbooks, use this as asubstitute playbook directory.This sets the relativepath 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_FILESvault password file-v, --verbose         verbose mode (-vvv for more, -vvvv to enableconnection 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--graphActions: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 mustbe a valid group nameShow Ansible inventory information, by default it uses the inventory script
JSON format

示例清单:

app1.furongwang.com[webservers]
web1.furongwang.com
web2.furongwang.com
192.168.1.5[dbservers]
db1.furongwang.com
db2.furongwang.com
192.0.2.5[eastdc]
web1.furongwang.com
db1.furongwang.com[westdc]
web2.furongwang.com
db2.furongwang.com[dc:children]
eastdc
westdc

验证:

# 树形结构显示
[furongwang@controller ~]$ ansible-inventory -i inventory --graph
@all:|--@dbservers:|  |--192.0.2.5|  |--db1.furongwang.com|  |--db2.furongwang.com|--@dc:|  |--@eastdc:|  |  |--db1.furongwang.com|  |  |--web1.furongwang.com|  |--@westdc:|  |  |--db2.furongwang.com|  |  |--web2.furongwang.com|--@ungrouped:|  |--app1.furongwang.com|--@webservers:|  |--192.168.1.5|  |--web1.furongwang.com|  |--web2.furongwang.com# yaml格式显示
[furongwang@controller ~]$ ansible-inventory -i inventory --list -y
all:children:dbservers:hosts:192.0.2.5: {}db1.furongwang.com: {}db2.furongwang.com: {}dc:children:eastdc:hosts:db1.furongwang.com: {}web1.furongwang.com: {}westdc:hosts:db2.furongwang.com: {}web2.furongwang.com: {}ungrouped:hosts:app1.furongwang.com: {}webservers:hosts:192.168.1.5: {}web1.furongwang.com: {}web2.furongwang.com: {}

管理 ANSIBLE 配置文件

配置文件位置和优先级
  1. 环境变量 ANSIBLE_CONFIG
  2. ./ansible.cfg,当前位置中的 ansible.cfg,当前位置一般是项目目录。
  3. ~/.ansible.cfg
  4. /etc/ansible/ansible.cfg

从上到下,优先级越来越低。

!建议 !:在当前目录下定义ansible.cfg文件。

验证优先级

# 环境准备
[furongwang@controller ~]$ mkdir web && cd web# 查看ansible命令当前使用的配置文件
[furongwang@controller web]$ ansible --version |grep 'config file'config file = /etc/ansible/ansible.cfg
# 此处显示默认路径[furongwang@controller web]$ touch ~/.ansible.cfg
[furongwang@controller web]$ ansible --version |grep 'config file'config file = /home/furongwang/.ansible.cfg
# 转到用户家目录路径[furongwang@controller web]$ touch ansible.cfg
[furongwang@controller web]$ ansible --version |grep 'config file'config file = /home/furongwang/furongwang/ansible.cfg[furongwang@controller web]$ export ANSIBLE_CONFIG=/opt/ansible.cfg
[furongwang@controller web]$ sudo touch /opt/ansible.cfg
[furongwang@controller web]$ ansible --version |grep 'config file'config file = /opt/ansible.cfg
# 转到opt目录
配置文件解析

ansible 默认配置文件 /etc/ansible/ansible.cfg。

Ansible 配置文件包括以下部分:

[furongwang@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]
remote_user = furongwang
inventory = ./inventory[privilege_escalation]
become = True
become_user = root
become_method = sudo
become_ask_pass = False

最终效果:

[furongwang@controller web]$ 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命令的配置。

[furongwang@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 optionsdump            Dump configurationview            View configuration fileoptional arguments:--version         show program's version number, config file location,configured module search path, module location, executablelocation and exit-h, --help        show this help message and exit-v, --verbose     verbose mode (-vvv for more, -vvvv to enable connectiondebugging)
ansible-config init

生成 ansible.cfg 模版文件。

[furongwang@controller web]$ ansible-config init > ansible.cfg.example
ansible-config view

查看当前ansible配合文件内容。

[furongwang@controller web]$ ansible --version|grep fileconfig file = /home/furongwang/web/ansible.cfg[furongwang@controller web]$ ansible-config view
[defaults]
inventory = ./inventory
remote_user = furongwang[privilege_escalation]
become=TRUE
become_method=sudo
become_user=root
become_ask_pass=FALSE
ansible-config dump

当前ansible生效的所有配置,包括所有默认值。

[furongwang@controller web]$ ansible-config dump
ACTION_WARNINGS(default) = True
AGNOSTIC_BECOME_PROMPT(default) = True
ALLOW_WORLD_READABLE_TMPFILES(default) = False
......
DEFAULT_HOST_LIST(/home/furongwang/web/ansible.cfg) = ['/home/furongwang/web/inventory']
......
HOST_KEY_CHECKING(default) = True
......
ansible-config list

查看所有配置参数用途,配置位置等。

DEFAULT_HOST_LIST:default: /etc/ansible/hostsdescription: Comma separated list of Ansible inventory sourcesenv:- {name: ANSIBLE_INVENTORY}expand_relative_paths: trueini:- {key: inventory, section: defaults}name: Inventory Sourcetype: pathlistyaml: {key: defaults.inventory}
localhost 连接

默认Ansible连接到受管主机的协议为 smart (通常采用最有效的方式 - SSH)。如本地清单中并未指定localhost,Ansible会隐式设置localhost,并使用local连接类型连接localhost。

  • local连接类型会忽略remote_user的设置,并且直接在本地系统上运行命令。
  • 如果使用了特权提升,此时ansible将会在运行sudo时使用运行Ansible命令的账户的身份进行提权,而非remote_user所指定的账户。

更改 localhost 连接方式:清单中包涵 localhost。

运行 AD HOC 命令

实验环境
[furongwang@controller ~]$ mkdir web && cd web[furongwang@controller web]$ cat > ansible.cfg <<'EOF'
[defaults]
remote_user = furongwang
inventory = ./inventory[privilege_escalation]
become = True
become_user = root
become_method = sudo
become_ask_pass = False
EOF[furongwang@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 软件包
  • 系统模块
    • ansible.posix.firewalld: 使用firewalld管理任意端口和服务
    • reboot: 重新启动计算机
    • service: 管理服务
    • user、group: 管理用户和组帐户
  • NetTools模块
    • get_url: 通过HTTP、HTTPS或FTP下载文件
    • nmcli: 管理网络
    • uri: 与 Web 服务交互
ansible-doc 命令
[furongwang@controller ~]$ ansible-doc -h
Usage: ansible-doc [-l|-F|-s] [options] [-t <plugin type> ] [plugin]plugin documentation toolOptions:-h, --help            show this help message and exit-j, --json            **For internal testing only** Dump json metadata forall plugins.-l, --list            List available plugins-F, --list_files      Show plugin names and their source files withoutsummaries (implies --list)-M MODULE_PATH, --module-path=MODULE_PATHprepend 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 enableconnection debugging)--version             show program's version number, config file location,configured module search path, module location,executable location and exitSee man pages for Ansible CLI options or website for tutorials
https://docs.ansible.com

示例:

# 查看模块清单及说明
[furongwang@controller ~]$ ansible-doc -l
fortios_router_community_list                Configure community lists i...
azure_rm_devtestlab_info                     Get Azure DevTest Lab facts
......# 查看模块清单及位置
[furongwang@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....
......# 查看特定模块说明文档
[furongwang@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):- appendIf `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 managementutilities. However they generally come pre-installed with thesystem and Ansible will require they are present at runtime. Ifthey are not, a descriptive error message will be shown.
... ...# 参考信息
SEE ALSO:* Module authorized_keyThe 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: johndcomment: John Doeuid: 1040group: admin
... ...# 模块返回值说明
RETURN VALUES:append:description: Whether or not to append the user to groupsreturned: When state is 'present' and the user existstype: boolsample: True
... ...

如果现有的模块无法实现现有需求,用户也可以自行编写模块:

  • Ansible会从变量ANSIBLE_LIBRARY中查找模块
  • 如果该变量未设置,将会从ansible.cfg配置文件library设置的位置查找模块
command 模块

command 模块允许管理员在受管节点的命令行中运行任意命令。要运行的命令通过-a选项指定为该模块的参数。

[furongwang@controller web]$ ansible node1 -m command -a 'hostname'
node1 | CHANGED | rc=0 >>
node1.furongwang.cloud[furongwang@controller web]$ ansible node1 -m command -a 'hostname' -o
node1 | CHANGED | rc=0 | (stdout) node1.furongwang.cloud

说明:

  • command 模块执行的远程命令不受受管节点上的shell处理,无法访问shell环境变量,也不能执行重定向和传送等shell操作。
  • 如果临时命令没有指定模块,Ansible默认使用command模块。
shell 模块

shell模块允许您将要执行的命令作为参数传递给该模块。 Ansible随后对受管节点远程执行该命令。与command模块不同的是, 这些命令将通过受管节点上的shell进行处理。因此,可以访问shell环境变量,也可使用重定向和管道等shell操作。

[furongwang@controller web]$ ansible node1 -m command -a set
node1 | FAILED | rc=2 >>
[Errno 2] No such file or directory: 'set': 'set'[furongwang@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。

ansible AD HOC 命令选项

临时命令选项优先级高于配置文件中配置。

配置文件指令命令行选项
inventory-i
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
http://www.xdnf.cn/news/1285615.html

相关文章:

  • ncurses 6.5 交叉编译移植到OpenHarmomy
  • 【软考中级网络工程师】知识点之 IP QoS 技术
  • 小红书笔记信息获取_实在智能RPA源码解读
  • 【Redis优化深度剖析:如何通过读写分离提升系统性能】
  • 【限时分享:Hadoop+Spark+Vue技术栈电信客服数据分析系统完整实现方案
  • Rocky Linux 10 部署 Kafka 集群
  • Bevy渲染引擎核心技术深度解析:架构、体积雾与Meshlet渲染
  • AI-调查研究-49-大数据调研报告 发展历程:从概念诞生到多元化生态1997-2025
  • msyql中,max_connections和max_user_connections区别
  • 【DL】深层神经网络
  • 记录docker使用kong consul postgresql配置dns异常解决
  • SQL180 每类试卷得分前3名
  • 【Redis在在线表单提交防重复机制中的应用策略】
  • 移动端调用大模型详解
  • Web学习笔记5
  • [git] 重配ssh key | 解决冲突
  • 一键生成 Android 适配不同分辨率尺寸的图片
  • Wireshark专家模式定位网络故障:14种TCP异常深度解剖
  • Ceph存储池参数中pg_num和pgp_num的关系
  • 终端安全检测和防御技术
  • 华为发布AI推理新技术,降低对HBM内存依赖
  • 负载均衡详解
  • 纯CSS+JS制作抽奖大转盘
  • C#教程之NPOI读写excel文件XLS,XLSX格式
  • 【vue(二)Vuex】
  • damn the jvm again(2)
  • 《Qwen2.5-VL 》论文精读笔记
  • 【测试】Bug+设计测试用例
  • 【Bug经验分享】由jsonObject-TypeReference引发的序列化问题
  • 无人机在环保监测中的应用:低空经济发展的智能监测与高效治理