Ansible Environment Setup

前言

安裝完Ansible後還要進行基礎的設定之後才能使用

Basic Configuration

SSH key preparation

基本上雖然可以用--ask-pass指令輸入密碼來操作,但是實際上還是有ssh key比較簡單,詳細的部份就放在SSH Commands | Kiwi's Wiki

/etc/ansible/ansible.cfg

在範例中可以用

1
ansible-config init --disable-all > /etc/ansible/ansible.cfg

來建立一個預設全部都關掉的cfg檔,又或是直接手動建立如下

1
2
3
4
5
#/etc/ansible/ansible.cfg
[defaults] # 定義整個section是defualt
inventory=/etc/ansible/hosts # 定義inventory是要讀哪個檔,預設就是/etc/ansible/hosts
private_key_file=/location/private.key # 定義預設連線時要用哪個ssh private key(若不打算用Key pair不用設定)
remote_user=USER_on_server # 定義預設連線的USER,因為一般的Linux/FreeBSD Server都不喜歡用root直接連進去,所以會用其他使用者

基本上可以在hosts裡面針對不同的host(或是host group)進行設定,所以不一定需要在ansible.cfg內去設定remote_user或是private_key_file, 但是需要設定inventory位置

hosts

參考資料

Ansible official document - How to build Inventory

基本語法

1
2
3
4
5
6
7
8
[tag1]
server1.example.com
[tag2]
server2.example.com
[tag3]
server[a:z].example.com
[tag4]
192.168.0.101

上述的意思為有四個tag,一個是tag1有一台server1, tag2有一台server2,tag3servera.example.com,serverb.example.com...serverz.example.com等26台server.tag4是ip表示的server

群組 :children

1
2
3
4
5
6
7
8
9
10
11
12
[group1:children]
tag1
tag2

[tag1]
server1.example.com
[tag2]
server2.example.com
[tag3]
server[a:z].example.com
[tag4]
192.168.0.101

有一個群組裡面包括了tag1&tag2,這個指令可以群組裡面包含群組弄成很多層

變數 :vars

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[group1:children]
tag1
tag2

[tag1]
server1.example.com ansible_user=myuser
[tag2]
server2.example.com
[tag3]
server[a:z].example.com
[tag4]
192.168.0.101

[tag3:vars]
ansible_passwd=mypassword

這裡設定了單項變數ansible_user=myuserserver1以及整體變數ansible_passwd=mypasswordtag3所有的機器上

參考範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 設定localhost給在Localhost上使用的,主要是ansible-pull這種需要設定本機才需要

# 需要先弄個[]定義個名字
[Desktop]
# 這裡不用ip而是用localhost來定義
localhost
# 定義[Desktop]的相關變數
[Desktop:vars]
# 有些python3的位置不是預設的(例如Manjaro)所以手動指定
ansible_python_interpreter=/usr/bin/python3
# 指定localhost的連線方式不使用ssh而是local
ansible_connection=local

# 這是用一個大集合包括小集合的概念
[Oracle_Cloud:children]
Oracle_Private
Oracle_Friend

# 定義其中一個
[Oracle_Private]
# 可以是以下這種格式
# 別名 ansible_ssh_host=XXX.XXX.XXX.XXX or my.server.domain
oci1 ansible_ssh_host=xxx.xxx.xxx.xxx
oci2 ansible_ssh_host=xxx.xxx.xxx.xxx
oci3 ansible_ssh_host=xxx.xxx.xxx.xxx

[Oracle_Friend]
oci4 ansible_ssh_host=xxx.xxx.xxx.xxx
oci5 ansible_ssh_host=xxx.xxx.xxx.xxx


[Oracle_Cloud:vars]
# 可以個別指定python
ansible_python_interpreter=/usr/bin/python3
# 可以指定這個群組的連線account是誰
ansible_ssh_user=UserNameYouUsing
# 如前面說的可以指定對應的Private key
ansible_ssh_private_key_file=/where/you/.ssh/the.key

基本上hosts或該說inventory設定對於ansible來說是非常重要的定義,因為這個檔案基本上定義了你所有需要被納管的remote node資訊所以不要沒事把連同這個檔案在內的ansible設定放在public accessable repo內