Ansible教程

慕容峻才發表於2018-11-06

安裝方式

原始碼包安裝

安裝git

yum - y install git

下載原始碼包並安裝

git clone git://github.com/ansible/ansible.git --recursive
cd ./ansible
source ./hacking/env-setup

安裝pip

easy_install pip

安裝python模組

pip install paramiko PyYAML Jinja2 httplib2

複製配置檔案

cd /root/ansible/examples
cp -rf playbooks/ scripts/ /etc/ansible/

yum方式安裝

匯入阿里雲epel yum源

wget http://mirrors.aliyun.com/repo/epel-6.repo

安裝repo

yum install ansible

客戶端配置

windwos客戶端

安裝pywinrm

pip install http://github.com/diyan/pywinrm/archive/master.zip#egg=pywinrm

安裝kerberos用來連線域賬戶

apt-get install libkrb5-dev
Apt-get install python-dev
 libexpat1-dev libpython-dev libpython2.7-dev python2.7-dev

pip install kerberos

新增hosts檔案

[win]
192.168.1.40

建立inventory環境變數檔案

mkdir /etc/ansible/group_vars
touch win.yml
ansible_ssh_user: administrator
ansible_ssh_pass: 1a!
ansible_ssh_port: 5986
ansible_connection: winrm

複製指令碼ConfigureRemotingForAnsible.ps1在windows客戶端執行啟動windows系統winrm服務,並設定服務為自動啟動

net start winrm

安裝winrm模組依賴的兩個模組

wget https://pypi.python.org/packages/source/i/isodate/isodate-0.5.4.tar.gz
wget https://pypi.python.org/packages/source/x/xmltodict/xmltodict-0.10.1.tar.gz

解壓後用python setpu.py install執行安裝測試

ansible win -m win_ping -vvvv

windows模組

win_feature : 安裝和解除安裝功能
win_get_url : 從給定的 url 下載檔案
win_group : 新增和刪除本地組
win_msi : 安裝和解除安裝 MSI 檔案
win_ping : windows 版本的 ping 模組
win_service : 管理 windows 服務
win_stat : 返回關於 windows 檔案的資訊
win_user : 管理本地賬號

案例

建立使用者acai,密碼1a@

ansible win -m win_user -a "name=acai password=1a@"

Linux客戶端

ansible管理linux伺服器可以使用兩種方式:使用ssh雙機互信和通過在配置檔案中指定密碼

使用ssh互信的方式管理主機

ssh-keygen
scp id_rsa.pub root@client:/root/.ssh/authorized_keys

使用變數的方式管理主機

mkdir /etc/ansible/group_vars
vi test
ansible_ssh_user:root
ansible_ssh_pass:123456
ansible_ssh_port:22

新增host

[linux]
192.168.1.1

測試

ansible linux -m ping -vvvv

linux模組

file模組

引數

group:定義檔案/目錄屬組
owner:定義檔案目錄屬主
mode:定義檔案目錄的許可權
path:定義檔案目錄的路徑
recurse:遞迴設定檔案的屬性,只對目錄有效
state:定義檔案狀態(state狀態有三個選項directory:如果目錄不存在則建立、touch:如果檔案不存在則建立、absent:刪除檔案或目錄)

案例

檢視遠端主機的檔案許可權
ansible test -m command -a `ls -al /root/aaa`
192.168.1.16 | success | rc=0 >>
-rw-r--r--. 1 root root 86 Mar  9 19:03 /root/aaa
#將檔案許可權修改為777
ansible test -m file -a `dest=/root/aaa mode=777`

copy模組

引數

src:原始檔
dest:目標路徑
backup:覆蓋前是否備份原檔案
owner:設定檔案目錄的屬主
group:設定檔案目錄的屬組
mode:設定檔案目錄的許可權

案例

複製/root/aaa檔案到主機/root目錄下 
ansible test  -m -a  copy `src=/root/aaa dest=/root/`
檢視複製檔案
ansible test -m command -a `ls /root/`

cron模組

引數

backup:對遠端主機上原任務計劃內容修改之前備份
day:日
hour:小時
minute:分鐘
month:月
weekday:周
job:要執行的檔案,依賴於state=present
name:該任務的描述
special_time:指定什麼時候執行(引數:reboot、yearly、annually、monthly、weekly、daily、hourly)
sate:確認該任務計劃是建立還是刪除
user:以哪個使用者的身份執行

案例

