您的位置:首页 > 其它

Ansible Ad-Hoc 常用命令

2018-08-01 14:46 387 查看

Ansible Ad-Hoc常用命令

Ansible可以通过命令行形式使用它的模块,Ansible自带了很多模块,可以直接使用这些模块。目前Ansible已经自带了259个模块,可以通过ansible-doc -l 显示所有自带的模块,也可以通过ansible-doc -s 模块名 查看模块的介绍及使用示例。

Ansible命令行的基本格式如下:

ansible <host-pattern> [-m modult_name] [-a agrs]

基本语法说明:

<host-pattern> :主机
[-m modult_name] :模块名
[-a agrs]:模块的参数

列出可使用的模块名称:

ansible-doc -l

列出某个模块的描述信息和使用示例:

ansible-doc -s yum

command模块(默认)

Ansible管理工具使用-m选项来指定使用模块,默认使用command模块,即-m选项省略时会运行此选项,用于在被管理节点上运行命令

1.对所有被管节点连通性进行测试

ansible all -m ping

2.查询被管节点的系统时间

ansible webserver -m command -a 'date'

cron模块 计划性任务 (两种状态state: present:添加,absent:移除)

Ansible中的cron模块用于定义计划性任务。其中有两种状态(state):present表示添加(省略状态时默认使用),absent表示移除

1.添加计划性任务

ansible webserver -m cron -a 'minute="*/10" job="/usr/bin/echo hello" name="test cron job"'

2.查询系统计划性任务

ansible webserver -a 'crontab -l'

3.移除该计划性任务

ansible webserver -m cron -a 'minute="*/10" job="/usr/bin/echo hello" name="test cron job" state=absent'

user模块

Ansible中的user模块用于创建新用户和更改、删除已存在的用户。

1.创建用户user1

ansible webserver -m user -a 'name="user1"'


2.删除用户mysql

ansible webserver -m user -a 'name="user1" state=absent'

group模块

Ansible中的group模块用于对用户组进行管理

1.创建mysql组

ansible webserver -m group -a 'name=mysql gid=306 system=yes'

2.新建mysql组的user2用户

ansible webserver -m user -a 'name=user2 uid=306 system=yes group=mysql'

copy模块

Ansible中的copy模块用于实现文件复制和批量下发文件,其中使用src定义本地源文件路径,dest定义被管理主机文件路径,使用content则是通过指定信息内容来生成目标文件

1.复制文件

ansible webserver -m copy -a 'src=/etc/fstab dest=/tmp/fstab.txt owner=root mode=600'

2.查看复制后的文件

ansible webserver -a 'cat /tmp/fstab.txt'

file模块

在Ansible中使用file模块来设置文件属性,其中path指定文件路径,src指定源文件路径,使用name和dest来替换创建文件的符号链接

1.修改文件的属性

ansible webserver -m file -a 'owner=mysql group=mysql mode=644 path=/tmp/fstab.txt'

2.创建连接文件

ansible webserver -m file -a 'path=/tmp/fstab.link src=/tmp/fstab.txt state=link'

3.创建空问文件/tmp/test1.txt

ansible webserver -m file -a 'path=/tmp/test1.txt state=touch'

ping模块

Ansible中使用ping模块来检测指定主机的连通性

ansible all -m ping

shell模块

Ansible中的shell模块可以在被管理节点上运行命令,并支持像管道符等功能的复杂命令。

1.创建user3用户

ansible webserver -m user -a 'name=user3'

2.设置user3用户的密码

ansible webserver -m shell -a 'echo abc123|passwd --stdin user3'

script模块

Ansible中的script模块可以将本地脚本文件复制到被管理节点上进行运行(需使用相对路径来指定脚本)。

yum模块

Ansible中的yum模块负责在被管理节点上安装与卸载软件包,但是需要提前在每个节点配置自己的yum仓库。其中name指定要安装的软件包名(可以指定版本号,不指定则安装最新版),state指定安装软件包的状态,present表示安装,absent表示卸载。

1.安装httpd软件包

ansible webserver -m yum -a 'name=httpd'

2.被控节点查询

rpm -q httpd

3.卸载httpd软件包

ansible webserver -m yum -a 'name=httpd state=absent'

service模块

在Ansible中使用service模块来控制管理服务的运行状态,其中enabled表示是否开启自启动(true或false),name定义服务名称,state指定服务状态(started、stoped、restarted)。

1.启动httpd服务并添加系统管理

ansible webserver -m service -a 'enable=true name=httpd state=started'

2.查看httpd启动状态信息

ansible webserver -a 'service httpd status'

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Ansible Ad Hoc