ANSIBLE自動化工具

ANSIBLE自動化工具

ansible相關文件html

rpm包安裝:EPEL源
配置文件
    /etc/ansible/hosts          #管理主機的清單
    /etc/ansible/roles/         #存放角色的目錄
    /etc/ansible/ansible.cfg    #主配置文件,配置ansible工做特性,通常默認就好
程序
    /usr/bin/ansible            #主程序,臨時命令執行工具
    /usr/bin/ansible-doc        #查看配置文檔,模塊功能查看工具
    /usr/bin/ansible-galaxy     #下載/上傳優秀代碼或Roles模塊的官網平臺
    /usr/bin/ansible-playbook   #定製自動化任務,編排劇本工具/usr/bin/ansible-pull 遠程執行命令的工具
    /usr/bin/ansible-vault      #文件加密工具
    /usr/bin/ansible-console    #基於Console界面與用戶交互的執行工具

ansible命令:mysql

ansible-doc:顯示模塊幫助
    ansible-doc [options][module]
    -a      顯示全部模塊的文檔
    -l      列出可用模塊
    -s      顯示指定模塊的playbook片斷
例:    ansible-doc ping   
        ansible-doc -l
        ansible-doc -s ping
ansible
    --version       #顯示版本
    -m module       #指定模塊,默認command
    -v              #顯示詳細過程 -vv -vvv
    --list          #顯示主機列表,
    -C              #檢查,並不執行
    all             #表示全部清單列表的主機 ansible all -m ping
    *               #通配符 ansible "*" -m ping      ansible 192.168.2.* -m ping
    :               #邏輯或 ansible "web1:web2" --list
    :&              #邏輯與 ansible "web1:&web2" -m ping
    :!   用單引號    #邏輯非 ansible 'web1:&web2' --list

https://galaxy.ansible.com
ansible-galaxy list                         #列出全部已安裝的galaxy
ansible-galaxy install geerlingguy.redis    #下載安裝galaxy
ansible-galaxy remove geerlingguy.redis     #刪除galaxy
ansible-pull                                #推送至遠程,提高效率
ansible-playbook

ansible-vaultlinux

功能:管理加密解密yml文件
ansible-vault [create|decrypt|edit|encrypt|rekey|view]
ansible-vault encrypt hello.yml             #加密
ansible-vault decrypt hello.yml             #解密
ansible-vault view hello.yml                #查看
ansible-vault edit hello.yml                #編輯加密文件
ansible-vault rekey hello.yml               #修改口令
ansible-vault create new.yml                #建立新文件

ansible經常使用模塊 nginx

command:在遠程主機執行簡單命令(默認是command,能夠不用m選項)web

[root@localhost ~]# ansible web1 -a 'cat /etc/issue'
[root@localhost ~]# ansible web1 -a 'ls -l /etc/selinux'

shell:調用bash執行復雜命令(萬能模塊)redis

[root@localhost ~]# ansible web1 -m shell -a 'sed -i "s/SELINUX=enforcing/SELINUX=disabled/"  /etc/selinux/config
[root@localhost ~]# ansible web1 -a 'echo $HOSTNAME'
[root@localhost ~]# ansible web1 -m shell -a 'tar -Jcvf /root/boot.tar.xz /boot/'

script:在遠程主機上運行ansible服務器上的腳本sql

[root@localhost ~]# ansible web1 -m script -a '/data/hello.sh'

copy:從主控端複製文件到遠程主機shell

[root@localhost ~]# ansible-doc -s copy
[root@localhost ~]# ansible web1 -m copy -a ' src=/etc/selinux/config dest=/etc/selinux/config.bak mode=600 owner=huahua group=bin'
[root@localhost ~]# ansible web1 -m copy -a ' src=/etc/selinux/config dest=/etc/selinux/ backup=yes'          #默認覆蓋,加入backup=yes備份。
[root@localhost ~]# ansible web1 -m copy -a 'content="111\n222\n333" dest=/tmp/text.txt'                      #content指定內容,直接生成目標文件。
[root@localhost ~]# ansible web1 -m copy -a 'content="[base]\nname=base\nbaseurl=file:///mnt/cdrom\ngpgcheck=0" dest=/etc/yum.repos.d/base.repo'                                                                               #批量建立yum源

fetch:從遠程主機提取文件至主控端,copy相反,目錄的話須要tar打包編程

[root@localhost ~]# ansible-doc -s fetch
[root@localhost ~]# ansible web1 -m fetch -a 'src=/etc/yum.repos.d/base.repo dest=/tmp/'            #將遠程base.repo文件抓取放到本機tmp目錄下