建立一個計劃任務
 ansible test -m cron -a `name="cron_test" minute=*/3 hour=* day=* month=* weekday=* job="/usr/sbin/ntpdate cn.ntp.org.cn"`
檢視建立的任務計劃
ansible test -m command -a `crontab -l`
192.168.1.16 | success | rc=0 >>
#Ansible: cron_test
*/3 * * * * /usr/sbin/ntpdate cn.ntp.org.cn

group模組

引數

home:指定家目錄,需要createhome為yes
groups:使用者組
uid:使用者uid
password:使用者密碼
name:使用者名稱
createhome:是否建立家目錄
system:是否建立為系統使用者
remove:sate=absent時,刪除家目錄
state:建立或者刪除
shell:指定使用者shell環境

案例

建立一個gid為2016,group名字為acai的組
ansible test -m group -a `gid=2016 name=acai`
user模組

建立使用者test_user,並加入acai組
ansible test -m user -a `name=test_user groups=acai state=present`
刪除建立的使用者
ansible test -m user -a `name=test_user state=absent remove=yes`

template模組

template使用了Jinjia2格式作為檔案模版,進行文件內變數的替換的模組。它的每次使用都會被ansible標記為”changed”狀態。
使用template模組後,ansible會在當前role路徑下templates目錄中檔案copy到相應目錄,若該檔案存在替換變數時,ansible會根據配置替換該變數。

template引數

引數 可選項 備註
backup yes/no
src 檔案源地址
dest 檔案目的地址
mode 設定遠端節點上的template檔案許可權。類似Linux中chmod的用法
owner 設定遠端節點上的template檔案所屬使用者
group 設定遠端節點上的的template檔案的所屬使用者組

案例:

在templates目錄下建立chrony.conf.j2檔案並替換以下變數
allow {{ cluster_network }}
{{ cluster_network }} 代表是由ansible引入的一個變數,該變數可在group_vars目錄下檔案中呼叫,eg:

cat group_vars/all 
---
#k8s cluster api network
#eg: cluster_network : 192.168.1.0/24
cluster_network : 192.168.1.0/24

當ansible執行該任務後,被copy的配置檔案會被替換為cluster_network變數的值。

yum模組

引數

enablerepo:啟動某個源
name:要操作軟體包的名字,也可以傳遞一個url和本地路徑
state:定義軟體包的狀態(present:安裝、absent:刪除、latest:安裝最新的)

案例

安裝httpd服務
ansible test -m yum -a `state=present name=httpd`

service模組

引數

enabled:是否開機啟動 yes|no
name:服務名稱
runlevel:執行級別
sleep:如果執行了restarted,在stop和start之間沉睡幾秒
state:對服務執行啟動,停止,重啟,重新載入等

案例

啟動httpd服務,並設定開機自動啟動
ansible test -m service -a `name=httpd state=started enabled=yes`

script模組

ansible test -m script -a `/root/aaa.sh`

ping模組:(測試主機網路)

ansible test -m ping 

command模組

引數

creates:一個檔名,當該檔案存在則命令不執行
free_form:要執行的Linux指令
chdir:在執行指令之前,先切換到該指定的目錄
removes:一個檔名,如果檔案不存在,則該選項不執行
ansible test -m command -a `hostname`

raw模組

ansible test -m raw -a `cat /root/aaa`

get_url模組

案例

下載檔案到本地/tmp
ansible test -m get_url -a `url=http://mirrors.aliyun.com/centos/timestamp.txt dest=/tmp`

setup模組

收集系統所有資訊
ansible test -m setup
收集系統所有資訊,以主機名為檔名分別儲存
ansible test -m setup --tree /tmp/host
收集系統網路卡資訊
ansible test -m setup -a `filter=ansible_eth[0-2]` --tree host
收集系統記憶體資訊
ansible test -m setup -a `filter=ansible_*_mb`

lineinfile模組

該模組用於從一個檔案中搜尋一行,確保該行存在或刪除該行。lineinfile模組主要用於改變一個檔案的一行。如果想要改變檔案中相似的多行,可以使用replace模組。如果想要插入/更新/刪除一個行塊,可以使用blockinfile模組。
引數

