基礎ansible命令
ansible採用ssh的方式操作遠程機器,首先我們需要在ansible所在機器創建一個hosts
文件記錄要操作機器的ip。
[root@vm1 ansible-test]# cat hosts
[master]
192.168.178.129
[node]
192.168.178.130
# 設置k8s組包含這倆組
[k8s:children]
master
node
# 設置組中每個ip包含的變量
# 本例中設置了ssh的用戶名密碼
[k8s:vars]
ansible_ssh_user=root
ansible_ssh_pass=1234
[master]
和[node]
是爲一組ip起的名字,同時它們屬於[k8s]
組。
然後嘗試命令:
[root@vm1 ansible-test]# ansible -i hosts all -m ping
其中,-i
指定了hosts
文件,all
指的是操作目標爲hosts中的所有組,也可以寫node就只操作node組的ip了,-m
指定模塊,本例是ping
模塊,即執行ping命令。
繼續嘗試命令:
[root@vm1 ansible-test]# ansible -i hosts all -a "ls"
該命令讓目標機器執行ls
命令。
以上這些只能一次命令執行一個操作,下面介紹ansible-playbook命令,可以一次命令執行多個操作。
ansible-playbook
創建一個play-test.yml
文件,內容如下:
[root@vm1 ansible-test]# cat play-test.yml
- name: say 'hello world'
hosts: all
tasks:
- name: echo 'hello world'
command: echo 'hello world'
register: result
- name: print stdout
debug: var=result.stdout
其中,tasks
可以包含多個操作,這裏第一個操作是輸出hello world字符,通過register
將命令echo 'hello world'
的輸出結果記錄到了變量result
中。第二個命令是將變量result
打印出來,不然命令輸出結果是不顯示的。
執行該腳本:
[root@vm1 ansible-test]# ansible-playbook -i hosts play-test.yml
roles
當我們需要操作的機器越來越多,執行的命令也越來越多,爲了方便管理和增強複用性,可以使用roles。
[root@vm1 ansible-test]# mkdir roles && cd roles
[root@vm1 roles]# ansible-galaxy init test-role
- test-role was created successfully
[root@vm1 roles]# tree .
.
└── test-role
├── defaults
│ └── main.yml
├── files
├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── README.md
├── tasks
│ └── main.yml
├── templates
├── tests
│ ├── inventory
│ └── test.yml
└── vars
└── main.yml
9 directories, 8 files
在roles
目錄下可以包含多個我們創建的role,各個role去做各自的操作方便管理,這裏用了ansible-galaxy init test-role
直接初始化了一個名爲test-role
的role,目錄結構含義可以百度,這裏關心tasks
裏的main.yml
即可,它是整個role的主入口,修改它的內容:
[root@vm1 ansible-test]# cat roles/test-role/tasks/main.yml
# shell module可以執行shell命令
- name: shell command
shell: ls -a /home
# copy module類似scp命令,傳文件
- name: copy file, like scp
copy:
src: /home/test.yml
dest: /tmp/test/
owner: root
group: root
mode: 0644
# file module可以創建或者修改文件/文件夾屬性
- name: mkdir
file:
path: /tmp/file-mkdir-test
state: directory
owner: root
group: root
mode: 0700
# service module類似service命令,管理服務
- name: stop firewall
service:
name: firewalld
state: stopped
enabled: no
# lineinfile module可以Manage lines in text files
# 在/etc/hosts文件裏用"hahaha"取代開頭爲"666.666"的一行。
- name: set 666.666 as hahaha
lineinfile:
dest: /etc/hosts
regexp: '^666\.666'
line: 'hahaha'
各個操作都有name
,以及對應的模塊的關鍵字。
在roles
目錄的同級創建文件play-role-test.yml
,內容如下:
[root@vm1 ansible-test]# cat play-role-test.yml
- hosts: node
roles:
- test-role
該文件指定了操作對象爲hosts
文件中的node
組,使用的role是test-role
。
然後執行即可:
[root@vm1 ansible-test]# ansible-playbook -i hosts play-role-test.yml