file:設置文件屬性vim

[root@localhost ~]# ansible-doc -s file
[root@localhost ~]# ansible web1 -m file -a 'path=/tmp/yum.log owner=huahua mode=000'
[root@localhost ~]# ansible web1 -m file -a 'src=/tmp/yum.log name=/tmp/yum.log.link state=link'        #建立軟鏈接
[root@localhost ~]# ansible web1 -m file -a 'src=/tmp/yum.log name=/tmp/yum.log.hard state=hard'        #建立硬連接
[root@localhost ~]# ansible web1 -m file -a 'path=/tmp/dir1 state=directory'                            #建立文件夾
[root@localhost ~]# ansible web1 -m file -a 'path=/tmp/f1.log state=touch'                              #建立空文件
[root@localhost ~]# ansible web1 -m file -a 'path=/tmp/f1.log state=absent'                             #刪除文件(目錄)
[root@localhost ~]# ansible web1 -m shell -a 'rm -rf /tmp/*'

hostname:管理主機名

[root@localhost ~]# ansible-doc -s hostname
[root@localhost ~]# ansible 192.168.2.20 -m hostname -a 'name=centos7.6'                                #更改主機名

cron:計劃任務

[root@localhost ~]# ansible-doc -s cron
[root@localhost ~]# ansible web2 -m cron -a 'name=synctime minute=*/5 job="/usr/sbin/ntpdate 192.168.2.10 &> /dev/null"'
[root@localhost ~]# ansible web2 -a 'crontab -l'

yum:管理包

[root@localhost ~]# ansible-doc -s yum
[root@localhost ~]# ansible web1 -m yum -a 'name=httpd state=present'
[root@localhost ~]# ansible web1 -m yum -a 'name=httpd state=absent'

service:管理服務

[root@localhost ~]# ansible-doc -s service
[root@localhost ~]# ansible web1 -m service -a 'name=named state=started enabled=true'
[root@localhost ~]# ansible web1 -m service -a 'name=named state=stopped'

user:管理用戶

[root@localhost ~]# ansible-doc -s user
[root@localhost ~]# ansible web1 -a 'getent passwd'
[root@localhost ~]# ansible web1 -m user -a 'name=mysql system=yes shell=/sbin/nologin'
[root@localhost ~]# ansible web1 -m user -a 'name=mysql state=absent'
[root@localhost ~]# ansible web1 -m user -a 'name=mysql state=absent remove=yes'

YAML語言

一、第一行寫「---」       最後一行「...」     (建議不要省略)
二、第二行建議寫明功能用#註釋
三、縮進必須是統一的,不能空格和tab混用
四、縮進的級別也必須是一致的,一樣的縮進表明一樣的級別,程序判斷配置的級別是經過縮進結合換行來實現的
五、YAML文件內容是區分大小寫的,k/v的值均大小寫敏感
六、一個完整的代碼塊功能須要最少元素需包括name和task
七、一個name只能包括一個task
八、YAML文件擴展名一般爲yml和yaml

List:列表,全部元素均使用「-」打頭

Dictionary:字典,由多個key和value組成
            ksy:value

playbook的核心元素:

hosts:playbook配置文件做用的主機
tasks:任務列表
variables:變量
templates:包含模板語法的文本文件
handlers:由特定條件觸發的任務
roles:用於層次性、結構化地組織playbook。roles可以根據層次結構自動裝載變量文件、tasks以及handlers

運行playbook的方式:

ansible-playbook <filename.yml> ... [options]
常見選項
--check -C          #只檢測可能會發生的改變,但不真正執行操做
--list-hosts        #列出運行任務的主機
--list-tags         #列出tag
--list-tasks        #列出task
--limit             #主機列表 只針對主機列表中的主機執行
-v -vv -vvv         #顯示過程

[root@localhost ansible]# vim http.yml
---
#install httpd
- hosts: web1
  remote_user: root

  tasks:
    - name: install package
      yum: name=httpd
    - name: cofig file
      copy: src=/tmp/httpd.conf dest=/etc/httpd/conf/ backup=yes
    - name: service
      service: name=httpd state=started enabled=yes
[root@localhost ansible]# ansible-playbook -C http.yml
[root@localhost ansible]# ansible-playbook http.yml

觸發handlers (handlers由notify觸發)

---
#install httpd
- hosts: web1
  remote_user: root

  tasks:
    - name: install package
      yum: name=httpd
    - name: cofig file
      copy: src=/tmp/httpd.conf dest=/etc/httpd/conf/ backup=yes
      notify: restart service
    - name: service
      service: name=httpd state=started enabled=yes

  handlers:
    - name: restart service
      service: name=httpd state=restarted
