Ansible - 9 - 技巧提示


Ansible 技巧提示

1 - Ansible 免密登錄

# 通過祕鑰方式連接
ssh-keygen -t rsa 
ssh-copy-id -i /vipxf/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /vipxf/.ssh/id_rsa.pub [email protected]

2 - Ansible playbook輸入root密碼

[root@test01 ansible-test]# cat test-temp.yaml 
---
- name: test-root
  hosts: ta
  remote_user: vipxf
  gather_facts: no
  become: yes
  become_user: root
  become_method: su
  become_flags: "-"
  vars:
    ansible_become_pass: "{{ root_pass_input }}"
  tasks:
    - name: test
      shell: date && sleep 3
      ignore_errors: True
[root@test01 ansible-test]# 
[root@test01 ansible-test]# ansible-playbook  test-temp.yaml -e root_pass_input=redhat

PLAY [test-root] **************************************************************************************************************************************************************************************************************

TASK [test] *******************************************************************************************************************************************************************************************************************
changed: [172.20.8.247]

PLAY RECAP ********************************************************************************************************************************************************************************************************************
172.20.8.247               : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

[root@test01 ansible-test]# 

3 - Ansible 簡單的複用方式

通過關鍵字include可以實現簡單的代碼複用。

# 在playbook中,Include 指令可以跟task 混合在一起使用
  - tasks:
      - include: tasks/foo.yml  # 引用配置文件

# 參數化的include
  - tasks: 
      - include: aaa.yml user=anliven  # 引用配置文件的同時傳入變量
      - include: bbb.yml pwd=P@ssw0rd

4 - Ansible task通知多個handlers任務

通過關鍵字listen爲handlers中的一個或多個觸發器任務指定主題,task就可以按主題名進行通知。
觸發順序按照handler定義的先後順序執行。

---
- hosts: ta
  remote_user: vipxf
  gather_facts: no
  vars:
    - package: vim
  tasks:
    - name: test-step one
      shell: echo "111" 
      notify: "test listen"  # task通知handlers主題
    - name: test-step two
      shell: echo "222"
  handlers:
    - name: check-hostname-date
      shell: hostname && date
      ignore_errors: True
      listen: "test listen"  # 按照定義順序被觸發
    - name: who-am-i
      shell: whoami && date
      ignore_errors: True
      listen: "test listen"  # 按照定義順序被觸發

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章