shell+ansible汇总远程主机开销(hosts文件加解密)

秒速五厘米 2022-11-11 05:27 276阅读 0赞

ansible hosts 格式

  1. name1 ansible_ssh_host=*.*.*.* ansible_ssh_user=root ansible_ssh_pass=* ansible_ssh_port=22
  2. name2 ansible_ssh_host=*.*.*.* ansible_ssh_user=root ansible_ssh_pass=* ansible_ssh_port=22
  • name1 :别名,可以写服务器名称
  • ansible_ssh_user:登陆账号,默认值在ansible.cfg中定义
  • ansible_ssh_pass:登陆密码
  • ansible_ssh_port:登录端口

注意:密码有#等特殊字符会导致登陆失败,需要加上转义
加、解密 hosts

  1. [root@yx01 ansible_playbook]# ansible-vault encrypt /etc/ansible/hosts
  2. New Vault password:
  3. Confirm New Vault password:
  4. Encryption successful

在这里插入图片描述

  1. ansible-vault decrypt /etc/ansible/hosts

在这里插入图片描述

playbook code

  1. ---
  2. - hosts: all
  3. remote_user: root
  4. gather_facts: True
  5. tasks:
  6. - name: 休眠10秒,防止刚开始登陆负载飙升
  7. shell: "sleep 10"
  8. - name: 过滤负载信息
  9. shell: "top -c -n 1 -b|grep load|grep -v grep|awk '{print $(NF-2),$(NF-1),$NF}'"
  10. - name: 过滤cpu信息
  11. shell: "top -c -n 1 -b|grep Cpu|grep -v grep|cut -c 10-"

shell code

  1. #!/bin/bash
  2. localtime=`date "+%Y-%m-%d_%H:%M:%S"`
  3. logfile=logs/${ localtime}.txt
  4. if [ "$(ls -A logs)" ]
  5. then
  6. echo "-------start time:$localtime-------"
  7. rm -rf logs/*
  8. fi
  9. # 获取信息,--verbose将执行回显输出
  10. # 添加 --ask-vault-pass参数手动交互式的输入密码
  11. # 添加 --vault-password-file 指定存放密码的文件
  12. ansible-playbook collect.yml --verbose > logs/tempfile.txt
  13. # 过滤负载信息
  14. cat logs/tempfile.txt |grep load|awk '{print $(NF-2),$(NF-1),$NF}'|sed 's/\[\"//g'|sed 's/\"\]\}//g' > $logfile
  15. # 过滤cpu信息
  16. cat logs/tempfile.txt|grep Cpu|egrep -o "\[\".*\"\]\}"|sed 's/\[\"//g'|sed 's/\"\]\}//g' >> $logfile
  17. localtime=`date "+%Y-%m-%d_%H:%M:%S"`
  18. echo "-------end time:$localtime-------"

解决ansible首次连接host服务器需验证问题

  1. "msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host."

修改/etc/ansible/ansible.cfg,放开注释
在这里插入图片描述
输出结果

  1. 9.31, 6.05, 6.05
  2. 22.5 us, 5.6 sy, 0.0 ni, 70.4 id, 0.0 wa, 0.0 hi, 1.4 si, 0.0 st

发表评论

表情:
评论列表 (有 0 条评论,276人围观)

还没有评论,来说两句吧...

相关阅读