[root@localhost ansible]# ansible-playbook http.yml

tags標籤(根據tags來實現部分功能)

---
#install httpd
- hosts: web1
  remote_user: root

  tasks:
    - name: install package
      yum: name=httpd
    - name: cofig file
      copy: src=/tmp/httpd.conf dest=/etc/httpd/conf/ backup=yes
      notify: restart service
      tags: config
    - name: service
      service: name=httpd state=started enabled=yes
      tags: service

  handlers:
    - name: restart service
      service: name=httpd state=restarted
[root@localhost ansible]# ansible-playbook -t config http.yml
[root@localhost ansible]# ansible-playbook -t config,service http.yml       #選擇多個標籤

ansible初步準備

[root@localhost ~]# yum -y install ansible
[root@localhost ~]# vim /etc/ansible/hosts      #加入清單列表
[web1]
192.168.2.20
192.168.2.30

[web2]
192.168.2.30
192.168.2.40

[root@localhost ~]# vim /etc/ansible/ansible.cfg 
log_path = /var/log/ansible.log             #開啓日誌
module_name = shell                         #修改默認模塊
host_key_checking = False                   #取消對應服務器host_key的檢查

基於ksy驗證,實現無密鑰登陸管理

[root@localhost ~]# ssh-keygen              
[root@localhost ~]# ssh-copy-id 192.168.2.20
[root@localhost ~]# ssh-copy-id 192.168.2.30
[root@localhost ~]# ssh-copy-id 192.168.2.40

測試連通

[root@localhost ~]# ansible web1 -m ping
192.168.2.20 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.2.30 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[root@localhost ~]# ansible web2 -m ping
192.168.2.30 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.2.40 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

playbook變量使用

[root@localhost ansible]# ansible all -m setup  #查看全部變量

[root@localhost ansible]# ansible-playbook -e port=6869 file.yml        #命令行指定變量,優先級最高
ansible_hostname
ansible_memtotal_mb

調用ansible_hostname變量
---
# file var
 - hosts: web1
   remote_user: root

   tasks:
     - name: file
       file: name=/tmp/{{ansible_hostname}}.log state=touch

在清單裏定義變量port和mark

[root@localhost ansible]# vim /etc/ansible/hosts
[web2]
192.168.2.30 port=80
192.168.2.40 port=8080
[web2:vars]                 
mark="_"

調用變量
---
# file var
 - hosts: web1
   remote_user: root

   tasks:
     - name: file
       file: name=/tmp/{{ ansible_hostname }}{{ mark }}{{ port }}.log state=touch

在playbook定義變量

---
# file var
 - hosts: web1
   remote_user: root
   vars_files:
     - vars.yml                 #調用vars.yuml變量文件
---
# file var
 - hosts: web1
   remote_user: root
   vars:
     - port: 1989               #文件內定義

模板template

文本文件,嵌套有腳本(使用模板編程語言編寫)
Jinja2語言,使用字面量,有下面形式
    字符串:使用單引號或雙引號
    數字:整數,浮點數
    列表:[item1, item2, ...]
    元組:(item1, item2, ...)
    字典:{key1:value1, key2:value2, ...}
    布爾型:true/false
算術運算:+, -, *, /, //, %, **
比較操做:==, !=, >, >=, <, <=
邏輯運算:and,or,not
流表達式:For,If,When

template功能:根據模塊文件動態生成對應的配置文件
    template文件必須存放於templates目錄下,且命名爲 .j2 結尾
    yaml/yml 文件需和templates目錄平級,目錄結構以下:
 ./
 ├── temnginx.yml
 └── templates
 └── nginx.conf.j2

 ---
#nginx 
- hosts: web2
  remote_user: root

  tasks:
    - name: package
      yum: name=nginx
    - name: config
      template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
      notify: restart
    - name: service
     service: name=nginx state=started enabled=yes

   handlers:
     - name: restart
       service: name=nginx state=restarted

[root@localhost ansible]# tree
.
├── nginx.yml
└── templates
    └── nginx.conf.j2

when條件判斷

---
#install httpd
- hosts: web1
  remote_user: root

  tasks:
    - name: install package
      yum: name=httpd
    - name: config file
      template: src=templates/httpd.conf6.j2 dest=/etc/httpd/conf/httpd.conf
      when: ansible_distribution_major_version == "6"
      notify: restart service
    - name: config file
      template: src=templates/httpd.conf7.j2 dest=/etc/httpd/conf/httpd.conf
      when: ansible_distribution_major_version == "7"
    - name: service
      service: name=httpd state=started enabled=yes
      tags: service

  handlers:
    - name: restart service
      service: name=httpd state=restarted

