ansible入门指南 - 常用的Ad-Hoc指令

常用的Ad-Hoc指令

ansible命令的基本语法为

ansible -m module -a params -i inventory.yaml -f 5 -u username all

-m 指定运行的模块, 缺省值为 ansible.builtin.command , 即在服务器上直接运行命令
-a 指定模块的参数
-i 指定inventory文件
-f 指定同时运行的数量, 缺省值为5
-u 指定运行的用户, 缺省值为控制机当前用户

command

使用chino用户登录服务器, 切换到root用户重启机器

ansible all -a "/sbin/reboot" -f 10 -u chino --become root [--ask-become-pass] -i inventory.yaml

copy

ansible all -m copy -a 'src=/etc/hosts dest=/tmp/hosts mode=600' -i inventory.yaml

上面的指令把控制机上/etc/hosts文件复制到所有的被控机上, 并且文件的权限设置为600. 使用 ansible-doc copy指令可以查看所有的参数信息

file

ansible all -m file -a "dest=/tmp/path/to/c mode=755 owner=chino group=chino state=directory" -i inventory.yaml

上面的命令在被控机器上创建了 /tmp/path/to/c 目录, 并且设置了目录的权限和owner

yum

ansible webservers -m ansible.builtin.yum -a "name=acme state=absent"

yum模块用于管理系统安装的软件包, 对应的同样有apt模块, absent表示删除软件. 状态包含 present, installed, latest, absent, removed, 使用ansible-doc yum 查看详情

user

user模块在linux上建用户时只能接受加密过的密码, 可以使用下面的几种方式生成加密的密码, 根据需求修改密码和加密的salt

  1. 使用ansible的password_hash过滤器生成加密密码
ansible all -i localhost, -m debug -a "msg={{ 'mypassword' | password_hash('sha512', 'mysecretsalt') }}"
# msg的值即为创建用户时用到的密码
# localhost | SUCCESS => {
#     "msg": "$6$mysecretsalt$qJbapG68nyRab3gxvKWPUcs2g3t0oMHSHMnSKecYNpSi3CuZm.GbBqXO8BE6EI6P1JUefhA0qvD7b5LSh./PU1"
# }
  1. 使用passlib库创建密码, 需要安装好 passlib库, 即 pip install passlib
python -c "from passlib.hash import sha512_crypt; import getpass; print(sha512_crypt.using(rounds=5000).hash(getpass.getpass()))"

  1. 使用mkpasswd命令
# ubuntu上默认没有mkpasswd命令, 需要使用如下命令安装
sudo apt install whois
# 使用mkpasswd 生成密码
mkpasswd -m sha-512
# 创建foo用户, 并且把用户加到sudo组中
ansible -m user -a 'name=foo password=$6$mysecretsalt$qJbapG68nyRab3gxvKWPUcs2g3t0oMHSHMnSKecYNpSi3CuZm.GbBqXO8BE6EI6P1JUefhA0qvD7b5LSh./PU1 groups=sudo' all -i localhost, --become-user=root --become
# 删除foo用户
ansible -m user -a 'name=foo state=absent' all -i localhost, --become-user=root --become

service

service 模块用于管理服务器上的服务状态, state的可选值有 reloaded, restarted, started, stopped

ansible all -m service -a "name=httpd state=restarted" -i localhost,

setup

setup 模块用于收集系统信息, 这些信息可以用于在任务中根据条件执行任务

ansible all -m setup -i localhost,
posted @ 2023-08-18 16:11  Chinor  阅读(59)  评论(0编辑  收藏  举报