backup    用於建立一個包含時間戳資訊的備份檔案。以便在錯誤的修改了檔案的時候,能夠找回原始的檔案。
create    與state=present一起使用。如果指定了這個引數,當要修改的檔案不存在的時候,會建立它。否則會報錯。
dest    要修改的檔案
insertbefore    當regexp不匹配檔案中的任何行的時候,會將line引數所指定的行,插入到insertbefore所指定的正規表示式匹配的行中的最後一行的前面,當insertbefore所指定的正規表示式不匹配任何行時,會插入到檔案的末尾
insertafter    與insertbefore類似,不同的是,insertbefore會將新行插入到其所指定的正規表示式匹配的行中的最後一行的前面,而insertafter是插入到後面。
line    要插入或者替換的行。如果設定了backrefs引數,那麼line中可以包含 位置分組 或 命名分組,lineinfile模組會使用regexp捕獲的分組填充它們。
mode    用來指定檔案的許可權,比如mode=0644 或 mode=`a+x`
owner 和 group    用來指定檔案的屬主 和 屬組。(可能需要使用-b提權)
regexp    用於搜尋檔案中的每一行的正規表示式。對於state=present,這個正規表示式所匹配的行中的最後一行會被替換;對於state=present,會刪除所有匹配的行。
state    用於設定 新增或替換一行,還是刪除行

案例

1.刪除passwd檔案開頭為root的行
ansible test -m lineinfile -a "dest=/root/passwd state=absent regexp=`^root`"
2.修改selinux配置檔案SELINUX=disabled
ansible test -m lineinfile -a "dest=/etc/selinux/config regexp=`^SELINUX=.*` line=`SELINUX=disabled` state=present"
3.新增hosts解析
ansible test -m lineinfile -a "dest=/etc/hosts line=172.16.1.10	test" state=present

systemd模組

systemd模組就是使用systemctl來管理centos7系統服務
模組引數

引數名稱 可選值 備註
name yes/no 服務名稱
enabled yes/no 是否設定開機啟動
state started、stopped、restarted、reload 對服務執行的動作

docker_container模組

引數

引數 可選項 描述
command 容器啟動時執行的命令可以是字串,也可以是列表
hostname 容器hostname
image 容器映象
name 容器名稱
env 容器環境變數
network_mode bridge、host、none 容器的網路模式
pull 下載映象到本地
read_only 掛載容器根檔案系統為只讀
restart 重啟容器
restart_policy no、on-failure、always、unless-stopped 重啟容器策略
state absent、present、stopped、started 容器執行狀態
volume_driver volume driver
volumes 容器共享宿主機的目錄,例如:volumes: /opt:container:/opt

建立容器

- name: start docker registry
  docker_container:
    name: registry
    image: registry:2
    ports: 
      - 4000:5000
      - 80:80
    state: started
    restart_policy: always
    volumes: 
      - /opt/t2cp:/var/lib/registry
      - /etc/test:/etc/test

重啟容器

- name: restart docker registry
  docker_container:
    name: registry
    image: registry:2
    state: started
    restart: yes
    ports: 4000:5000

Playbooks

playbooks定義

Playboos:簡單說就是定義一個配置檔案,檔案中寫入你需要安裝的服務,配置檔案,變數等資訊。可以安裝事先定義好的機制完成一個任務

yml指令碼語法

a、用“---”開始
b、在冒號之後,必須存在一個空格
c、name和service必須對齊
d、hosts和tasks必須對齊
e、在書寫key和value的時候,不能存在空格

playbooks組成部分

target section:定義要執行playbook的遠端主機組
variable section:定義playbook執行時需要的變數
task section:定義要在遠端主機上執行任務列表
handler section:定義task執行完成以後需要呼叫的任務
target section引數
hosts:遠端主機組
user:執行該任務的使用者
sudo:設定為yes的時候,執行任務的時候使用root許可權
sudo_user:如果設定為tshare365,執行的時候會使用tshare365使用者許可權
connection:通過什麼方式連線到遠端主機,預設ssh
gather_facks:是否啟用在遠端主機執行setup模組,預設會執行。可用同setup模組獲取遠端主機的資訊,在定義變數的時候使用。
variadble section引數
vars:定義格式 變數名:變數值
vars_files:指定變數檔案
vars_prompt:使用者互動模式自定義變數
setup:模組取遠端主機的值
task section引數
name:輸出到螢幕的資訊
action:定義執行的動作呼叫ansible的模組
copy:複製本地檔案到遠端主機
template:複製本地檔案到遠端主機也可以在本地檔案中呼叫變數
service:定義服務的狀態

案例

