自动化工具ansible常用命令

2019年1月10日14:11:07 发表评论 3,612 ℃

ansible all -m ping  #检测主机连接

-m:指定模块

    copy    file     cron   group   user    yum   service   script    ping     command     raw    get_url    synchronize

    默认模块command

ansible all -a "free -m" #执行远程命令

    等同于ansible '*' -a "free -m"

    -a:模块参数

    *和all,表示定义在/etc/ansible/hosts的所有主机

ansible '*' -m file -a "dest=/tmp/t.sh mode=755 owner=root group=root" # 指定节点上的权限,属主和数组为root

ansible '*' -m file -a "dest=/tmp/test state=directory" # 创建文件夹

ansible '*' -m cron -a 'name="custom job" minute=*/3 hour=* day=* month=* weekday=* job="/usr/sbin/ntpdate 172.16.254.139"' #指定节点上定义一个计划任务,每隔3分钟到主控端更新一次时间

ansible all -m group -a 'gid=2017 name=a'  # 指定节点上创建一个组名为aaa,gid为2017的组

ansible all -m user -a 'name=aaa groups=aaa state=present'  # 在节点上创建一个用户aaa,组为aaa

ansible all -m user -a 'name=aaa groups=aaa remove=yes'  #删除用户示例

ansible all -m yum -a "state=present name=httpd"  # 在节点上安装httpd

ansible all -m service -a 'name=httpd state=started enabled=yes'  # 在节点上启动服务,并开机自启动

ansible '*' -m script -a '/root/test.sh'  # 执行主控端脚本

ansible '*' -m shell -a 'ps aux|grep zabbix'  # 执行远程主机的脚本

ansible '*' -m raw -a "ps aux|grep zabbix|awk '{print \$2}'" # 类似shell

ansible '*' -m file -a "src=/etc/resolv.conf dest=/tmp/resolv.conf state=link"  # 创建软链接

ansible '*' -m file -a "path=/tmp/resolv.conf state=absent"  # 删除软链接

ansible '*' -m copy -a "src=/etc/ansible/ansible.cfg dest=/tmp/ansible.cfg owner=root group=root mode=0644" # 复制文件到远程服务器

ansible all -m raw -a 'hostname|tee' # 在节点上运行hostname

ansible all -m get_url -a 'url=http://10.1.1.116/favicon.ico dest=/tmp'  # 将指定url上的文件下载到/tmp下

ynchronize模块:

    目的:将主控方/root/a目录推送到指定节点的/tmp目录下

    命令:ansible all -m synchronize -a 'src=/root/a dest=/tmp/ compress=yes'

    执行效果:

    delete=yes   使两边的内容一样(即以推送方为主)

    compress=yes  开启压缩,默认为开启

    --exclude=.git  忽略同步.git结尾的文件

由于模块,默认都是推送push。因此,如果你在使用拉取pull功能的时候,可以参考如下来实现mode=pull   更改推送模式为拉取模式

    目的:将10.1.1.113节点的/tmp/a目录拉取到主控节点的/root目录下

    命令:ansible 10.1.1.113 -m synchronize -a 'mode=pull src=/tmp/a dest=/root/'

    dest_port=22    # 指定目的主机的ssh端口,ansible配置文件中的 ansible_ssh_port 变量优先级高于该 dest_port 变量

    rsync_path      # 指定 rsync 命令来在远程服务器上运行。这个参考rsync命令的--rsync-path参数,--rsync-path=PATH     # 指定远程服务器上的rsync命令所在路径信息

    rsync_timeout   # 指定 rsync 操作的 IP 超时时间,和rsync命令的 --timeout 参数效果一样

【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: