準(zhǔn)備工作:
安裝方式:這里我們選擇使用yum直接安裝
server端操作系統(tǒng):Centos 7
修改鏡像源為阿里云的源
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bak
curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
yum clean all
yum makecache
yum install -y epel-release # 需要epel源支持
安裝
yum install -y ansible
檢查是否安裝成功:
[root@harbor ~]# ansible --version
ansible 2.9.3
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Aug 7 2019, 00:51:29) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]
命令補全
https://github.com/dysosmus/ansible-completion
[root@harbor ansible]# wget https://github.com/dysosmus/ansible-completion/raw/master/ansible-completion.bash
[root@harbor ansible]# wget https://github.com/dysosmus/ansible-completion/raw/master/ansible-doc-completion.bash
[root@harbor ansible]# wget https://github.com/dysosmus/ansible-completion/raw/master/ansible-galaxy-completion.bash
[root@harbor ansible]# wget https://github.com/dysosmus/ansible-completion/raw/master/ansible-playbook-completion.bash
[root@harbor ansible]# wget https://github.com/dysosmus/ansible-completion/raw/master/ansible-pull-completion.bash
[root@harbor ansible]# wget https://github.com/dysosmus/ansible-completion/raw/master/ansible-vault-completion.bash
[root@harbor ansible]# cp * /etc/bash_completion.d/
[root@harbor ansible]# source /etc/profile.d/bash_completion.sh
# 如果沒效果就執(zhí)行 source /etc/bashrc
開啟日志記錄:
vim /etc/ansible/ansible.cfg # 取消注釋下面這行
log_path = /var/log/ansible.log
ansible 程序結(jié)構(gòu)
安裝目錄如下(yum安裝):
配置文件目錄:/etc/ansible/
執(zhí)行文件目錄:/usr/bin/
Lib庫依賴目錄:/usr/lib/pythonX.X/site-packages/ansible/
Help文檔目錄:/usr/share/doc/ansible-X.X.X/
Man文檔目錄:/usr/share/man/man1/
初始化
添加被管機IP
編輯(或創(chuàng)建)/etc/ansible/hosts 并在其中加入一個或多個遠(yuǎn)程系統(tǒng).你的public SSH key必須在這些系統(tǒng)的authorized_keys
中:
這里根據(jù)需求我添加了6臺服務(wù)器:
[root@harbor harbor]# cat /etc/ansible/hosts |grep "^\s*[^# \t].*$"
[k8s_master]
k8s-master[01:03]
[k8s_node]
k8s-node[01:03]
收集被管機公鑰或者關(guān)閉公鑰認(rèn)證(二選一即可)
收集被管服務(wù)器的公鑰做公鑰認(rèn)證,它的目的是創(chuàng)建和驗證“ssh_known_hosts”文件
ssh-keyscan k8s-master01 k8s-master02 k8s-master03 k8s-node01 k8s-node02 k8s-node03 >> /root/.ssh/known_hosts
如果不想啟用公鑰認(rèn)證(推薦)
關(guān)閉公鑰認(rèn)證的方法有兩種(推薦):
- 編輯ansible.cfg配置文件 (/etc/ansible/ansible.cfg)
[defaults]
host_key_checking = False
- 直接設(shè)置環(huán)境變量
命令為:
export ANSIBLE_HOST_KEY_CHECKING=False
創(chuàng)建公鑰
[root@harbor ansible]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:CobRTxn2/KOf4a3Q2Ks/0ReP50bVZtMnBiDzJ7euwNM root@harbor
The key's randomart image is:
+---[RSA 2048]----+
| o o .. |
| . . = + . |
| . . o o o o. o|
| o o . + .+.B|
| . o . S o... B+|
| . . o *.o. o +|
| . B E... + |
| *.* o|
| .oOo. . |
+----[SHA256]-----+
編寫Playbook劇本文件
[root@harbor harbor]# cd /etc/ansible/
[root@harbor ansible]# ls
ansible.cfg hosts roles
[root@harbor ansible]# vim ssh.yml
[root@harbor ansible]# cat ssh.yml # 這里的hosts參數(shù)可以改變?yōu)橹付ǖ膆ost組
---
- hosts: all
gather_facts: no
tasks:
- name: install ssh key
authorized_key: user=root
key="{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"
state=present
運行playbook文件做免密認(rèn)證
[root@harbor ansible]# ansible-playbook -i hosts ssh.yml -k # 如果需要使用其他用戶添加-u xxx
SSH password:
PLAY [all] ********************************************************************************************************************************************************************************************************
TASK [install ssh key] ********************************************************************************************************************************************************************************************
changed: [k8s-master02]
changed: [k8s-master01]
changed: [k8s-master03]
changed: [k8s-node02]
changed: [k8s-node01]
changed: [k8s-node03]
PLAY RECAP ********************************************************************************************************************************************************************************************************
k8s-master01 : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
k8s-master02 : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
k8s-master03 : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
k8s-node01 : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
k8s-node02 : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
k8s-node03 : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
輸入密碼后應(yīng)該都會被加入被管了吱殉,執(zhí)行下命令測試一下
[root@harbor ansible]# ansible k8s_master -m ping
k8s-master02 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
k8s-master03 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
k8s-master01 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
[root@harbor ansible]# ansible k8s_node -m ping
k8s-node01 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
k8s-node02 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
k8s-node03 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
[root@harbor ansible]# cat ~/.ssh/known_hosts # 可以看到都已經(jīng)添加進去了
k8s-master01,192.168.1.50 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBM221wY62j/3BRakXcMfnhNZtK68XmM3UpFskgtWT/kVknc44MuNsLuwP/zTTO9b7EhQbK70yHlRkHfHG3fHU4A=
k8s-master03,192.168.1.52 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBM221wY62j/3BRakXcMfnhNZtK68XmM3UpFskgtWT/kVknc44MuNsLuwP/zTTO9b7EhQbK70yHlRkHfHG3fHU4A=
k8s-master02,192.168.1.51 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBM221wY62j/3BRakXcMfnhNZtK68XmM3UpFskgtWT/kVknc44MuNsLuwP/zTTO9b7EhQbK70yHlRkHfHG3fHU4A=
k8s-node02,192.168.1.61 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBM221wY62j/3BRakXcMfnhNZtK68XmM3UpFskgtWT/kVknc44MuNsLuwP/zTTO9b7EhQbK70yHlRkHfHG3fHU4A=
k8s-node01,192.168.1.60 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBM221wY62j/3BRakXcMfnhNZtK68XmM3UpFskgtWT/kVknc44MuNsLuwP/zTTO9b7EhQbK70yHlRkHfHG3fHU4A=
k8s-node03,192.168.1.62 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBM221wY62j/3BRakXcMfnhNZtK68XmM3UpFskgtWT/kVknc44MuNsLuwP/zTTO9b7EhQbK70yHlRkHfHG3fHU4A=
[root@harbor ansible]# ssh k8s-master03 # 嘗試無密碼登錄
Last login: Fri Feb 14 12:44:40 2020 from hub.lixiang.com
[root@k8s-master03 ~]# exit
登出
Connection to k8s-master03 closed.
[root@harbor ~]# ansible k8s_master --list
hosts (3):
k8s-master01
k8s-master02
k8s-master03
可以看到返回都很正常
常用模塊
ping模塊
這個上面已經(jīng)演示過了:
ansible <host-pattern> -m ping
以wang用戶執(zhí)行ping存活檢測
ansible all -m ping -u wang -k
以wang sudo至root執(zhí)行ping檢測
ansible all -m ping -u wang -b -k
以wang sudo至mage用戶執(zhí)行ping存活檢測
ansible all -m ping -u wang -b -k --become-user mage
command模塊 (默認(rèn)模塊)
ansible <host-pattern> [-f forks] [-m module_name] [-a args]
[root@harbor ansible]# ansible lede -m command -a "ip a" # 由于是默認(rèn)模塊,-m 后可不加command
192.168.1.111 | CHANGED | rc=0 >>
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 00:0c:29:c5:d6:44 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.111/24 brd 192.168.1.255 scope global ens33
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fec5:d644/64 scope link
valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link/ether 02:42:a8:f0:9f:f0 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
以wang sudo 至root用戶執(zhí)行l(wèi)s
ansible all -m command -u wang --become-user=root -a 'ls /root' -b -k -K
shell模塊
command模塊無法處理代參數(shù)砂沛、管道或者環(huán)境變量的命令,這個時候就需要shell模塊來執(zhí)行
[root@harbor ansible]# ansible k8s-node03 -a 'echo $hostname'
k8s-node03 | CHANGED | rc=0 >>
$hostname
[root@harbor ansible]# ansible k8s-node03 -m shell -a 'echo $hostname'
k8s-node03 | CHANGED | rc=0 >>
[root@harbor ansible]# ansible k8s-node03 -a 'echo 123456|passwd --stdin test1' # command 模塊實際不會執(zhí)行
k8s-node03 | CHANGED | rc=0 >>
123456|passwd --stdin test1
[root@harbor ansible]# ansible k8s-node03 -m shell -a 'echo 123456|passwd --stdin test1'
k8s-node03 | CHANGED | rc=0 >>
更改用戶 test1 的密碼 。
passwd:所有的身份驗證令牌已經(jīng)成功更新柠衍。
script模塊
在指定機器上執(zhí)行ansible上指定的腳本
[root@harbor ansible]# vim host.sh
[root@harbor ansible]# cat host.sh
#!/bin/bash
hostname
[root@harbor ansible]# chmod +x host.sh
[root@harbor ansible]# ansible k8s-node03 -m script -a ~/ansible/host.sh
k8s-node03 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to k8s-node03 closed.\r\n",
"stderr_lines": [
"Shared connection to k8s-node03 closed."
],
"stdout": "k8s-node03\r\n",
"stdout_lines": [
"k8s-node03"
]
}
copy模塊
[root@harbor ~]# ansible k8s-node03 -m copy -a 'src=/root/111 dest=/root/ backup=yes'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"backup_file": "/root/111.9184.2020-02-21@12:04:56~",
"changed": true,
"checksum": "f0fbe82ee70ca0dc32ea691eb8d9f2dc2be1aa57",
"dest": "/root/111",
"gid": 0,
"group": "root",
"md5sum": "fdd30fbcc1024bebea93f6076076c15a",
"mode": "0644",
"owner": "root",
"size": 7,
"src": "/root/.ansible/tmp/ansible-tmp-1582257895.69-175368708621216/source",
"state": "file",
"uid": 0
}
如果需要修改文件權(quán)限柒傻,或者文件所屬用戶及組,可以參考一下:
[root@harbor ~]# ansible k8s-node03 -m copy -a 'src=/root/111 dest=/root/ backup=yes mode=000 owner=root group=root'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "f0fbe82ee70ca0dc32ea691eb8d9f2dc2be1aa57",
"dest": "/root/111",
"gid": 0,
"group": "root",
"mode": "0000",
"owner": "root",
"path": "/root/111",
"size": 7,
"state": "file",
"uid": 0
}
fetch模塊
使用說明: 注意這個模塊只能操作單個文件
[root@harbor ~]# ansible-doc -s fetch
- name: Fetch files from remote nodes
fetch:
dest: # (required) A directory to save the file into. For example, if the `dest' directory is `/backup' a `src' file named
`/etc/profile' on host `host.example.com', would be saved into
`/backup/host.example.com/etc/profile'. The host name is based on the inventory
name.
fail_on_missing: # When set to `yes', the task will fail if the remote file cannot be read for any reason. Prior to Ansible 2.5,
setting this would only fail if the source file was missing. The default was changed
to `yes' in Ansible 2.5.
flat: # Allows you to override the default behavior of appending hostname/path/to/file to the destination. If `dest' ends
with '/', it will use the basename of the source file, similar to the copy module.
This can be useful if working with a single host, or if retrieving files that are
uniquely named per host. If using multiple hosts with the same filename, the file
will be overwritten for each host.
src: # (required) The file on the remote system to fetch. This `must' be a file, not a directory. Recursive fetching may
be supported in a later release.
validate_checksum: # Verify that the source and destination checksums match after the files are fetched.
示例:
[root@harbor ~]# ansible k8s-node03 -m fetch -a 'src=/var/log/messages dest=~'
k8s-node03 | CHANGED => {
"changed": true,
"checksum": "81c5a7255563bdd09fa4ec570be5d4822850e850",
"dest": "/root/k8s-node03/var/log/messages",
"md5sum": "7e889237d8978b68cfae2dd711b1a80c",
"remote_checksum": "81c5a7255563bdd09fa4ec570be5d4822850e850",
"remote_md5sum": null
}
archive模塊(打包模塊)
ansible-doc -s archive
- name: Creates a compressed archive of one or more files or trees.
action: archive
dest # 目標(biāo)歸檔文件名曼振。除非path指定要壓縮的是單文件几迄,否則需要dest選項
format # 指定壓縮格式,默認(rèn)為gz格式
group # 文件/目錄的所屬組
owner # 文件/目錄的所有者
mode # 設(shè)置文件/目錄的的權(quán)限冰评,支持'0644'或'u+rwx'或'u=rw,g=r,o=r'等格式
path= # 要壓縮的文件映胁,可以是絕對路徑,也可以是glob統(tǒng)配的路徑甲雅,還可以是文件列表
remove # 壓縮后刪除源文件
示例
[root@harbor ~]# ansible k8s-node03 -m archive -a 'path=/root/anaconda-ks.cfg format=tar dest=/mnt/111.tar'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"archived": [
"/root/anaconda-ks.cfg"
],
"arcroot": "/root/",
"changed": true,
"dest": "/mnt/111.tar",
"expanded_exclude_paths": [],
"expanded_paths": [
"/root/anaconda-ks.cfg"
],
"gid": 0,
"group": "root",
"missing": [],
"mode": "0644",
"owner": "root",
"size": 10240,
"state": "file",
"uid": 0
}
file模塊
創(chuàng)建文件夾:
[root@harbor ~]# ansible k8s-node03 -m file -a 'dest=/root/222 state=directory'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/root/222",
"size": 6,
"state": "directory",
"uid": 0
}
創(chuàng)建文件:
[root@harbor ~]# ansible k8s-node03 -m file -a 'dest=/root/333 state=touch'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/root/333",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"size": 0,
"state": "file",
"uid": 0
}
創(chuàng)建軟連接
[root@harbor ~]# ansible k8s-node03 -m file -a 'src=/root/333 dest=/root/333-link state=link'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/root/333-link",
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"size": 9,
"src": "/root/333",
"state": "link",
"uid": 0
}
刪除文件或目錄
[root@harbor ~]# ansible k8s-node03 -m file -a 'dest=/root/333-link state=absent'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/root/333-link",
"state": "absent"
}
設(shè)置文件屬性
[root@harbor ~]# ansible k8s-node03 -m file -a 'path=/root/333 mode=755 owner=test'
cron模塊(定時模塊)
創(chuàng)建(這里建議每次創(chuàng)建都指定好name參數(shù)解孙,否則會存在重復(fù)創(chuàng)建的情況)
[root@harbor ~]# ansible k8s-node03 -m cron -a 'minute=* weekday=1,3,5,6 job="/usr/bin/wall FBI warning" name=warningcron'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"warningcron"
]
}
停用指定定時任務(wù)
[root@harbor ~]# ansible k8s-node03 -m cron -a 'disabled=true job="/usr/bin/wall FBI warning" name=warningcron'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"warningcron"
]
}
啟用指定定時任務(wù)
[root@harbor ~]# ansible k8s-node03 -m cron -a 'disabled=false job="/usr/bin/wall FBI warning" name=warningcron'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"warningcron"
]
}
刪除指定定時任務(wù)
[root@harbor ~]# ansible k8s-node03 -m cron -a 'job="/usr/bin/wall FBI warning" name=warningcron state=absent'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": []
}
yum模塊
安裝
[root@harbor ~]# ansible k8s-node03 -m yum -a 'name=htop,nload state=latest'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"htop",
"nload"
],
"updated": []
},
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.aliyun.com\n * elrepo: mirrors.tuna.tsinghua.edu.cn\n * epel: mirrors.tuna.tsinghua.edu.cn\n * extras: mirrors.aliyun.com\n * updates: mirrors.ustc.edu.cn\nResolving Dependencies\n--> Running transaction check\n---> Package htop.x86_64 0:2.2.0-3.el7 will be installed\n---> Package nload.x86_64 0:0.7.4-4.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n htop x86_64 2.2.0-3.el7 epel 103 k\n nload x86_64 0.7.4-4.el7 epel 70 k\n\nTransaction Summary\n================================================================================\nInstall 2 Packages\n\nTotal download size: 174 k\nInstalled size: 393 k\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal 121 kB/s | 174 kB 00:01 \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : htop-2.2.0-3.el7.x86_64 1/2 \n Installing : nload-0.7.4-4.el7.x86_64 2/2 \n Verifying : nload-0.7.4-4.el7.x86_64 1/2 \n Verifying : htop-2.2.0-3.el7.x86_64 2/2 \n\nInstalled:\n htop.x86_64 0:2.2.0-3.el7 nload.x86_64 0:0.7.4-4.el7 \n\nComplete!\n"
]
}
刪除包:
[root@harbor ~]# ansible k8s-node03 -m yum -a 'name=htop,nload state=absent'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"removed": [
"htop",
"nload"
]
},
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nResolving Dependencies\n--> Running transaction check\n---> Package htop.x86_64 0:2.2.0-3.el7 will be erased\n---> Package nload.x86_64 0:0.7.4-4.el7 will be erased\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nRemoving:\n htop x86_64 2.2.0-3.el7 @epel 218 k\n nload x86_64 0.7.4-4.el7 @epel 176 k\n\nTransaction Summary\n================================================================================\nRemove 2 Packages\n\nInstalled size: 393 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Erasing : htop-2.2.0-3.el7.x86_64 1/2 \n Erasing : nload-0.7.4-4.el7.x86_64 2/2 \n Verifying : nload-0.7.4-4.el7.x86_64 1/2 \n Verifying : htop-2.2.0-3.el7.x86_64 2/2 \n\nRemoved:\n htop.x86_64 0:2.2.0-3.el7 nload.x86_64 0:0.7.4-4.el7 \n\nComplete!\n"
]
}
service模塊
設(shè)置服務(wù)啟動并開機自啟
[root@harbor ~]# ansible k8s-node03 -m service -a 'name=ntpd state=started enabled=true'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"enabled": true,
"name": "ntpd",
"state": "started",
"status": {
"ActiveEnterTimestampMonotonic": "0",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "inactive",
"""
"""
}
}
停止服務(wù)并關(guān)閉開機自啟
[root@harbor ~]# ansible k8s-node03 -m service -a 'name=ntpd state=stopped enabled=false'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"enabled": false,
"name": "ntpd",
"state": "stopped",
"status": {
"ActiveEnterTimestamp": "Sat 2020-02-22 19:05:16 CST",
"ActiveEnterTimestampMonotonic": "11389238933",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "active",
"""
"""
}
}
user 模塊
創(chuàng)建用戶,指定UID抛人,指定home路徑弛姜,指定nologin,指定groups
[root@harbor ~]# ansible k8s-node03 -m user -a 'name=testuser shell=/sbin/nologin system=yes home=/home/nginx groups=root,bin uid=666 comment="account for test"'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"comment": "account for test",
"create_home": true,
"group": 666,
"groups": "root,bin",
"home": "/home/nginx",
"name": "testuser",
"shell": "/sbin/nologin",
"state": "present",
"system": true,
"uid": 666
}
[root@harbor ~]# ansible k8s-node03 -a 'getent passwd testuser' # 查看是否創(chuàng)建成功
k8s-node03 | CHANGED | rc=0 >>
testuser:x:666:666:account for test:/home/nginx:/sbin/nologin
刪除指定用戶
[root@harbor ~]# ansible k8s-node03 -m user -a 'name=testuser state=absent remove=yes'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"force": false,
"name": "testuser",
"remove": true,
"state": "absent",
"stderr": "userdel: testuser mail spool (/var/spool/mail/testuser) not found\n",
"stderr_lines": [
"userdel: testuser mail spool (/var/spool/mail/testuser) not found"
]
}
[root@harbor ~]# ansible k8s-node03 -a 'getent passwd testuser' # 確認(rèn)刪除
k8s-node03 | FAILED | rc=2 >>
non-zero return code
group模塊
創(chuàng)建組
[root@harbor ~]# ansible k8s-node03 -m group -a 'name=testgroup system=yes gid=666'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 666,
"name": "testgroup",
"state": "present",
"system": true
}
[root@harbor ~]# ansible k8s-node03 -a 'getent group testgroup' # 驗證
k8s-node03 | CHANGED | rc=0 >>
testgroup:x:666:
刪除組
[root@harbor ~]# ansible k8s-node03 -m group -a 'name=testgroup state=absent'
k8s-node03 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"name": "testgroup",
"state": "absent"
}
[root@harbor ~]# ansible k8s-node03 -a 'getent group testgroup'
k8s-node03 | FAILED | rc=2 >>
non-zero return code
選擇執(zhí)行對象
sudo執(zhí)行
如果需要遠(yuǎn)程并sudo 至root用戶執(zhí)行相關(guān)命令:
[root@harbor ansible]# ansible lede -m command -a "ls -a /root" -b -K # -b 默認(rèn)參數(shù)是root -K 輸入sudo的密碼
BECOME password:
192.168.1.111 | CHANGED | rc=0 >>
.
..
.bash_history
.bashrc
docker_test
.profile
.ssh
.viminfo
多個組同時執(zhí)行
[root@harbor ansible]# ansible '*master:lede' -m ping # 組與組之間加冒號
同時滿足幾個組的交集執(zhí)行:(a與b的交集)
[root@harbor ansible]# ansible '*master:&lede' -m ping # 組與組之間加:&
滿足a,但不在b組中的主機執(zhí)行:
[root@harbor ansible]# ansible '*master:!lede' -m ping # 需要注意順序妖枚,組與組之間加:廷臼!
[root@harbor ansible]# ansible '*master:!lede' -m ping
k8s-master01 | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: ssh: connect to host k8s-master01 port 22: No route to host",
"unreachable": true
}
k8s-master02 | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: ssh: connect to host k8s-master02 port 22: No route to host",
"unreachable": true
}
k8s-master03 | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: ssh: connect to host k8s-master03 port 22: No route to host",
"unreachable": true
}
[root@harbor ansible]# ansible 'lede:!*master' -m ping
192.168.1.111 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
正則
按host環(huán)境條件執(zhí)行
removes條件滿足則執(zhí)行
[root@harbor ansible]# ansible lede -a 'removes=/etc/fs cat /etc/fstab'
192.168.1.111 | SUCCESS | rc=0 >>
skipped, since /etc/fs does not exist
[root@harbor ansible]# ansible lede -a 'removes=/etc/fstab cat /etc/fstab'
192.168.1.111 | CHANGED | rc=0 >>
UUID=97a2ffb1-7a68-428d-8ef0-7c96b9b6989a / ext4 defaults 0 0
UUID=cc756777-a22d-4dee-afd8-0d2ebb677693 /boot ext4 defaults 0 0
/swap.img none swap sw 0 0
creates條件滿足則不執(zhí)行
[root@harbor ansible]# ansible lede -a 'creates=/home/lixiang/lean-lede ip a'
192.168.1.111 | SUCCESS | rc=0 >>
skipped, since /home/lixiang/lean-lede exists
[root@harbor ansible]# ansible lede -a 'creates=/home/lixiang/lean ip a'
192.168.1.111 | CHANGED | rc=0 >>
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 00:0c:29:c5:d6:44 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.111/24 brd 192.168.1.255 scope global ens33
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fec5:d644/64 scope link
valid_lft forever preferred_lft forever
3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link/ether 02:42:a8:f0:9f:f0 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
[root@harbor ansible]# ansible lede -a 'ls /home/lixiang'
192.168.1.111 | CHANGED | rc=0 >>
lean-lede
wget-log
切換到指定目錄再執(zhí)行
使用chdir參數(shù)指定需要切換的目錄
[root@harbor ansible]# ansible lede -a 'chdir=/home/lixiang ls'
192.168.1.111 | CHANGED | rc=0 >>
lean-lede
wget-log
查看模塊使用文檔
usage: ansible-doc [-h] [--version] [-v] [-M MODULE_PATH]
[--playbook-dir BASEDIR]
[-t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,module,strategy,vars}]
[-j] [-F | -l | -s | --metadata-dump]
[plugin [plugin ...]]
[root@harbor ansible]# ansible-doc command -s # 添加 -s 簡易模式
- name: Execute commands on targets
command:
argv: # Passes the command as a list rather than a string. Use `argv' to avoid quoting values that would otherwise be interpreted incorrectly (for example
"user name"). Only the string or the list form can be provided, not both. One or the other must be provided.
chdir: # Change into this directory before running the command.
cmd: # The command to run.
creates: # A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be run.
free_form: # The command module takes a free form command to run. There is no actual parameter named 'free form'.
removes: # A filename or (since 2.0) glob pattern. If it already exists, this step *will* be run.
stdin: # Set the stdin of the command directly to the specified value.
stdin_add_newline: # If set to `yes', append a newline to stdin data.
strip_empty_ends: # Strip empty lines from the end of stdout/stderr in result.
warn: # Enable or disable task warnings.
交互式工具
[root@harbor ansible]# ansible-console # 多用于調(diào)試playbook
Welcome to the ansible console.
Type help or ? to list commands.
root@all (7)[f:5]$ cd
192.168.1.111 k8s-master01 k8s-master03 k8s-node02 k8s_master lede
all k8s-master02 k8s-node01 k8s-node03 k8s_node ungrouped
root@all (7)[f:5]$ cd k8s-node03
root@k8s-node03 (1)[f:5]$ command hostname
k8s-node03 | CHANGED | rc=0 >>
k8s-node03
root@k8s-node03 (1)[f:5]$ exit
PlayBook
基礎(chǔ)寫法
[root@harbor ansible]# vim playbook.yml
- hosts: k8s-node03
remote_user: root
tasks:
- name: hello
command: hostname
執(zhí)行playbook
[root@harbor ansible]# ansible-playbook playbook.yml
PLAY [k8s-node03] *********************************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************
ok: [k8s-node03]
TASK [hello] **************************************************************************************************************************************
changed: [k8s-node03]
PLAY RECAP ****************************************************************************************************************************************
k8s-node03 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
playbook加密和解密
[root@harbor ansible]# ansible-vault encrypt playbook.yml # 加密
New Vault password:
Confirm New Vault password:
Encryption successful
[root@harbor ansible]# cat playbook.yml
$ANSIBLE_VAULT;1.1;AES256
38666630626439353938656236623532346466373735313261623261356334373661373538393234
6330613030373664373635643031396432373532353831330a626430396533646237656134383435
65636532393130636164353362356337633761643037633135346564373836643439636230306533
3437616661613831610a356631363064373130626239393133323062396566393962666639663962
61313665643064333466333961386330306335336465623035376433323435383336373064323635
64366634653538623861336662613962306164666163656636623462373539613436303830333839
37633965613638393133663165313930663830336531376162393031313864333036386638303130
36343534366537303264356534343466656365363732383630306131663963333432643230626337
3233
[root@harbor ansible]# ansible-playbook playbook.yml
ERROR! Attempting to decrypt but no vault secrets found
[root@harbor ansible]# ansible-playbook playbook.yml --ask-vault-pass
Vault password:
PLAY [k8s-node03] *********************************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************
ok: [k8s-node03]
TASK [hello] **************************************************************************************************************************************
changed: [k8s-node03]
PLAY RECAP ****************************************************************************************************************************************
k8s-node03 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[root@harbor ansible]# ansible-vault view playbook.yml # 通過view命令查看加密的內(nèi)容
Vault password:
- hosts: k8s-node03
remote_user: root
tasks:
- name: hello
command: hostname
[root@harbor ansible]# ansible-vault edit playbook.yml # 可以通過輸入密碼對playbook內(nèi)容進行編輯
Vault password:
[root@harbor ansible]# cat playbook.yml
$ANSIBLE_VAULT;1.1;AES256
62366634303831363762303137626134353532326437336466373833376161396561316364333234
3265623562336365316333346337636164616462336432310a386235383130633132623538343562
38363339373566356165623638633239383334616131336164386539383135373539363439303036
3966393064366663620a363037393666303235376339653661636433653430326532613131346164
31656137353434313237633930336331643566383534633830363766366333636338316363316438
30353364323263646533666136373236396665623139646163356564396237656164353834653134
65633066356363326661616131663164343933323934656335636462636662346261663737343663
64366230356131353936383432363238346537343935633630393965613461326161363637643039
3766
[root@harbor ansible]# ansible-vault decrypt playbook.yml # 解密
Vault password:
Decryption successful
[root@harbor ansible]# cat playbook.yml
- hosts: k8s-node03
remote_user: root
tasks:
- name: hello
command: hostname
YAML語言寫法
List
List: 列表,其所有元素均使用"-" 打頭
示例:
# A list of tasty fruits
- Apple
- Orange
- Strawberry
- Mango
Dictionary
Dictionary: 字典,通常由多個key與value構(gòu)成
示例
# An employee record
name: Example Developer
job: Developer
skill: Elite
也可以將key:value放置于{}中進行表示, 用","分隔多個key:value
示例
# An employee record
{name: Example Developer, job: Developer, skill: Elite}
YAML陷阱
YAML語法要求如果值以{{ foo }}開頭的話我們需要將整行用雙引號包起來.這是為了確認(rèn)你不是想聲明一個YAML字典.該知識點在 YAML 語法 頁面有所講述.
這樣是不行的:
- hosts: app_servers
vars:
app_path: {{ base_path }}/22
你應(yīng)該這么做:
- hosts: app_servers
vars:
app_path: "{{ base_path }}/22"
一些樣例
[root@harbor ansible]# cat test.yml
---
- hosts: k8s-node03
remote_user: root
tasks:
- name: test createfile
file: name=/root/newfile state=touch
- name: test connection
ping:
- name: test createuser
user: name=test1 shell=/sbin/nologin system=yes home=/home/test1 groups=root,bin uid=666 comment="account for test"
- name: install yum htop
yum: name=htop,nload
- name: test copyfile
copy: src=/root/111 dest=/root
模擬測試(dry run)
使用-C參數(shù)進行dry run
[root@harbor ansible]# ansible-playbook test.yml -C
PLAY [k8s-node03] *********************************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************
ok: [k8s-node03]
TASK [test createfile] ****************************************************************************************************************************
ok: [k8s-node03]
TASK [test connection] ****************************************************************************************************************************
ok: [k8s-node03]
TASK [test createuser] ****************************************************************************************************************************
changed: [k8s-node03]
TASK [install yum htop] ***************************************************************************************************************************
changed: [k8s-node03]
TASK [test copyfile] ******************************************************************************************************************************
changed: [k8s-node03]
PLAY RECAP ****************************************************************************************************************************************
k8s-node03 : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
模擬測試通過后就實際運行一下
[root@harbor ansible]# ansible-playbook test.yml
PLAY [k8s-node03] *********************************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************
ok: [k8s-node03]
TASK [test createfile] ****************************************************************************************************************************
changed: [k8s-node03]
TASK [test connection] ****************************************************************************************************************************
ok: [k8s-node03]
TASK [test createuser] ****************************************************************************************************************************
changed: [k8s-node03]
TASK [install yum htop] ***************************************************************************************************************************
changed: [k8s-node03]
TASK [test copyfile] ******************************************************************************************************************************
changed: [k8s-node03]
PLAY RECAP ****************************************************************************************************************************************
k8s-node03 : ok=6 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
檢測是否執(zhí)行成功
[root@k8s-node03 ~]# ls
111 111.9184.2020-02-21@12:04:56~ 333 anaconda-ks.cfg kubernetes.conf newfile
[root@k8s-node03 ~]# getent passwd test1
test1:x:666:666:account for test:/home/test1:/sbin/nologin
[root@k8s-node03 ~]# htop --version
htop 2.2.0 - (C) 2004-2019 Hisham Muhammad
Released under the GNU GPL.
執(zhí)行腳本時忽略錯誤的方法
1.如果命令或腳本的退出碼不為0荠商,可以使用如下方案替代
tasks:
- name: run this command and ignore the result
shell: /usr/bin/somecommand || bin/true
2.或者使用ignore_errors來忽略錯誤信息:
tasks:
- name: run this command and ignore the result
shell: /usr/bin/somecommand
ignore_errors: True
查看待執(zhí)行的主機列表
添加--list-hosts參數(shù)
[root@harbor ansible]# ansible-playbook test.yml --list-hosts
playbook: test.yml
play #1 (k8s-node03): k8s-node03 TAGS: []
pattern: [u'k8s-node03']
hosts (1):
k8s-node03
查看playbook的任務(wù)列表
[root@harbor ansible]# ansible-playbook test.yml --list-tasks
playbook: test.yml
play #1 (k8s-node03): k8s-node03 TAGS: []
tasks:
test createfile TAGS: []
test connection TAGS: []
test createuser TAGS: []
install yum htop TAGS: []
test copyfile TAGS: []
針對特定主機執(zhí)行
執(zhí)行時添加--limit參數(shù)
[root@harbor ansible]# ansible-playbook test.yml --limit k8s-node03
Handlers: 在發(fā)生改變時執(zhí)行的操作
由于module 具有”冪等”性,所以當(dāng)遠(yuǎn)端系統(tǒng)被人改動時,可以重放 playbooks 達(dá)到恢復(fù)的目的. playbooks 本身可以識別這種改動,并且有一個基本的 event system(事件系統(tǒng)),可以響應(yīng)這種改動.
(當(dāng)發(fā)生改動時)’notify’ actions 會在 playbook 的每一個 task 結(jié)束時被觸發(fā),而且即使有多個不同的 task 通知改動的發(fā)生, ‘notify’ actions 只會被觸發(fā)一次.
舉例來說,比如多個 resources 指出因為一個配置文件被改動,所以 apache 需要重新啟動,但是重新啟動的操作只會被執(zhí)行一次.
這里有一個例子,當(dāng)一個文件的內(nèi)容被改動時,重啟兩個 services:
- name: template configuration file
template: src=template.j2 dest=/etc/foo.conf
notify:
- restart memcached
- restart apache
‘notify’ 下列出的即是 handlers.
Handlers 也是一些 task 的列表,通過名字來引用,它們和一般的 task 并沒有什么區(qū)別.Handlers 是由通知者進行 notify, 如果沒有被 notify,handlers 不會執(zhí)行.不管有多少個通知者進行了 notify,等到 play 中的所有 task 執(zhí)行完成之后,handlers 也只會被執(zhí)行一次.
這里是一個 handlers 的示例:
handlers:
- name: restart memcached
service: name=memcached state=restarted
- name: restart apache
service: name=apache state=restarted
Handlers 最佳的應(yīng)用場景是用來重啟服務(wù),或者觸發(fā)系統(tǒng)重啟操作.除此以外很少用到了.
tags
可以在創(chuàng)建task的時候為其指定標(biāo)簽寂恬,以方便在執(zhí)行playbook的時候選擇指定標(biāo)簽的任務(wù)去執(zhí)行
執(zhí)行方法:ansible-playbook -t yourtags1,yourtags2 yourplaybook.yml
[root@harbor ansible]# vim playbook.yml
[root@harbor ansible]# cat playbook.yml
- hosts: k8s-node03
remote_user: root
tasks:
- name: stop ntpd
service: name=ntpd state=stopped
tags: stop_ntpd
- name: restart ntpd
service: name=ntpd state=restarted
tags: restart_ntpd
[root@harbor ansible]# ansible-playbook --list-tags playbook.yml # 查看標(biāo)簽
playbook: playbook.yml
play #1 (k8s-node03): k8s-node03 TAGS: []
TASK TAGS: [restart_ntpd, stop_ntpd]
[root@harbor ansible]# ansible-playbook -t stop_ntpd playbook.yml # 這里我們只執(zhí)行停止任務(wù)的標(biāo)簽
PLAY [k8s-node03] *********************************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************
ok: [k8s-node03]
TASK [stop ntpd] **********************************************************************************************************************************
changed: [k8s-node03]
PLAY RECAP ****************************************************************************************************************************************
k8s-node03 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[root@harbor ansible]# ansible k8s-node03 -a 'systemctl status ntpd'
k8s-node03 | FAILED | rc=3 >>
● ntpd.service - Network Time Service
Loaded: loaded (/usr/lib/systemd/system/ntpd.service; enabled; vendor preset: disabled)
Active: inactive (dead) since Tue 2020-02-25 10:16:20 CST; 57s ago
Process: 998 ExecStart=/usr/sbin/ntpd -u ntp:ntp $OPTIONS (code=exited, status=0/SUCCESS)
Main PID: 1014 (code=exited, status=0/SUCCESS)
Feb 25 10:11:34 k8s-node03 ntpd[1014]: Listen and drop on 1 v6wildcard :: UDP 123
Feb 25 10:11:34 k8s-node03 ntpd[1014]: Listen normally on 2 lo 127.0.0.1 UDP 123
Feb 25 10:11:34 k8s-node03 ntpd[1014]: Listening on routing socket on fd #19 for interface updates
Feb 25 10:11:34 k8s-node03 ntpd[1014]: 0.0.0.0 c016 06 restart
Feb 25 10:11:34 k8s-node03 ntpd[1014]: 0.0.0.0 c012 02 freq_set kernel 6.765 PPM
Feb 25 10:11:37 k8s-node03 ntpd[1014]: Listen normally on 3 ens33 192.168.1.62 UDP 123
Feb 25 10:11:37 k8s-node03 ntpd[1014]: Listen normally on 4 docker0 172.17.0.1 UDP 123
Feb 25 10:11:37 k8s-node03 ntpd[1014]: new interface(s) found: waking up resolver
Feb 25 10:16:20 k8s-node03 systemd[1]: Stopping Network Time Service... # 只執(zhí)行了停止任務(wù)
Feb 25 10:16:20 k8s-node03 systemd[1]: Stopped Network Time Service.non-zero return code
Playbook使用變量
變量名:僅能由字母、數(shù)字和下劃線組成结啼,且只能以字母開頭
變量來源:
? ansible setup facts 遠(yuǎn)程主機的所有變量都可以直接調(diào)用
查看變量
[root@harbor ~]# ansible k8s-node03 -m setup -a 'filter=ansible_hostname' # 這里的過濾條件支持通配符
k8s-node03 | SUCCESS => {
"ansible_facts": {
"ansible_hostname": "k8s-node03",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
由于支持通配符掠剑,也可以寫成
[root@harbor ~]# ansible k8s-node03 -m setup -a 'filter=*hostname*'
k8s-node03 | SUCCESS => {
"ansible_facts": {
"ansible_hostname": "k8s-node03",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
變量的優(yōu)先級:
ansible-playbook -e "key=value"
Playbook 文件里面定義的變量
hosts文件里面定義的單個主機變量
hosts文件里面定義的group變量
調(diào)用系統(tǒng)默認(rèn)變量
[root@harbor ~]# ansible k8s-node03 -m setup -a 'filter=ansible_ens33' # 先查詢要獲取的變量
k8s-node03 | SUCCESS => {
"ansible_facts": {
"ansible_ens33": {
"active": true,
"device": "ens33",
"features": {
"busy_poll": "off [fixed]",
"fcoe_mtu": "off [fixed]",
"generic_receive_offload": "on",
"generic_segmentation_offload": "on",
"highdma": "off [fixed]",
"l2_fwd_offload": "off [fixed]",
"large_receive_offload": "off [fixed]",
"loopback": "off [fixed]",
"netns_local": "off [fixed]",
"ntuple_filters": "off [fixed]",
"receive_hashing": "off [fixed]",
"rx_all": "off",
"rx_checksumming": "off",
"rx_fcs": "off",
"rx_vlan_filter": "on [fixed]",
"rx_vlan_offload": "on",
"rx_vlan_stag_filter": "off [fixed]",
"rx_vlan_stag_hw_parse": "off [fixed]",
"scatter_gather": "on",
"tcp_segmentation_offload": "on",
"tx_checksum_fcoe_crc": "off [fixed]",
"tx_checksum_ip_generic": "on",
"tx_checksum_ipv4": "off [fixed]",
"tx_checksum_ipv6": "off [fixed]",
"tx_checksum_sctp": "off [fixed]",
"tx_checksumming": "on",
"tx_fcoe_segmentation": "off [fixed]",
"tx_gre_segmentation": "off [fixed]",
"tx_gso_robust": "off [fixed]",
"tx_ipip_segmentation": "off [fixed]",
"tx_lockless": "off [fixed]",
"tx_nocache_copy": "off",
"tx_scatter_gather": "on",
"tx_scatter_gather_fraglist": "off [fixed]",
"tx_sit_segmentation": "off [fixed]",
"tx_tcp6_segmentation": "off [fixed]",
"tx_tcp_ecn_segmentation": "off [fixed]",
"tx_tcp_segmentation": "on",
"tx_udp_tnl_segmentation": "off [fixed]",
"tx_vlan_offload": "on [fixed]",
"tx_vlan_stag_hw_insert": "off [fixed]",
"udp_fragmentation_offload": "off [fixed]",
"vlan_challenged": "off [fixed]"
},
"hw_timestamp_filters": [],
"ipv4": {
"address": "192.168.1.62",
"broadcast": "192.168.1.255",
"netmask": "255.255.255.0",
"network": "192.168.1.0"
},
"macaddress": "00:0c:29:73:7f:5c",
"module": "e1000",
"mtu": 1500,
"pciid": "0000:02:01.0",
"promisc": false,
"speed": 1000,
"timestamping": [
"tx_software",
"rx_software",
"software"
],
"type": "ether"
},
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
[root@harbor ansible]# vim playbook2.yml
[root@harbor ansible]# cat playbook2.yml
- hosts: k8s-node03
remote_user: root
tasks:
- name: get ip
shell: echo {{ ansible_ens33.ipv4.address }} > /root/321 # 使用變量
[root@harbor ansible]# ansible-playbook playbook2.yml
PLAY [k8s-node03] *********************************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************
ok: [k8s-node03]
TASK [get ip] *************************************************************************************************************************************
changed: [k8s-node03]
PLAY RECAP ****************************************************************************************************************************************
k8s-node03 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[root@harbor ansible]# ansible k8s-node03 -a 'cat /root/321'
k8s-node03 | CHANGED | rc=0 >>
192.168.1.62
示例里面playbook里的變量可以有兩種寫法,效果都是一樣的:
shell: echo {{ ansible_ens33.ipv4.address }} > /root/321
shell: echo {{ ansible_ens33["ipv4"]["address"] }} > /root/321
在hosts中定義變量
hosts文件路徑默認(rèn)為/etc/ansible/hosts
普通變量:
在主機組中主機單獨定義郊愧,優(yōu)先級高于公共變量
[root@harbor ansible]# vim /etc/ansible/hosts # 對指定對象添加變量
[k8s_node]
k8s-node[01:03] package=ntpd
編寫playbook并執(zhí)行
[root@harbor ansible]# vim playbook3.yml
[root@harbor ansible]# cat playbook3.yml
- hosts: k8s-node03
remote_user: root
tasks:
- name: stop service
service: name={{ package }} status=stopped
[root@harbor ansible]# ansible-playbook playbook3.yml
PLAY [k8s-node03] *********************************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************
ok: [k8s-node03]
TASK [stop service] *******************************************************************************************************************************
changed: [k8s-node03]
PLAY RECAP ****************************************************************************************************************************************
k8s-node03 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
公共(組)變量:
針對主機組中所有主機定義統(tǒng)一變量
[root@harbor ansible]# vim /etc/ansible/hosts # 對指定組添加變量
[k8s_node]
k8s-node[01:03]
[k8s_node:vars] # 添加[group:vars]來配置組變量
package=ntpd
執(zhí)行
[root@harbor ansible]# vim playbook3.yml
[root@harbor ansible]# cat playbook3.yml
- hosts: k8s-node03
remote_user: root
tasks:
- name: stop service
service: name={{ package }} state=stopped
[root@harbor ansible]# ansible-playbook playbook3.yml
PLAY [k8s-node03] *********************************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************
ok: [k8s-node03]
TASK [stop service] *******************************************************************************************************************************
changed: [k8s-node03]
PLAY RECAP ****************************************************************************************************************************************
k8s-node03 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
通過命令行指定變量朴译,優(yōu)先級最高
Ansible-playbook -e varname=value
- hosts: k8s-node03
remote_user: root
tasks:
- name: stop ntpd
service: name={{package}} state=stopped
- name: start ntpd
service: name={{package}} state=started
執(zhí)行:
[root@harbor ansible]# ansible-playbook -e 'package=ntpd' playbook.yml
PLAY [k8s-node03] *********************************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************
ok: [k8s-node03]
TASK [stop ntpd] **********************************************************************************************************************************
changed: [k8s-node03]
TASK [start ntpd] *********************************************************************************************************************************
changed: [k8s-node03]
PLAY RECAP ****************************************************************************************************************************************
k8s-node03 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[root@harbor ansible]# ansible k8s-node03 -a 'systemctl status ntpd'
k8s-node03 | CHANGED | rc=0 >>
● ntpd.service - Network Time Service
Loaded: loaded (/usr/lib/systemd/system/ntpd.service; enabled; vendor preset: disabled)
Active: active (running) since Tue 2020-02-25 11:04:30 CST; 7s ago
Process: 68118 ExecStart=/usr/sbin/ntpd -u ntp:ntp $OPTIONS (code=exited, status=0/SUCCESS)
Main PID: 68120 (ntpd)
Tasks: 1
Memory: 580.0K
CGroup: /system.slice/ntpd.service
└─68120 /usr/sbin/ntpd -u ntp:ntp -g
Feb 25 11:04:30 k8s-node03 ntpd[68120]: 0.0.0.0 c01d 0d kern kernel time sync enabled
Feb 25 11:04:30 k8s-node03 ntpd[68120]: ntp_io: estimated max descriptors: 1024, initial socket boundary: 16
Feb 25 11:04:30 k8s-node03 ntpd[68120]: Listen and drop on 0 v4wildcard 0.0.0.0 UDP 123
Feb 25 11:04:30 k8s-node03 ntpd[68120]: Listen and drop on 1 v6wildcard :: UDP 123
Feb 25 11:04:30 k8s-node03 ntpd[68120]: Listen normally on 2 lo 127.0.0.1 UDP 123
Feb 25 11:04:30 k8s-node03 ntpd[68120]: Listen normally on 3 ens33 192.168.1.62 UDP 123
Feb 25 11:04:30 k8s-node03 ntpd[68120]: Listen normally on 4 docker0 172.17.0.1 UDP 123
Feb 25 11:04:30 k8s-node03 ntpd[68120]: Listening on routing socket on fd #21 for interface updates
Feb 25 11:04:30 k8s-node03 ntpd[68120]: 0.0.0.0 c016 06 restart
Feb 25 11:04:30 k8s-node03 ntpd[68120]: 0.0.0.0 c012 02 freq_set kernel 6.765 PPM
如果有多個變量:
ansible-playbook -e 'key1=value1 key2=value2' yourplaybook.yml
在playbook中定義
- hosts: k8s-node03
remote_user: root
vars:
- package: ntpd
tasks:
- name: stop ntpd
service: name={{package}} state=stopped
- name: start ntpd
service: name={{package}} state=started
執(zhí)行:
[root@harbor ansible]# ansible-playbook playbook.yml
PLAY [k8s-node03] *********************************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************
ok: [k8s-node03]
TASK [stop ntpd] **********************************************************************************************************************************
changed: [k8s-node03]
TASK [start ntpd] *********************************************************************************************************************************
changed: [k8s-node03]
PLAY RECAP ****************************************************************************************************************************************
k8s-node03 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
自動寫/etc/hosts:
需要先在/etc/ansible/hosts中定義對應(yīng)的hostname變量
[fastdfs]
192.168.1.31 hostname=tracker_group1
192.168.1.32 hostname=tracker_group2
192.168.1.33 hostname=storage_group1_1
192.168.1.34 hostname=storage_group1_2
192.168.1.35 hostname=storage_group2_1
192.168.1.36 hostname=storage_group2_2
- name: mod hosts
tags:
- test1
lineinfile:
dest: /etc/hosts
regexp: '.*{{ item }}$'
line: "{{item}} {{ hostvars[item].hostname }}"
state: present
when: hostvars[item].hostname is defined
with_items: "{{ groups.fastdfs }}"
YAML文件定義變量
區(qū)別于playbook中定義,我們可以將變量全部放到一個yml文件里來調(diào)用
[root@harbor ansible]# vim /etc/ansible/vars.yml
[root@harbor ansible]# cat /etc/ansible/vars.yml
package: ntpd
[root@harbor ansible]# vim playbook3.yml
[root@harbor ansible]# cat playbook3.yml
- hosts: k8s-node03
remote_user: root
vars_files: # 指定變量文件的路徑
- /etc/ansible/vars.yml
tasks:
- name: stop service
service: name={{ package }} state=stopped
執(zhí)行
[root@harbor ansible]# ansible-playbook playbook3.yml
PLAY [k8s-node03] *********************************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************
ok: [k8s-node03]
TASK [stop service] *******************************************************************************************************************************
changed: [k8s-node03]
PLAY RECAP ****************************************************************************************************************************************
k8s-node03 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
在role中定義
Template模板
文本文件属铁,嵌套有腳本(使用模板變成語言編寫)
jinja2語言眠寿,使用字面量,有下面形式:
? 字符串:使用單引號或雙引號
? 數(shù)字:整數(shù)焦蘑,浮點數(shù)
? 列表:[item1, item2, ...]
? 元祖:(item1, item2, ...)
? 字典:{key1:vlaue1, key2:value2, ...}
? 布爾型:true/false
算術(shù)運算:+, -, *, /, //, %, **
比較操作:==, !=, >, >=, <, <=
邏輯運算:and, or, not
流表達(dá)式:For If When
基礎(chǔ)寫法
修改文件nginx.com.j2下面的行
worker_processes {{ ansible_processor_vcpus }};
創(chuàng)建playbook文件:
cat temnginx2.yml
---
- hosts: websrvs
remote_usr: root
tasks:
- name: template config to remote hosts
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
ansible-playbook temnginx2.yml
when 判斷
條件測試:如果需要根據(jù)變量盯拱、facts或此前任務(wù)的執(zhí)行結(jié)果來作為某task執(zhí)行與否的前提時要用到條件測試,通過when語句實現(xiàn)例嘱,在task中使用狡逢,jinja2的語法格式
when語句:
在task后添加when子句即可使用條件測試;when語句支持jinja2表達(dá)式語法
示例:
tasks:
- name: "shutdown RedHat flavored systems"
command: /sbin/shutdown -h now
when: ansible_os_family == "RedHat"
Playbook常用模塊使用
更換centos7系統(tǒng)源為阿里源
這個劇本執(zhí)行前需要準(zhǔn)備兩個repo文件
- name: change repo
template: src=CentOS-Base.repo dest=/etc/yum.repos.d/CentOS-Base.repo
- name: install epel release
yum:
name: epel-release
- name: change repo
template: src=epel-7.repo dest=/etc/yum.repos.d/epel-7.repo
notify:
- make cache
handlers:
- name: make cache
shell:
cmd: yum clean all && yum makecache
文件1:CentOS-Base.repo:
# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client. You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#
[base]
name=CentOS-$releasever - Base - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/os/$basearch/
http://mirrors.aliyuncs.com/centos/$releasever/os/$basearch/
http://mirrors.cloud.aliyuncs.com/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
#released updates
[updates]
name=CentOS-$releasever - Updates - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/updates/$basearch/
http://mirrors.aliyuncs.com/centos/$releasever/updates/$basearch/
http://mirrors.cloud.aliyuncs.com/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/extras/$basearch/
http://mirrors.aliyuncs.com/centos/$releasever/extras/$basearch/
http://mirrors.cloud.aliyuncs.com/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/centosplus/$basearch/
http://mirrors.aliyuncs.com/centos/$releasever/centosplus/$basearch/
http://mirrors.cloud.aliyuncs.com/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
#contrib - packages by Centos Users
[contrib]
name=CentOS-$releasever - Contrib - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/contrib/$basearch/
http://mirrors.aliyuncs.com/centos/$releasever/contrib/$basearch/
http://mirrors.cloud.aliyuncs.com/centos/$releasever/contrib/$basearch/
gpgcheck=1
enabled=0
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
文件2:epel-7.repo
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=http://mirrors.aliyun.com/epel/7/$basearch
failovermethod=priority
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
[epel-debuginfo]
name=Extra Packages for Enterprise Linux 7 - $basearch - Debug
baseurl=http://mirrors.aliyun.com/epel/7/$basearch/debug
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=0
[epel-source]
name=Extra Packages for Enterprise Linux 7 - $basearch - Source
baseurl=http://mirrors.aliyun.com/epel/7/SRPMS
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=0
Yum安裝常用軟件(yum)
- name: install necessary tools
tags:
- yum
yum:
name: unzip,conntrack,ntpdate,ntp,ipvsadm,ipset,jq,iptables,curl,sysstat,libseccomp,wget,vim,net-tools,git,nfs-utils,rpcbind,iptables-services,nload,htop,telnet,nmap,openssl
需要編譯包的時候:
- name: install necessary tools
tags:
- yum
yum:
name: make,cmake,gcc,gcc-c++
更改時區(qū)(timezone)
- name: Set timezone to Asia/Shanghai
timezone:
name: Asia/Shanghai
設(shè)置主機名(hostname)
需要在hosts文件里指定相應(yīng)的hostname參數(shù)
- name: set hostname
hostname:
name: "{{ hostname }}"
ansible的host文件指定參數(shù)示例:
[rocketmq]
192.168.1.81 hostname=rocketmq01
192.168.1.82 hostname=rocketmq02
192.168.1.83 hostname=rocketmq03
192.168.1.84 hostname=rocketmq04
主機組互相添加host信息(lineinfile)
同上一條,需要在ansible的host文件內(nèi)指定hostname參數(shù)
- name: mod hosts
lineinfile:
dest: /etc/hosts
regexp: '.*{{ item }}$'
line: "{{item}} {{ hostvars[item].hostname }}"
state: present
when: hostvars[item].hostname is defined
with_items: "{{ groups.rocketmq }}" # 注意修改組名
注意最后一行的變量里面需要修改為主機組名,在此時示例中組名為rocketmq
ansible的host文件指定參數(shù)示例:
[rocketmq]
192.168.1.81 hostname=rocketmq01
192.168.1.82 hostname=rocketmq02
192.168.1.83 hostname=rocketmq03
192.168.1.84 hostname=rocketmq04
獲取本機ip變量
實際使用的時候需要測試一下是否正常獲取
mysqlip: "{{ansible_default_ipv4.address}}"
service相關(guān)操作(service)
指定相關(guān)進程的狀態(tài),以及是否開機自動啟動
state可以指定的狀態(tài)有reloaded, restarted, started, stopped
- name: Disable unnecessary services
service:
name: "{{ item }}"
state: stopped
enabled: false
with_items:
- firewalld
- postfix
關(guān)閉SELinux(selinux)
- name: Disable SELinux tempoary
selinux:
state: disabled
關(guān)閉swap
- name: disable swap
lineinfile:
path: /etc/fstab
regexp: swap
state: absent
設(shè)置limits(lineinfile)
- name: setting
lineinfile:
path: /etc/security/limits.conf
line: "{{ item }}"
with_items:
- '* soft nofile 65535'
- '* hard nofile 65535'
- '* soft nproc 65535'
- '* hard nproc 65535'
notify:
- ulimit
handlers:
- name: ulimit
shell: ulimit -n
啟用iptables并清理策略(service)
- name: set iptables
service:
name: iptables
state: started
enabled: true
notify:
- clean iptables
handlers:
- name: clean iptables
shell:
cmd: iptables -F && service iptables save
ntp設(shè)置
需要指定一個ntp server變量,準(zhǔn)備一個ntp.conf的template
- hosts: k8s
vars:
ntp_server: 192.168.1.1
gather_facts: yes
tasks:
- name: set ntp
tags:
- ntp
template: src=ntp.conf dest=/etc/ntp.conf
- name: sync time
tags:
- ntp
shell: ntpdate {{ ntp_server }} && hwclock -w
- name: start ntp
tags:
- ntp
service:
name: ntpd
state: restarted
enabled: true
ntp.conf
server {{ ntp_server }}
#在配置中增加以下配置:
#允許上層時間服務(wù)器主動修改本機時間
restrict {{ ntp_server }} nomodify notrap noquery
#外部時間服務(wù)器不可用時拼卵,以本地時間作為時間服務(wù)
server 127.0.0.1
fudge 127.0.0.1 stratum 10
創(chuàng)建group,user(group)(user)
- name: create mysql group
group:
name: mysql
state: present
- name: create mysql user
user:
name: mysql
group: mysql
shell: /sbin/nologin
home: /home/mysql
state: present
創(chuàng)建文件夾(file)
Owner,group不寫默認(rèn)root
recurse:true允許遞歸創(chuàng)建
- name: Create data directory
file:
path: "{{ item }}"
state: directory
owner: mysql
group: mysql
recurse: true
with_items:
- "{{data}}"
- "{{data}}/logs"
- "{{data}}/tmp"
- "{{data}}/undolog"
- /usr/local/mysql
拷貝文件(copy)
remote_src為yes的時候src和dest都在遠(yuǎn)程主機上
backup參數(shù)表示如果源文件存在將會備份源文件,可選參數(shù)
- name: Copy the files
copy:
src: /etc/my.cnf
dest: /etc/my.cnf.bak
remote_src: yes
backup: yes
ignore_errors: yes
解壓包(unarchive)
src這里沒有特殊參數(shù)指定,會從ansible端的相關(guān)目錄拉取壓縮包
dest表示需要解壓的目標(biāo)目錄
creates參數(shù)表示如果文件夾存在就不會重復(fù)進行解壓操作
- name: unarchive packages
tags:
- unzip
unarchive:
src: "{{ item.name }}"
dest: /usr/local
creates: /usr/local/{{ item.unarchived_name }}
with_items:
- { name: 'fastdfs.V6.06.tar.gz', unarchived_name: 'fastdfs-6.06' }
- { name: 'libfastcommon.V1.0.43.tar.gz', unarchived_name: 'libfastcommon-1.0.43' }
- { name: 'nginx-1.16.1.tar.gz', unarchived_name: 'nginx-1.16.1' }
- { name: 'fastdfs-nginx-module.tar.gz', unarchived_name: 'fastdfs-nginx-module' }
- { name: 'ngx_cache_purge-2.3.tar.gz', unarchived_name: 'ngx_cache_purge-2.3' }
執(zhí)行shell命令(shell)
chdir: 表示切換到指定目錄下再執(zhí)行相應(yīng)命令
cmd:命令主體
creates: 如果文件或文件夾存在,則不執(zhí)行該命令
- name: make libfastcommon
tags:
- make
shell:
chdir: /usr/local/{{ libfastcommon }} # 這個變量于演示無關(guān)
cmd: ./make.sh && ./make.sh install
creates: /usr/lib64/libfastcommon.so
做軟鏈(file)
src: 源文件
dest: 軟鏈地址
- name: ln
tags:
- ln
file:
src: "{{ item.src }}"
dest: "{{ item.dest }}"
state: link
with_items:
- { src: '/usr/lib64/libfastcommon.so', dest: '/usr/local/lib/libfastcommon.so' }
- { src: '/usr/lib64/libfastcommon.so', dest: '/usr/lib/libfastcommon.so' }
- { src: '/usr/lib64/libfdfsclient.so', dest: '/usr/local/lib/libfdfsclient.so' }
套用模板(template)
src: 模板文件,需要自己準(zhǔn)備,同時模板內(nèi)的變量需要自己定義好
dest:目標(biāo)路徑
notify,handlers:可選項,有時候需要在修改完配置文件后重啟相關(guān)服務(wù)
- name: config tracker
tags:
- install
template:
src: fdfs/tracker.conf.j2
dest: /etc/fdfs/tracker.conf
notify:
- restart tracker
handlers:
- name: restart tracker
shell: /etc/init.d/fdfs_trackerd restart
another example
- hosts: mongo_config_servers
gather_facts: yes
vars:
- based_dir: "/mongodb/sharded_cluster"
tasks:
- name: create config file for config_server and shard_server
tags:
- key
template: src=mongod.conf.normal.j2 dest=/etc/mongod_{{ item.server_port }}.conf
with_items:
- { server_port: '20000', server_name: 'configs', cluster_role: 'configsvr' }
- { server_port: '20001', server_name: 'shard1', cluster_role: 'shardsvr' }
- { server_port: '20002', server_name: 'shard2', cluster_role: 'shardsvr' }
- { server_port: '20003', server_name: 'shard3', cluster_role: 'shardsvr' }
角色條件判斷(when)
when:
當(dāng)待執(zhí)行主機滿足某個條件時才執(zhí)行某些操作
- name: set master
tags:
- master
template:
src: master.sh
dest: /tmp/master.sh
mode: u+x
notify: apply master
when: role == "master"
- name: set slave
tags:
- slave
template:
src: slave.sh
dest: /tmp/slave.sh
mode: u+x
notify: apply slave
when: role == "slave"
這里貼上ansible的hosts文件:
[mysql]
192.168.0.71 hostname=master01 serverid=13306 role=master
192.168.0.72 hostname=slave01 serverid=23306 role=slave
192.168.0.73 hostname=slave02 serverid=33306 role=slave
在指定文件中加入一段文本(blockinfile)
create:如果沒有就創(chuàng)建
- name: create mongodb repo file
tags:
- test1
blockinfile:
path: /etc/yum.repos.d/mongodb-org-4.2.repo
create: True
block: |
[mongodb-org-4.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc
修改文本(lineinfile)
示例中前兩個是正則匹配替換,第三個表示確保文件中存在這一行
- name: set ntp restrict
tags:
- ntp
lineinfile:
dest: /etc/ntp.conf
regexp: '^restrict 192\.[0-9]{1,3}\.255\.1'
line: restrict 192.168.1.1
notify:
- restart ntpd
- name: set ntp server
tags:
- ntp
lineinfile:
dest: /etc/ntp.conf
regexp: '^server 192\.[0-9]{1,3}\.255\.1 iburst minpoll 3 maxpoll 4 prefer'
line: 'server 192.168.1.1 iburst minpoll 3 maxpoll 4 prefer'
notify:
- restart ntpd
- name: disable auto update for mongodb
lineinfile:
path: /etc/yum.conf
line: 'exclude=mongodb-org,mongodb-org-server,mongodb-org-shell,mongodb-org-mongos,mongodb-org-tools'
another example:
- name: mod service
tags:
- test6
lineinfile:
path: /usr/lib/systemd/system/mongod_{{ server_port }}.service
regexp: '^ExecStart=/usr/bin/m'
line: 'ExecStart=/usr/bin/mongos $OPTIONS'
with_items:
- { server_port: '27017' }
替換文本(replace)
- name: change log dir
tags:
- log
replace:
path: "{{ item }}"
regexp: '\${user.home}' # 這里$需要打轉(zhuǎn)義符
replace: '/data/rocketmq'
with_items:
- /usr/local/rocketmq/conf/logback_broker.xml
- /usr/local/rocketmq/conf/logback_namesrv.xml
- /usr/local/rocketmq/conf/logback_tools.xml
- /usr/local/rocketmq/conf/plain_acl.yml
- /usr/local/rocketmq/conf/tools.yml
重啟(reboot)
- name: Reboot all nodes make sure all changes effected
reboot:
reboot_timeout: 3600