迭代:with_items

---
# file var
 - hosts: web1
   remote_user: root

   tasks:
     - name: file
       file: name=/tmp/{{item}}.log state=touch
       with_items:
         - abc
         - qwe
         - 798

---
- hosts: web1
  remote_user: root

  tasks:
    - name: create user
      user: name={{item}}
      with_items:
        - huahua
        - lili
        - yangyang

---
- hosts: web1
  remote_user: root

  tasks:
    - name: create group
      group: name={{item}}
      with_items:
        - agroup
        - bgroup
        - cgroup

    - name: create user
      user: name={{item.name}} group={{item.group}}
      with_items:
        - {name: "huahua",group: "agroup"}
        - {name: "lili",group: "bgroup"}
        - {name: "yangyang",group: "cgroup"}

template for if
1

[root@localhost templates]# pwd
/tmp/ansible/templates
[root@localhost templates]# vim test.j2         #模板文件
{%for i in ports  %}
server{
    listen  {{i}}
    server_name www.a.com
    root        /app/log/
}
{%endfor%}

[root@localhost ansible]# pwd
/tmp/ansible
[root@localhost ansible]# vim test.yml      #YAML文件調用
---
- hosts: web1
  remote_user: root
  vars:
    ports:
      - 81
      - 82
      - 83

  tasks:
    - name: template
      template: src=test.j2 dest=/tmp/test.conf

[root@localhost ansible]# ansible-playbook -C test.yml 
[root@localhost ansible]# ansible-playbook test.yml 
[root@localhost ansible]# ansible web1 -a 'cat /tmp/test.conf'
192.168.2.20 | CHANGED | rc=0 >>
server{
    listen  81
    server_name www.a.com
    root        /app/log/
}
server{
    listen  82
    server_name www.a.com
    root        /app/log/
}
server{
    listen  83
    server_name www.a.com
    root        /app/log/
}
...

2

[root@localhost templates]# pwd
/tmp/ansible/templates
[root@localhost templates]# vim test2.j2 
{%for i in vhosts  %}
server{
    listen  {{i.port}}
    server_name {{i.name}}
    root     {{i.dir}}
}
{%endfor%}

[root@localhost ansible]# pwd
/tmp/ansible
[root@localhost ansible]# vim test2.yml
---
- hosts: web1
  remote_user: root
  vars:
    vhosts:
      - web1:
        port: 81
        name: www.a.com
        dir: /tmp/webs
      - web1:
        port: 82
        name: www.b.com
        dir: /tmp/webs
      - web1:
        port: 83
        name: www.c.com
        dir: /tmp/webs

  tasks:
    - name: template
      template: src=test2.j2 dest=/tmp/test2.conf

[root@localhost ansible]# ansible-playbook -C test2.yml
[root@localhost ansible]# ansible-playbook test2.yml
[root@localhost ansible]# ansible web1 -a "cat /tmp/test2.conf"
192.168.2.30 | CHANGED | rc=0 >>
server{
    listen  81
    server_name www.a.com
    root     /tmp/webs
}
server{
    listen  82
    server_name www.b.com
    root     /tmp/webs
}
server{
    listen  83
    server_name www.c.com
    root     /tmp/webs
}
...

3

[root@localhost templates]# pwd
/tmp/ansible/templates
[root@localhost templates]# vim test3.j2 
{%for i in vhosts  %}
server{
    listen  {{i.port}}
{% if i.name is defined %}
    server_name  {{i.name}}
{% endif %}
    root  {{i.dir}}
}

{%endfor%}

[root@localhost ansible]# pwd
/tmp/ansible
[root@localhost ansible]# vim test3.yml 
---
- hosts: web1
  remote_user: root
  vars:
    vhosts:
      - web1:
        port: 81
        # name: www.a.com
        dir: /tmp/webs
      - web1:
        port: 82
        name: www.b.com
        dir: /tmp/webs
      - web1:
        port: 83
        #name: www.c.com
        dir: /tmp/webs

  tasks:
    - name: template
      template: src=test3.j2 dest=/tmp/test3.conf

[root@localhost ansible]# ansible-playbook -C test3.yml 
[root@localhost ansible]# ansible-playbook test3.yml 
[root@localhost ansible]# ansible web1 -a 'cat /tmp/test3.conf'
192.168.2.30 | CHANGED | rc=0 >>
server{
    listen  81
    root  /tmp/webs
}

server{
    listen  82
    server_name  www.b.com
    root  /tmp/webs
}

