ansible 基本使用


安裝ansible

yum install ansble

ansible用ssh管理主機,可以用密鑰登陸,也可以用密碼登錄

密碼免輸入登錄(sshpass需要有這個服務)

添加主機,端口,賬號,密碼  /etc/ansible/hosts

[cs]
192.168.43.201 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass=wangwei
192.168.43.202 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass=wangwei

在/etc/ansible/ansible.cfg配置文件中刪除 host_key_checking = False 前面的#,因為ansible登錄節點主機時會獲取key,然后造成報錯。

管理節點的命令

ansible -i /etc/ansible/hosts web -m ping     #/etc/ansible/hosts節點管理路徑, web組

[root@centos01 ~]# vim /etc/ansible/hosts
............   <!--此處省略部分內容-->
[web]
192.168.100.20
192.168.100.30
[test]
www.benet.com:222                         <!--通過222端口管理設備-->
[mail]
yj1.kgc.cn
yj[2:5].kgc.cn
<!--[2:5]表示2~5之間的所有數字,即表示yj2.kgc.cn、yj3.kgc.cn……的所有主機-->

ansible web -m command -a "systemctl status httpd" --limit "192.168.100.20"  #發送命令給web組192.168.100.20節點主機

ansible web -m command -a "systemctl status httpd" #發送命令給web組的所有主機

 批量復制文件到節點主機用yml,然后用

ansible-playbook copy.yml執行

---

- name: copy file

  hosts: 192.168.43.201 192.168.43.202

  tasks:

  - name: copy ifcfg

    copy:

      src: /etc/docker/daemon.json

      dest: /root

 command不支持管道,這里用shell

ansible cs -m shell -a "ps -ef|grep httpd"

用copy傳文件到節點主機

ansible ziji -m copy -a "src=/root/1.txt dest=/tmp owner=hailin group=hailin mode=0755" (src源文件 dest目標位置 owner文件用戶 group文件組 mode文件權限)

用stat查看節點主機某文件信息

ansible ziji -m stat -a "path=/tmp/1.txt"

lineinfile用這個模塊對文件內容進行操作

ansible centos7 -m lineinfile -a "dest=/etc/selinux/config regexp='SELINUX=enforcing' line='SELINUX=disabled'"  #把SELINUX=enforcing替換成SELINUX=disabled

yum模塊

ansible centos7 -m yum -a "name=ntp state=latest" #安裝ntp

 file模塊

ansible centos7 -m file -a "src=/usr/share/zoneinfo/Asia/Shanghai dest=/etc/localtime state=link"  #創建軟鏈接

 

非root權限執行

sudo ansible 2 -m copy -a "src=/etc/apt/sources.list dest=/etc/apt/ owner=devteam group=devteam mode=655" -u devteam --sudo

 

切換其他用戶執行命令

sz2 ansible_ssh_user=devteam ansible_become_pass="123456"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM