Ansible

Ansible

Ansible 是一種 agentless(基於 ssh),可實現批量配置、命令執行和控制,基於 Python 實現的自動化運維工具。
其特性有:javascript

  • 模塊化:經過調用相關模塊,完成指定任務,且支持任何語言編寫的自定義模塊
  • playbook:劇本,可根據須要一次執行完劇本中的全部任務或某些任務
        
    /usr/bin/ansible: 命令行工具
    ansible 命令通用格式:ansible [options] [-m module_name] [-a args]
    /usr/bin/ansible-doc: 幫助文檔
    /usr/bin/ansible-playbook: 劇本執行工具
    /etc/ansible/ansible.cfg: 主配置文件
    /etc/ansible/hosts: 管理的主機清單
    /etc/ansible/roles: 角色存放處

一、安裝ansible(依賴於epel源)php

wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo

yum install ansible -y

執行ansible報錯html

ERROR! Unexpected Exception, this is probably a bug: (cryptography 0.8.2 (/usr/lib64/python2.7/site-packages), Requirement.parse('cryptography>=1.1'))

解決方法
rpm -qa |grep python-crypto    把列出的 rpm 包所有刪除
rpm -e python-cryptography --nodeps    強制刪除

二、定義HOSTS文件,配置主機,配置登錄方式java

cd /etc/ansible/
cp  hosts{,.bak}

2-1使用配置文件認證方式(不推薦這種方式)node

vim hosts
[webs]
192.168.2.100 ansible_ssh_user=root ansible_ssh_pass=123456
192.168.2.101 ansible_ssh_user=root ansible_ssh_pass=123456 ansible_ssh_port=22

[dbs]
192.168.2.102 ansible_ssh_user=root ansible_ssh_pass=123456 ansible_ssh_port=22

若報這個錯,需用SSH鏈接一次便可python

[root@ansibles ansible]# ansible

192.168.2.101 | FAILED! => {
    "msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this.  Please add this host's fingerprint to your known_hosts file to manage this host."
}

[root@ansibles ansible]# ssh 192.168.2.101
The authenticity of host '192.168.2.101 (192.168.2.101)' can't be established.
ECDSA key fingerprint is 58:da:34:71:b4:08:0c:95:c3:ff:72:15:c4:05:10:24.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.2.101' (ECDSA) to the list of known hosts.
root@192.168.2.101's password: 
Last login: Tue Oct 23 13:26:43 2018 from 192.168.2.254

2-2基於密鑰方式登錄mysql

ssh-keygen -t rsa
ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.2.100
ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.2.101
ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.2.102

配置完測下linux

ansible all -m ping
192.168.2.101 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.2.100 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.2.102 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

三、如何查看模塊幫助
ansible-doc -l 列出哪些模塊
ansible-doc -s MODULE_NAME 查看模塊參數web

語法
ansible <host-pattern> [options]
-f forks:啓動的併發線程數
-m module_name:要使用的模塊
-a args:模塊物有的參數sql

經常使用模塊

command:命令模塊,默認模塊,用於在遠程執行命令

  • creates:一個文件名,當該文件存在,則該命令不執行
  • free_form:要執行的 linux 指令
  • chdir:在執行指令以前,先切換到該目錄
  • removes:一個文件名,當該文件不存在,則該選項不執行
  • executable:切換 shell 來執行指令,該執行路徑必須是一個絕對路徑
    ansible all -a 'date'
    ansible all -m command 'date'

cron:計劃任務模塊

  • minute=/hour=/day=/month=/weekday= 某個值不寫,默認就是 *
  • name: 必選項,任務描述信息
  • job: 執行的任務,要加引號
  • state:present(建立)/absent(刪除)
ansible all -m cron -a 'minute="30" hour="3" job="usr/sbin/ntpdate ntp.aliyun.com" name="ntp date time"'

查看下結果 
[root@ansibles ~]# ansible all -a 'crontab -l'
刪除此計劃任務
ansible all -m cron -a 'name="ntp date time" state=absent'

user模塊

  • name: 用戶名
  • password: 爲用戶設置登錄密碼,此密碼是明文密碼加密後的密碼
  • update_password:always/on_create
    • always: 只有當密碼不相同時纔會更新密碼 (默認)
    • on_create: 只爲新用戶設置密碼
  • shell: 用戶的 shell 設定
  • groups: 用戶組設定
  • home: 指定用戶的家目錄
  • state:present/absent
  • append:yes/no
    • yes: 增量添加 group
    • no: 全量變動 group, 只設置 groups 指定的 group 組 (默認)
  • remove: 配合 state=absent 使用,刪除用戶的家目錄 ->remove=yes
  • expires: 設置用戶的過時時間,值是一個時間戳
建立用戶
ansible dbs -m user -a 'name="user1"'
192.168.2.102 | SUCCESS => {
    "changed": true, 
    "comment": "", 
    "createhome": true, 
    "group": 1000, 
    "home": "/home/user1", 
    "name": "user1", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1000
}
刪除用戶
ansible dbs -m user -a 'name="user1" state=absent'

group模塊

  • name: 組名稱
  • gid: 指定 GID
  • state:present/absent
  • system:yes/no
ansible dbs -m group -a 'name=mysql gid=306 system=yes'
ansible dbs -m user -a 'name=mysql uid=306 system=yes group=mysql'

驗證下
ansible dbs -a 'grep mysql /etc/passwd'

copy模塊

  • backup:在覆蓋以前,將源文件備份,備份文件包含時間信息。有兩個選項:yes|no
  • content:用於替代 「src」,能夠直接設定指定文件的值
  • dest:必選項。要將源文件複製到的遠程主機的絕對路徑,若是源文件是一個目錄,那麼該路徑也必須是個目錄
  • directory_mode:遞歸設定目錄的權限,默認爲系統默認權限
  • force:若是目標主機包含該文件,但內容不一樣,若是設置爲yes,則強制覆蓋,若是爲 no,則只有當目標主機的目標位置不存在該文件時,才複製。默認爲 yes
  • others:全部的 file 模塊裏的選項均可以在這裏使用
  • src:被複制到遠程主機的本地文件,能夠是絕對路徑,也能夠是相對路徑。若是路徑是一個目錄,它將遞歸複製。在這種狀況下,若是路徑使用 「/」 來結尾,則只複製目錄裏的內容,若是沒有使用 「/」 來結尾,則包含目錄在內的整個內容所有複製,相似於 rsync。
複製文件
ansible dbs -m copy -a 'src=/etc/fstab dest=/tmp/fstab.ans owner=root mode=600'
ansible dbs -a 'ls /tmp/fstab.ans'

content=取代src=,代表用此處的信息生成目標文件
使用信息輸出目標文件
ansible dbs -m copy -a 'content="ansbile test" dest=/tmp/test.ans'
ansible dbs -a 'cat /tmp/test.ans'

file模塊:設定文件屬性

  • group:定義文件 / 目錄的屬組
  • mode:定義文件 / 目錄的權限
  • owner:定義文件 / 目錄的屬主
  • path:必選項,定義文件 / 目錄的路徑 指定符號連接文件路徑
  • recurse:遞歸設置文件的屬性,只對目錄有效
  • src:被連接的源文件路徑,只應用於 state=link 的狀況
  • dest:被連接到的路徑,只應用於 state=link 的狀況
  • state:
    • directory:若是目錄不存在,就建立目錄
    • file:即便文件不存在,也不會被建立
    • link:建立軟連接
    • hard:建立硬連接
    • touch:若是文件不存在,則會建立一個新的文件,若是文件或目錄已存在,則更新其最後修改時間
    • absent:刪除目錄、文件或者取消連接文件
更換文件權限
ansible dbs -m file -a 'owner=mysql group=mysql mode=600 path=/tmp/test.ans'
建立連接文件
ansible dbs -m file -a 'path=/tmp/fstab.link src=/tmp/fstab.ans state=link'

ping模塊

測試遠程主機的是否在線

ansible all -m ping

service模塊指定服務運行狀態

  • enabled=是否開機自動啓動,取值爲true或者false
  • name=服務名稱
  • state=狀態,會有started stoped restarted
  • runlevel: 運行級別
ansible dbs -m service -a 'enabled=true name=mysqld state=started'

shell模塊

雖然執行成功,但密碼沒有設置成功,可能當作本地的命令符號
注意:尤爲是用到管道等功能的複雜命令,使用shell模塊

ansible all  -a 'echo password|passwd --stdin user1'
若使用到管理符號請使用shell模塊 ansible all  -m shell -a 'echo password|passwd --stdin user1' 

script模塊

將本地腳本複製到遠程主機並運行
注意:要使用相對路徑指定腳本

ansible all -m script -a '/root/test.sh'

yum模塊

安裝程序包

  • name=指明要安裝的程序包,能夠帶上版本號
  • state=present,latest表示安裝,absent表示卸載
ansible dbs -m yum -a 'name=vsftpd'

setup模塊

查看遠程主機的相關 facts 變量信息

ansible all -m setup

playbook組成結構

inventory
modules
ad hoc commands
playbooks
    tasks:任務
    variables:變量
    templates:模板
    handlers:處理器
    roles:角色

示例1 安裝httpd包,配置文件,啓動服務

vim webs.yml
- hosts: webs
 remote_user: root
 tasks:
  - name: install httpd package
 yum: name=httpd
  - name: install httpd config
 copy: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
  - name: start httpd service
 service: enabled=true name=httpd state=started

示例2 若更改配置文件,觸發handlers將重啓服務

vim webs.yml
- hosts: webs
 remote_user: root
 tasks:
 - name: install httpd package
 yum: name=httpd
 - name: install httpd config
 copy: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
 notify:
 - restart httpd
 - name: start httpd service
 service: enabled=true name=httpd state=started
 handlers:
 - name: restart httpd
 service: name=httpd state=restarted

示例3 引用變量

- hosts: webs
 remote_user: root
 vars:
 - package: httpd
 - service: httpd
 tasks:
 - name: install httpd package
 yum: name={{ package }}
 - name: install httpd config
 copy: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
 notify:
 - restart httpd
 - name: start httpd service
 service: enabled=true name={{ service }} state=started
 handlers:
 - name: restart httpd
 service: name={{ package }} state=restarted

輸出facts中的某個變量並輸入到文件

- hosts: dbs
  remote_user: root
  tasks:
  - name: copy file
    copy: content="{{ ansible_all_ipv4_addresses }}" dest=/tmp/vars.ans

when 條件測試
知足條件ansible_fqdn == "db1",將執行tasks

vim when.yml
- hosts: all
 remote_user: root
 vars:
 - username: user1
 tasks:
 - name: crate {{ username }} user
 user: name={{ username }}
 when: ansible_fqdn == "db1"

迭代:重複同類task時使用
調用:item
定義循環列表:with_items
- httpd
- php
- mysql-server

注意:with_items中的列表值也能夠是字典,但引用時要使用tiem.KEY
- {name: httpd, conf: configfile/httpd.conf}
- {name: php, conf: configfile/php.ini}
- {name: mysql-server, conf: configfile/my.cnf}

http_port 變量定義在/etc/ansible/hosts文件裏

[root@ansibles ~]# grep port /etc/ansible/hosts
192.168.2.100 http_port=80 
192.168.2.101 http_port=8080

[root@ansibles ~]# vim webs.yml
- hosts: webs
 remote_user: root
 vars:
 - package: httpd
 - service: httpd
 tasks:
 - name: install httpd package
 yum: name={{ package }}
 - name: install httpd config
 template: src=/root/httpd.conf.t1 dest=/etc/httpd/conf/httpd.conf
 notify:
 - restart httpd
 - name: start httpd service
 service: enabled=true name={{ service }} state=started
 handlers:
 - name: restart httpd
 service: name={{ package }} state=restarted
  • tags:在playbook能夠爲某個或某些任務定義一個標籤,在執行此playbook時,經過爲ansible-playbook命令使用--tags選項能實現僅運行指定的tasks而非全部的:
    template: src=/root/httpd.conf.t1 dest=/etc/httpd/conf/httpd.conf
    tags:
    - conf

    特殊tags: always

--tags="conf" --tars="restart"

- hosts: webs   remote_user: root
  vars:
  - package: httpd   - service: httpd   tasks:
  - name: install httpd package     yum: name={{ package }}
    tags:
    - always   - name: install httpd config     template: src=/root/httpd.conf.t1 dest=/etc/httpd/conf/httpd.conf
    tags:
    - conf     notify:
    - restart httpd   - name: start httpd service     service: enabled=true name={{ service }} state=started
    tags:
    - restart   handlers:
  - name: restart httpd     service: name={{ package }} state=restarted

roles:

目錄名同角色名
目錄結構有固定格式

  • files:靜態文件
  • templates:jinjia2模板文件
  • tasks:至少有mail.yml文件,定義名tasks
  • handlers:至少有一個mail.yml定義handlers
  • vars:至少有一個mail.yml文件,定義變量
  • meta:定義依賴關係等信息
  • site.yml中定義playbook,額外也能夠有其它的yml文件
建立目錄
mkdir -pv ansible_playbooks/roles/{webs,dbs}/{tasks,files,templates,meta,handlers,vars}
查看建立的目錄結構 
[root@ansibles ~]# tree ansible_playbooks/
ansible_playbooks/
├── roles
│   ├── dbs
│   │   ├── files
│   │   ├── handlers
│   │   ├── meta
│   │   ├── tasks
│   │   ├── templates
│   │   └── vars
│   └── webs
│       ├── files
│       │   └── httpd.conf
│       ├── handlers
│       │   └── main.yml
│       ├── meta
│       ├── tasks
│       │   └── main.yml
│       ├── templates
│       │   └── httpd.conf.j2
│       └── vars
│           └── main.yml
└── site.yml

下面是相關的配置文件

vim /root/ansible_playbooks/roles/webs/handlers/main.yml
- name: restart httpd
  service: name=httpd state=restarted
vim /root/ansible_playbooks/roles/webs/tasks/main.yml
- name: install httpd package
  yum: name=httpd
- name: install conf file
  template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
  tags:
  - conf
  notify:
  - restart httpd
- name: start httpd service
  service: name=httpd state=started enabled=true
grep "{{" /root/ansible_playbooks/roles/webs/templates/httpd.conf.j2 
Listen {{ http_port }}
ServerName {{ ansible_fqdn }}
vim /root/ansible_playbooks/roles/webs/vars/main.yml
http_port: "{{ 8888 }}"

驗證下

[root@ansibles ~]#ansible-playbook ansible_playbooks/site.yml
[root@ansibles ~]# ansible webs -a 'ss -tnl'|grep 8888
LISTEN     0      128         :::8888                    :::*                  
LISTEN     0      128         :::8888                    :::*
相關文章
相關標籤/搜索