1. 程式人生 > >ansible 基本操作(初試)

ansible 基本操作(初試)

color 逗號 基本 book centos 信息 免密鑰 rec 判斷

ansible 初級使用 yum install ansible -y 設置本機免密鑰登錄到 192.168.1.21 ssh-copy-id 192.168.1.21 vim /etc/ansible/hosts 添加2行 [web] 192.168.1.21 命令行操作方法,:ansible 主機組或ip -m 指定模塊 -a 模塊對應的參數 ansible 192.168.1.21 -m shell -a "echo hello" 192.168.1.21 | SUCCESS | rc=0 >> hello ansible 192.168.1.21 -m setup # 主機所有信息 ansible 192.168.1.21 -m setup -a "filter=ansible_hostname" # 用setup模塊取得主機名 192.168.1.21 | SUCCESS => { "ansible_facts": { "ansible_hostname": "21hostname" }, "changed": false } ansible web -m shell -a "echo hello" 192.168.1.21 | SUCCESS | rc=0 >> hello 編寫簡單的play-book cat test.yml --- - hosts: 192.168.1.21 tasks: - name: just test ansible shell: echo hello - name: get hostname setup: filter=ansible_hostname 執行 ansible-play test.yml PLAY [192.168.1.21] ******************************************************************************************************************************************************** TASK [Gathering Facts] ***************************************************************************************************************************************************** ok: [192.168.1.21] TASK [just test ansible] *************************************************************************************************************************************************** changed: [192.168.1.21] TASK [get hostname] ******************************************************************************************************************************************************** ok: [192.168.1.21] PLAY RECAP ***************************************************************************************************************************************************************** 192.168.1.21 : ok=3 changed=1 unreachable=0 failed=0 如需要指定其他ip,可以 --- - hosts: all # 這改成all tasks: - name: just test ansible shell: echo hello - name: get hostname setup: filter=ansible_hostname ansible-playbook -i '192.168.1.21,' test.yml # -i 指定執行清單 記得192.168.1.21, 後面有逗號. play-book 中傳入默認變量 --- - hosts: 192.168.1.146 remote_user: root vars: - hello: hello-world # 設定hello 變量的默認值為 hello-world gather_facts: false # 可選參數 tasks: - name: var test shell: echo {{ hello }} > /dev/pts/0 ansible-play a.yml 輸出為hello-world ansible-play a.yml -e hello=xiaoming 輸出為小明 ansible play-book 一個套路,記得最基本的方法,使用其他模塊一樣的。 play-book 中做條件判斷 - name: check kafka shell: pip list | grep kafka | wc -l ignore_errors: True register: check_kafka - name: pip install kafka-1.3.5 shell: pip install {{ item }} with_items: - kafka when: check_kafka.stdout == "0" 判斷是否已經安裝了kafka 沒安裝則安裝,已安裝則跳過。 - name: install zabbix-agent for centos-7 yum: name=zabbix22-agent.x86_64 state=present when: ansible_os_family == "RedHat" and ansible_distribution_major_version == "7" 判斷是否是redhat或centos 7 版本,來安裝對應的包。


ansible 基本操作(初試)