#playbooks中定義變數
---
 - hosts: web
   vars: 
 http_port: 80


#ping主機hadoop
---
- hosts: hadoop
  tasks: 
  - name: ping host
ping: 

例項:判斷nginx服務是否正常執行

---
- hosts: hadoop
  tasks: 
  - name: 
service: name=httpd state=running

例項:判斷selinux的狀態

---
- hosts: hadoop
  tasks: 
  - name: 
command: /sbin/setenforce 0

ansible-playbook 條件判斷

  1. when條件判斷:只條滿足when的條件時才執行對應的tasks
---
- hosts: master
  tasks:
  - name: test host IP address
    debug: `msg="{{ ansible_default_ipv4.address }}"`
    when: ansible_default_ipv4.address == "192.168.1.11"
程式碼介紹:
當滿足條件ansible_default_ipv4.address == "192.168.1.11"時,觸發task

案例: 判斷chrony配置檔案是否存在,如果存在則跳過;如果不存在則複製配置檔案

- name: chrony check is exits
  stat: path=/etc/chrony.conf.bak
  register: chrony_conf_status
  #先用register獲取chrony.conf.bak檔案的狀態
- name: backup chrony conf
  copy: src=/etc/chrony.conf dest=/etc/chrony.conf.bak
  when: chrony_conf_status.stat.exists == False
  #判斷配置檔案是否存在如果存在則不執行該task
  1. changed_when:先執行task,並對task返回的值進行判斷,當滿足changed_when指定的條件時說明是執行成功的
---
- hosts: master
  tasks:
  - name: check hostname
    shell: "hostname"
    changed_when: ansible_hostname == "master01"

ansible-playbook 迴圈控制

with_items標準迴圈

用於迴圈多個重複任務

---
- hosts: master
  tasks:
  - name: create {{ item }} file
    shell: "touch /tmp/{{ item }}"
    with_items:
      - aaa
      - bbb
      - ccc
程式碼解釋:
通過with_items變數中的值在shell命令中遍歷迴圈

ansible-playbook role

Roles 可以降低 Playbooks 的複雜性,更可以增加 Playbooks 的可用性。

role的目錄結構
├── defaults
│   └── main.yml
├── files
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── README.md
├── tasks
│   └── main.yml
├── templates
├── tests
│   ├── inventory
│   └── test.yml
└── vars
    └── main.yml
使用role

建立一個role

ansible-galaxy init base
備註:
ansible-galaxy 是管理 Roles 的指令

建立一個部署高可用k8s專案

基礎配置

建立專案目錄

mkdir ansible_k8s

建立專案目錄

├── deploy.yml
├── group_vars
│   └── all
├── inventory
│   └── hosts
├── roles
│  
└── scripts

編寫hosts

cat inventory/hosts 
[master]
master0[1:2]

[node]
node11[1:2]

[master:vars]
ansible_ssh_user=root
ansible_ssh_pass=123

建立一個base role

ansible-galaxy init base

編寫deploy.yml

 cat deploy.yml 
---

- hosts: master
  roles:
  - base

在base role裡編寫一個測試節點網路連通性的task

 cat roles/base/tasks/main.yml 
---
- name: ping test network
  ping:

規劃role

服務 所在節點
haproxy master
keepalived master
etcd master
flannel master、node
kube-api、kube-scheduler、kube-controller-manager master
kube-proxy、kubelet node

k8s服務介紹

etc 一個高可用K/V鍵值對儲存和服務發現系統
flannel 實現誇主機的容器網路通訊
kube-api 提供k8s叢集API
kube-controller-manager 管理叢集服務
kube-scheduler 排程容器,分配到node節點
kubelet 在node節點根據配置檔案中定義好的引數啟動容器
kube-proxy 提供網路代理服務

根據規劃建立role