server{
    listen  83
    root  /tmp/webs
}

Roles角色

/roles/project/ :項目名稱,有如下子目錄

  files/ :存放由copy或script模塊等調用的文件

  templates/:template模塊查找所須要模板文件的目錄

  tasks/:定義task,role的基本元素,至少應該包含一個名爲main.yml的文件;
其它的文件須要在此文件中經過include進行包含

  handlers/:至少應該包含一個名爲main.yml的文件;其它的文件須要在此
文件中經過include進行包含

  vars/:定義變量,至少應該包含一個名爲main.yml的文件;其它的文件須要
在此文件中經過include進行包含

  meta/:定義當前角色的特殊設定及其依賴關係,至少應該包含一個名爲
main.yml的文件,其它文件需在此文件中經過include進行包含

  default/:設定默認變量時使用此目錄中的main.yml文件

建立role的步驟
  (1) 建立以roles命名的目錄
  (2) 在roles目錄中分別建立以各角色名稱命名的目錄,如webservers等
  (3) 在每一個角色命名的目錄中分別建立files、handlers、meta、tasks、
templates和vars目錄;用不到的目錄能夠建立爲空目錄,也能夠不建立
  (4) 在playbook文件中,調用各角色

安裝httpd

目錄結構
[root@localhost ansible]# tree
.
├── role-httpd.yml
└── roles
    └── httpd
        ├── files
        │   ├── httpd.conf
        │   └── index.html
        └── tasks
            ├── conf.yml
            ├── data.yml
            ├── install.yml
            ├── main.yml
            └── service.yml

[root@localhost tasks]# cat conf.yml 
- name: config
  copy: src=httpd.conf dest=/etc/httpd/conf/httpd.conf

[root@localhost tasks]# cat data.yml 
- name: copy data file
  copy: src=index.html dest=/var/www/html/index.html

[root@localhost tasks]# cat install.yml 
- name: install package
  yum: name=httpd

[root@localhost tasks]# cat service.yml 
- name: service
  service: name=httpd state=started enabled=yes

[root@localhost tasks]# cat main.yml 
- include: install.yml
- include: conf.yml
- include: data.yml
- include: service.yml

[root@localhost ansible]# cat role-httpd.yml 
---
#test httpd role
- hosts: web1

  roles:
    - role: httpd

[root@localhost ansible]# ansible-playbook role-httpd.yml

nginx安裝

目錄結構
[root@localhost ansible]# tree
.
├── role-httpd.yml
├── role-nginx.yml
└── roles
    ├── httpd
    │   ├── files
    │   │   ├── httpd.conf
    │   │   └── index.html
    │   └── tasks
    │       ├── conf.yml
    │       ├── data.yml
    │       ├── install.yml
    │       ├── main.yml
    │       └── service.yml
    └── nginx
        ├── files
        │   └── index.html
        ├── handlers
        │   └── main.yml
        ├── tasks
        │   ├── config.yml
        │   ├── data.yml
        │   ├── group.yml
        │   ├── install.yml
        │   ├── main.yml
        │   ├── service.yml
        │   └── user.yml
        ├── templates
        │   └── nginx.conf.j2
        └── vars
            └── main.yml
[root@localhost handlers]# cat main.yml 
- name: restart service
  service: name=nginx state=restarted

[root@localhost tasks]# cat config.yml 
- name: config
  template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
  notify: restart service

[root@localhost tasks]# cat data.yml 
- name: copy data file
  copy: src=index.html dest=/usr/share/nginx/html/index.html

[root@localhost tasks]# cat group.yml 
- name: group
  group: name=nginx system=yes gid=77 

[root@localhost tasks]# cat user.yml 
- name: user
  user: name=nginx system=yes uid=77 group=nginx

[root@localhost tasks]# cat install.yml 
- name: install
  yum: name=nginx 

[root@localhost tasks]# cat service.yml 
- name: service
  service: name=nginx state=started enabled=yes

[root@localhost nginx]# cat tasks/main.yml 
- include: group.yml
- include: user.yml
- include: install.yml
- include: config.yml
- include: data.yml
- include: service.yml

[root@localhost ansible]# cat role-nginx.yml 
---
#test nginx role
- hosts: web2

  roles:
    - role: nginx

tags標籤和when判斷

---
#test httpd role
- hosts: web1:web3

  roles:
    - role: httpd
      tags: web
      when: ansible_distribution_major_version == "6"
    - role: nginx
      tags: web2
      when: ansible_distribution_major_version == "7"

[root@localhost ansible]# ansible-playbook -t web1 role-httpd-nginx.yml
相關文章
相關標籤/搜索