1. 程式人生 > >ansible中playbook使用

ansible中playbook使用

palybook使用

#####定義/etc/ansible/hosts

兩種方式:

基於ssh密碼登入

不配置免密碼登入,需要在hosts檔案中配置

第一種:基於ssh密碼登入

引數一:inventory
ansible的主要功能用於批量管理主機操作,便捷的使用部分主機,可以在inventory file中分組
預設的inventory file為/etc/ansible/hosts

1.inventory檔案格式
同一主機歸併到一個或者多個組中,主機使用非預設的22埠,也可以在主機名稱後加冒號埠標明

www.ab.com
[webservers] www.abc.com:222 www.abcd.com [dbservers] db1.abc.com db2.abc.com db3.abc.com

 如果主機遵循相似的命名模式,可以使用列表標記各個主機

[webserver]
www[01:30].example.com

[dbserver]
db-[a:f].example.com

 2.主機變數
可以在定義主機時新增遠端主機變數便於在playbook中使用{http中的變數,在j2中配置}

[webserver]
www.ab.com http_port=80 maxRequestsPerChild=808
www.abc.com http_port=8080 maxRequestsPerChild=909

 3.組變數
賦予指定組內的所有主機在playbook中用的變數(vars)
可以呼叫組裡面的變數。

[webserver]
www.ab.com
www.bc.com
[webserver:vars]
host_port=80
maxRequestsPerChild=890

4.組巢狀
組還包括其他組,可以在其他組中指定變數,只能在ansible-playbook中使用,ansible不支援
children中包括apache,nginx的主機。,共四臺主機

[apache]
http1.abc.com
http2.abc.com
[nginx]
nginx1.abc.com
nginx2.abc.com
[webservers:children]
apache
nginx
[webservers:vars]
host_port=80

 ansible基於ssh連線inventory可以指定遠端主機,通過引數指定互動式,引數如下:

ansible_ssh_host
ansible_ssh_port
ansible_ssh_user
ansible_ssh_pass
ansible_sudo_pass
ansible_connection
ansible_ssh_private_key_file
ansible_shell_type
ansible_python_interpreter

第二種:不基於ssh免密碼登入

即便是我們沒有做關於祕鑰的認證,我們也會自動使用賬戶和密碼來登入該主機。

[webservers]
192.168.133.2 ansible_ssh_user=root ansible_ssh_pass=123456
192.168.133.3 testvar="2.100

 ####基本結構

module_name: module_args   模組名和模組引數

- host: webserver
  remote_user:
  task:
  - task1
    module_name: module_args
    - name: test connection
      ping:
      remote_user; www
      sudo: yes
      command: /sbin/setenforce 0
      shell: /usr/bin/somecommand || /bin/true
      ignore_errors: True
  - task2
    module_name: module_args

- host:dbservers

 在執行playbook是中途發生錯誤,可能會回滾,更正後,重新執行一次。
可以指定使用sudo的方式遠端執行任務,用sudo到root使用者執行命令。
眾多模組中,只有command和shell模組僅使用給定一個列表而無需使用"key=value"
命令或指令碼的退出碼不為0,可以使用如上替代,命令不成功強行成功。
使用ignore_errors忽略錯誤資訊



handlers:

  在notify中列出的操作為handler,比如之前配置了apache的配置檔案,http.conf埠發生變化後,重新執行ansible-playbook後,檢視遠端的埠,並未發生變化。需要用到notify

引入變數:
    vars:在後面新增變數名,然後再引入變數,必須加{{}},用變數名替換。

- host: webservers
  remote_user: root
vars:
- packages: httpd tasks: - name: install httpd packages yum: name={{ packages }} state=lastest - name: install configuration file for httpd copy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf notify: - restart httpd - name: start httpd service service: enabled=true name={{ packages }} state=started handlers: - name: restart httpd service: name={{ packages }} state=restarted