.
├── base
│   ├── defaults
│   │   └── main.yml
│   ├── files
│   ├── handlers
│   │   └── main.yml
│   ├── meta
│   │   └── main.yml
│   ├── README.md
│   ├── tasks
│   │   └── main.yml
│   ├── templates
│   ├── tests
│   │   ├── inventory
│   │   └── test.yml
│   └── vars
│       └── main.yml
├── etcd
│   ├── defaults
│   │   └── main.yml
│   ├── files
│   ├── handlers
│   │   └── main.yml
│   ├── meta
│   │   └── main.yml
│   ├── README.md
│   ├── tasks
│   │   └── main.yml
│   ├── templates
│   ├── tests
│   │   ├── inventory
│   │   └── test.yml
│   └── vars
│       └── main.yml
├── flannel
│   ├── defaults
│   │   └── main.yml
│   ├── files
│   ├── handlers
│   │   └── main.yml
│   ├── meta
│   │   └── main.yml
│   ├── README.md
│   ├── tasks
│   │   └── main.yml
│   ├── templates
│   ├── tests
│   │   ├── inventory
│   │   └── test.yml
│   └── vars
│       └── main.yml
├── haproxy
│   ├── defaults
│   │   └── main.yml
│   ├── files
│   ├── handlers
│   │   └── main.yml
│   ├── meta
│   │   └── main.yml
│   ├── README.md
│   ├── tasks
│   │   └── main.yml
│   ├── templates
│   ├── tests
│   │   ├── inventory
│   │   └── test.yml
│   └── vars
│       └── main.yml
├── keepalived
│   ├── defaults
│   │   └── main.yml
│   ├── files
│   ├── handlers
│   │   └── main.yml
│   ├── meta
│   │   └── main.yml
│   ├── README.md
│   ├── tasks
│   │   └── main.yml
│   ├── templates
│   ├── tests
│   │   ├── inventory
│   │   └── test.yml
│   └── vars
│       └── main.yml
├── kube-api
│   ├── defaults
│   │   └── main.yml
│   ├── files
│   ├── handlers
│   │   └── main.yml
│   ├── meta
│   │   └── main.yml
│   ├── README.md
│   ├── tasks
│   │   └── main.yml
│   ├── templates
│   ├── tests
│   │   ├── inventory
│   │   └── test.yml
│   └── vars
│       └── main.yml
├── kube-controller-manager
│   ├── defaults
│   │   └── main.yml
│   ├── files
│   ├── handlers
│   │   └── main.yml
│   ├── meta
│   │   └── main.yml
│   ├── README.md
│   ├── tasks
│   │   └── main.yml
│   ├── templates
│   ├── tests
│   │   ├── inventory
│   │   └── test.yml
│   └── vars
│       └── main.yml
├── kubelet
│   ├── defaults
│   │   └── main.yml
│   ├── files
│   ├── handlers
│   │   └── main.yml
│   ├── meta
│   │   └── main.yml
│   ├── README.md
│   ├── tasks
│   │   └── main.yml
│   ├── templates
│   ├── tests
│   │   ├── inventory
│   │   └── test.yml
│   └── vars
│       └── main.yml
├── kube-proxy
│   ├── defaults
│   │   └── main.yml
│   ├── files
│   ├── handlers
│   │   └── main.yml
│   ├── meta
│   │   └── main.yml
│   ├── README.md
│   ├── tasks
│   │   └── main.yml
│   ├── templates
│   ├── tests
│   │   ├── inventory
│   │   └── test.yml
│   └── vars
│       └── main.yml
└── kube-scheduler
    ├── defaults
    │   └── main.yml
    ├── files
    ├── handlers
    │   └── main.yml
    ├── meta
    │   └── main.yml
    ├── README.md
    ├── tasks
    │   └── main.yml
    ├── templates
    ├── tests
    │   ├── inventory
    │   └── test.yml
    └── vars
        └── main.yml

編寫基礎配置task

cat roles/base/tasks/main.yml 
---
- name: ping test network
  ping:

- name: copy hosts configure files to nodes
  copy: src=/etc/hosts dest=/etc/hosts mode=600

- name: setings selinux disabled
  shell: "sed -i `7s/enforcing/disabled/g` /etc/selinux/config"

- name: backup repos
  file: path=/etc/yum.repos.d state=directory

- name: download yum repo file
  get_url: url=http://mirrors.aliyun.com/repo/{{ item }} dest=/etc/yum.repos.d
  register: repos
  with_items:
    - Centos-7.repo
    - epel-7.repo

- name: settings yum repo
  shell: "sed -i `/aliyuncs/d` /etc/yum.repos.d/{{ item }}"
  with_items:
    - Centos-7.repo
    - epel-7.repo

- name: yum clean all
  shell: yum clean all

- name: yum makecache
  shell: yum makecache

master節點安裝軟體包

---
- name: master node install packages
  yum: name={{ item }} state=latest
  with_items:
    - etcd
    - kubernetes-master 
    - ntp
    - flannel

node節點安裝軟體包


相關文章