天天看點

ansible學習筆記一:子產品需求:環境:常用子產品:

ansible學習筆記一:子產品

  • 需求:
  • 環境:
  • 常用子產品:
      • 1. cron子產品
      • 2. script子產品
      • 3. yum子產品
      • 4. service子產品
      • 5. user子產品
      • 6. group子產品
      • 7. copy子產品
      • 8. shell子產品

需求:

公司内随着機器使用的越來越多,按照之前的方式已經使用不便了,需要使用ansible批量管理了,這裡用測試執行個體驗證一次,做為學習筆記。

環境:

因為自己筆記本性能問題,這裡隻用兩台虛拟機做測試:

伺服器名 IP
ansible-server 192.168.31.53
ansible-client 192.168.31.167

安裝的話,這裡就不詳細的說明了,因為太簡單了。。因為我用的是centos7,直接yum安裝就好了。。配置的話,其實我隻是在/etc/ansible/hosts末尾加上了我的client主機,就開始做了測試了。下面從常用子產品開始吧。

常用子產品:

1. cron子產品

  • 這個子產品是添加/删除定時任務的。
  • 例如:
  • 每周1,3,5做定時報警
ansible all -m cron -a ‘minute=* week=1,3,5 job="/usr/bin/wall FBI warnging" name=warngingcron’

2. script子產品

  • 本地寫好腳本,加上執行權限之後,可以不需要分發到各伺服器上,直接能看到執行結果,這樣就省了copy子產品的一次操作
  • 例如:
ansible all -m script -a ‘/root/f1.sh’

3. yum子產品

  • 這裡的操作其實很簡單,直接就是安裝

ansible all -m yum -a ‘name=httpd’

ansible all -m yum -a ‘name=nginx’

  • 清理緩存,并安裝
ansible all -m yum -a ‘name=dstat update_cache=yes’

4. service子產品

  • 這個子產品是對服務的狀态程序操作的
  • 例如:
  • 啟動httpd服務并添加開啟自啟
ansible all -m service -a ‘name=httpd state=started enabled=yes’

5. user子產品

  • 這個子產品是對使用者的操作的
  • 例如:
  • 可以用name指定使用者名,system指定是否系統使用者,home指定家目錄,groups指定屬組,comment指定說明
ansible all -m user -a ‘name=nginx shell=/sbin/nologin system=yes home=/var/nginx groups=root,bin comment=“nginx service”’
  • 查詢

[[email protected] ~]# ansible all -a ‘getent passwd nginx’

192.168.31.167 | CHANGED | rc=0 >>

nginx❌988:982:nginx service:/var/nginx:/sbin/nologin

  • 删除使用者
ansible all -m user -a ‘name=ngixn state=absent remove=yes’

6. group子產品

  • 這個子產品是對使用者組程序操作的
  • 例如:
  • 添加使用者組
ansible all -m group -a ‘name=nginx system=yes gid=999’
  • 删除使用者組
ansible all -m group -a ‘name=nginx state=absent’
  • 查詢組資訊
ansible all -a ‘getent group nginx’

7. copy子產品

  • 這個子產品是對檔案進行複制操作的
  • 例如
ansible all -m copy -a ‘src=/root/file dest=/root/ mode=755’

8. shell子產品

  • 這個子產品其實是實際使用中用到最多的子產品,這個子產品基本快成萬能子產品了。。當然,你需要提前熟悉linux指令。當然這裡需要注意下單引号和雙引号的問題。
  • 例如:
  • 過濾/root/file檔案内容
ansible all -m shell -a ‘grep 123 /root/file’
  • 複制檔案到其他地方
ansible all -m shell -a ‘cp /root/file /opt’
  • 删除使用者及家目錄
ansible all -m shell -a ’ userdel -r test1’

繼續閱讀