Ansible 極簡教程

一、基本部署

安裝Ansible

# yum -y install epel-release# yum list all *ansible*# yum info ansible# yum -y install ansible

Ansible配置文件

/etc/ansible/ansible.cfg    主配置文件
/etc/ansible/hosts          Inventory
/usr/bin/ansible-doc        幫助文件
/usr/bin/ansible-playbook   指定運行任務文件

定義Inventory

# cd /etc/ansible/# cp hosts{,.bak}# > hosts # cat hosts[webserver]
127.0.0.1
192.168.10.149

[dbserver]
192.168.10.113

使用祕鑰方式連接

# ssh-keygen -t rsa # ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]# ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]# ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]

使用幫助

# ansible-doc -l                列出ansible所有的模塊# ansible-doc -s MODULE_NAME    查看指定模塊具體適用

Ansible命令應用基礎

語法:ansible <host-pattern> [-f forks] [-m module_name] [-a args]

<host-pattern>  這次命令對哪些主機生效的
    inventory group name
    ip
    all
-f forks        一次處理多少個主機
-m module_name  要使用的模塊
-a args         模塊特有的參數# ansible 192.168.10.113 -m command -a 'date'# ansible webserver -m command -a 'date'# ansible all -m command -a 'date'

二、常見模塊

command     命令模塊(默認模塊)用於在遠程主機執行命令;不能使用變量,管道等    # ansible all -a 'date'
cron        計劃任務    
    month   指定月份
    minute  指定分鐘
    job     指定任務
    day     表示那一天
    hour    指定小時
    weekday 表示周幾
    state   表示是添加還是刪除
        present:安裝
        absent:移除    # ansible webserver -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job"'   #不寫默認都是*,每個任務都必須有一個名字 
    # ansible webserver -a 'crontab -l'
    # ansible webserver -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state=absent'  #移除任務
user    用戶賬號管理
    name    用戶名
    uid     uid
    state   狀態  
    group   屬於哪個組
    groups  附加組
    home    家目錄
    createhome  是否創建家目錄    comment 註釋信息    system  是否是系統用戶
    
    # ansible all -m user -a 'name="user1"'
    # ansible all -m user -a 'name="user1" state=absent'
group   組管理
    gid     gid      
    name    組名               
    state   狀態           
    system  是否是系統組    # ansible webserver -m group -a 'name=mysql gid=306 system=yes'
    # ansible webserver -m user -a 'name=mysql uid=306 system=yes group=mysql'
copy    複製文件(複製本地文件到遠程主機的指定位置)
    src     定義本地源文件路徑
    dest    定義遠程目錄文件路徑(絕對路徑)
    owner   屬主
    group   屬組
    mode    權限
    content 取代src=,表示直接用此處的信息生成爲文件內容    # yum -y install libselinux-python
    # ansible all -m copy -a 'src=/etc/fstab dest=/tmp/fstab.ansible owner=root mode=640'
    # ansible all -m copy -a 'content="hello ansible\nHi ansible" dest=/tmp/test.ansible'
file    設置文件的屬性
    path|dest|name  對那個文件做設定
    
    創建文件的符號鏈接:
        src:    指定源文件
        path:   指明符號鏈接文件路徑    # ansible all -m file -a 'owner=mysql group=mysql mode=644 path=/tmp/fstab.ansible'
    # ansible all -m file -a 'path=/tmp/fstab.link src=/tmp/fstab.ansible state=link'
ping    測試指定主機是否能連接    # ansible all -m ping
service 管理服務運行狀態
    enabled 是否開機自動啓動
    name    指定服務名    state   指定服務狀態
        started     啓動服務
        stoped      停止服務
        restarted   重啓服務
    arguments   服務的參數    # ansible webserver -m service -a 'enabled=true name=httpd state=started'
shell   在遠程主機上運行命令
    尤其是用到管道變量等功能的複雜命令    # ansible all -m shell -a 'echo magedu | passwd --stdin user1'
script  將本地腳本複製到遠程主機並運行之    # ansible all -m script -a '/tmp/test.sh'
yum     安裝程序包
    name    程序包名稱(不指定版本就安裝最新的版本latest)    state   present,latest表示安裝,absent表示卸載    # ansible webserver -m yum -a 'name=httpd'
    # ansible all -m yum -a 'name=ntpdate'  #默認就是安裝
    # ansible all -m yum -a 'name=ntpdate state=absent'
setup   收集遠程主機的facts
    每個被管理節點在接受並運行管理命令之前,會將自己主機相關信息,如操作系統版本,IP地址等報告給遠程的ansible主機 
    # ansible all -m setup

三、Ansible playbook

組成結構:

inventory       #以下操作應用的主機modules         #調用哪些模塊做什麼樣的操作ad hoc commands #在這些主機上運行哪些命令playbooks   
    tasks       #任務,即調用模塊完成的某操作
    variable    #變量
    templates   #模板
    handlers    #處理器,由某事件觸發執行的操作
    roles       #角色

四、YAML

4.1 YAML介紹

YAML是一個可讀性高的用來表達資料序列的格式。YAML參考了其它多種語言,包括:XML、C語言、Python、Perl以及電子郵件格式RFC2822等。ClarkEvans在2001年首次發表了這種語言,另外Ingy dot Net與Oren Ben-Kiki也是這語言的共同設計者。

YAML Ain't Markup Language,即YAML不是XML,不過,在開發這種語言時,YAML的意思其實是:"Yet Another Markup Language"(仍是一種標記語言),其特性:

  • YAML的可讀性好

  • YAML和腳本語言的交互性好

  • YAML使用實現語言的數據類型

  • YAML有一個一致的信息模型

  • YAML易於實現

  • YAML可以基於流來處理

  • YAML表達能力強,擴展性好

更多的內容及規範參見http://www.yaml.org

4.2 YAML語法

YAML的語法和其他高階語言類似,並且可以簡單表達清單、散列表、標量等數據結構,其結構(structure)通過空格來展示,序列(sequence)裏的項用"-"來表示,Map裏面的鍵值對用":"分割,下面是一個示例。

name: john smithage: 41gender: malespouse:    name:jane smith
    age:37
    gender: femalechildren:    -   name:jimmy smith
        age:17
        gender: male
    -   name:jenny smith
        age: 13        gender: female

YAML文件擴展名通常爲.yaml,如example.yaml

4.2.1 list

列表的所有元素均使用"-"打頭,例如:

# A list of testy fruits- Apple- Orange- Strawberry- Mango

4.2.2 dictionary

字典通過key與value進行標識,例如:

---# An employee recordname: Example Developerjob: Developerskill: Elite

也可以將key:value放置於{}中進行表示,例如:

---#An exmloyee record{name: Example Developer, job: Developer, skill: Elite}

五、Ansible基礎元素

5.1 變量

5.1.1 變量命名

變量名僅能由字母、數字和下劃線組成,且只能以字母開頭。

5.1.2 facts

facts是由正在通信的遠程目標主機發回的信息,這些信息被保存在ansible變量中。要獲取指定的遠程主機所支持的所有facts,可使用如下命令進行:

#ansible hostname -m setup

5.1.3 register

把任務的輸出定義爲變量,然後用於其他任務,實例如下:

tasks:
    - shell: /usr/bin/foo
      register: foo_result
      ignore_errors: True

5.1.4 通過命令行傳遞變量

在運行playbook的時候也可以傳遞一些變量供playbook使用,示例如下:

#ansible-playbook test.yml --extra-vars "hosts=www user=mageedu"

5.1.5 通過roles傳遞變量

當給一個主機應用角色的時候可以傳遞變量,然後在角色內使用這些變量,示例如下:

- hosts: webserver
  roles:    - common
    - {role: foo_app_instance, dir: '/web/htdocs/a.com', port: 8080}

5.2 Inventory

ansible的主要功用在於批量主機操作,爲了便捷的使用其中的部分主機,可以在inventory file中將其分組命名,默認的inventory file爲/etc/ansible/hosts

inventory file可以有多個,且也可以通過Dynamic Inventory來動態生成。

5.2.1 inventory文件格式

inventory文件遵循INI文件風格,中括號中的字符爲組名。可以將同一個主機同時歸併到多個不同的組中;此外,當如若目標主機使用非默認的SSH端口,還可以在主機名稱之後使用冒號加端口號來表明。

ntp.magedu.com[webserver]www1.magedu.com:2222www2.magedu.com[dbserver]db1.magedu.comdb2.magedu.comdb3.magedu.com如果主機名遵循相似的命名模式,還可使用列表的方式標識個主機,例如:[webserver]www[01:50].example.com[databases]db-[a:f].example.com

5.2.2 主機變量

可以在inventory中定義主機時爲其添加主機變量以便於在playbook中使用,例如:

[webserver]
www1.magedu.com http_port=80 maxRequestsPerChild=808www2.magedu.com http_port=8080 maxRequestsPerChild=909

5.2.3 組變量

組變量是指賦予給指定組內所有主機上的在playbook中可用的變量。例如:

[webserver]
www1.magedu.com
www2.magedu.com[webserver:vars]ntp_server=ntp.magedu.com
nfs_server=nfs.magedu.com

5.2.4 組嵌套

inventory中,組還可以包含其它的組,並且也可以向組中的主機指定變量。不過,這些變量只能在ansible-playbook中使用,而ansible不支持。例如:

[apache]
httpd1.magedu.com
httpd2.magedu.com

[nginx]
ngx1.magedu.com
ngx2.magedu.com

[webserver:children]    #固定格式apache
nginx

[webserver:vars]
ntp_server=ntp.magedu.com

5.2.5 inventory參數

ansible基於ssh連接inventory中指定的遠程主機時,還可以通過參數指定其交互方式,這些參數如下所示:

ansible_ssh_hostansible_ssh_port
ansible_ssh_user
ansible_ssh_pass
ansible_sudo_pass
ansible_connection
ansible_ssh_private_key_file
ansible_shell_type
ansible_python_interpreter

5.3 條件測試

如果需要根據變量、facts或此前任務的執行結果來做爲某task執行與否的前提時要用到條件測試。

5.3.1 when語句

在task後添加when字句即可使用條件測試;when語句支持jinja2表達式語句,例如:

tasks:
  - name: 'shutdown debian flavored system"
    command: /sbin/shutdown -h now
    when: ansible_os_family == "Debian"

when語句中還可以使用jinja2的大多"filter",例如果忽略此前某語句的錯誤並基於其結果(failed或success)運行後面指定的語句,可使用類似如下形式;

tasks:
  - command:/bin/false
    register: result
    ignore_errors: True
  - command: /bin/something
    when: result|failed
  - command: /bin/something_else
    when: result|success
  - command: /bin/still/something_else
    when: result|skipped

此外,when語句中還可以使用facts或playbook中定義的變量

# cat cond.yml - hosts: all
  remote_user: root
  vars:
  - username: user10
  tasks:
  - name: create {{ username }} user
    user: name={{ username }} 
    when: ansible_fqdn == "node1.exercise.com"

5.4 迭代

當有需要重複性執行的任務時,可以使用迭代機制。其使用格式爲將需要迭代的內容定義爲item變量引用,並通過with_items語句來指明迭代的元素列表即可。例如:

- name: add server user
  user: name={{ item }} state=persent groups=wheel
  with_items:
    - testuser1
    - testuser2

上面語句的功能等同於下面的語句:

- name: add user testuser1
  user: name=testuser1 state=present group=wheel
- name: add user testuser2
  user: name=testuser2 state=present group=wheel

事實上,with_items中可以使用元素還可爲hashes,例如:

- name: add several users
  user: name={{ item.name}} state=present groups={{ item.groups }}
  with_items:
    - { name: 'testuser1', groups: 'wheel'}
    - { name: 'testuser2', groups: 'root'}

Ansible的循環機制還有更多的高級功能,具體請參考官方文檔http://docs.ansible.com/playbooks_loops.html

六、模板示例:

# grep '{{' conf/httpd.conf MaxClients       {{ maxClients }}
Listen {{ httpd_port }}# cat /etc/ansible/hosts[webserver]127.0.0.1 httpd_port=80 maxClients=100192.168.10.149 httpd_port=8080 maxClients=200# cat apache.yml - hosts: webserver
  remote_user: root
  vars:
  - package: httpd
  - service: httpd
  tasks:
  - name: install httpd package
    yum: name={{ package }} state=latest
  - name: install configuration file for httpd
    template: src=/root/conf/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=httpd state=restarted

七、Ansible playbooks

playbook是由一個或多個"play"組成的列表。play的主要功能在於將事先歸併爲一組的主機裝扮成事先通過ansible中的task定義好的角色。從根本上來講,所有task無非是調用ansible的一個module。將多個play組織在一個playbook中,即可以讓他們連同起來按事先編排的機制同唱一臺大戲。下面是一個簡單示例。

- hosts: webserver
  vars:
    http_port: 80
    max_clients: 256
  remote_user: root
  tasks:
  - name: ensure apache is at the latest version
    yum: name=httpd state=latest
  - name: ensure apache is running
    service: name=httpd state=started
  handlers:
    - name: restart apache
      service: name=httpd state=restarted

7.1 playbook基礎組件

7.1.1 Hosts和Users

playbook中的每一個play的目的都是爲了讓某個或某些主機以某個指定的用戶身份執行任務。hosts用於指定要執行指定任務的主機,其可以使一個或多個由冒號分隔主機組;remote_user則用於指定遠程主機的執行任務的用戶,如上面的實例中的

- hosts: webserver
  remote_user: root

不過,remote_user也可用於各task中,也可以通過指定其通過sudo的方式在遠程主機上執行任務,其可用於play全局或其任務;此外,甚至可以在sudo時使用sudo_user指定sudo時切換的用戶。

- hosts: webserver
  remote_user: magedu
  tasks:
   - name: test connection
     ping:
     remote_user: magedu
     sudo: yes

7.1.2 任務列表和action

play的主題部分是task list。task list中的各任務按次序逐個在hosts中指定的所有主機上執行,即在所有主機上完成第一個任務後再開始第二個。在運行自上而下某playbook時,如果中途發生錯誤,所有已執行任務都可能回滾,在更正playbook後重新執行一次即可。

taks的目的是使用指定的參數執行模塊,而在模塊參數中可以使用變量。模塊執行是冪等的。這意味着多次執行是安全的,因爲其結果均一致。

每個task都應該有其name,用於playbook的執行結果輸出,建議其內容儘可能清晰地描述任務執行步驟,如果爲提供name,則action的結果將用於輸出。

定義task可以使用"action: module options"或”module:options“的格式推薦使用後者以實現向後兼容。如果action一行的內容過多,也中使用在行首使用幾個空白字符進行換行。

tasks:
  - name:make sure apache is running
    service: name=httpd state=started

在衆多的模塊中,只有command和shell模塊僅需要給定一個列表而無需使用"key=value"格式,例如:

tasks:
  - name: disable selinux    command: /sbin/setenforce 0

如果命令或腳本的退出碼不爲零,可以使用如下方式替代:

tasks:
  - name: run this command and ignore the result
    shell: /usr/bin/somecommand || /bin/true

或者使用ignore_errors來忽略錯誤信息:

tasks:
  - name: run this command and ignore the result
    shell: /usr/bin/somecommand
    ignore_errors: True

7.1.3handlers

用於當關注的資源發生變化時採取一定的操作。

"notify"這個action可用於在每個play的最後被觸發,這樣可以避免多次有改變發生時每次都執行執行的操作,取而代之,僅在所有的變化發生完成後一次性地執行指定操作,在notify中列出的操作稱爲handlers,也即notify中調用handlers中定義的操作。

- name: template configuration file  template: src=template.j2 dest=/etc/foo.conf
  notify:
    - restart memcached
    - restart apache

handlers是task列表,這些task與前述的task並沒有本質上的不同。

handlers:
  - name: restart memcached
    service: name=memcached state=restarted
  - name: restart apache
    service: name=apache state=restarted

簡單示例1:

# cat nginx.yml - hosts: webserver
  remote_user: root
  tasks:
  - name: create nginxn group
    group: name=nginx system=yes gid=208
  - name: create nginx user
    user: name=nginx uid=208 group=nginx system=yes

- hosts: dbserver
  remote_user: root
  tasks:
  - name: copy file to dbserver
    copy: src=/etc/inittab dest=/tmp/inittab.ans    
# ansible-playbook nginx.yml

簡單示例2:

# cat apache.yml - hosts: webserver
  remote_user: root
  tasks:
  - name: install httpd package
    yum: name=httpd state=latest
  - name: install configuration file for httpd    copy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf
  - name: start httpd service
    service: enabled=true name=httpd state=started# ansible-playbook apache.yml

handlers 示例:

# cat apache.yml - hosts: webserver
  remote_user: root
  tasks:
  - name: install httpd package
    yum: name=httpd state=latest
  - name: install configuration file for httpd    copy: src=/root/conf/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#  ansible-playbook apache.yml

variable 示例1:

# cat apache.yml - hosts: webserver
  remote_user: root
  vars:
  - package: httpd
  - service: httpd
  tasks:
  - name: install httpd package
    yum: name={{ package }} state=latest
  - name: install configuration file for httpd
    copy: src=/root/conf/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=httpd state=restarted

variable 示例2:(在playbook中可以使用所有的變量)

# cat facts.yml - hosts: webserver
  remote_user: root
  tasks:
  - name: copy file    copy: content="{{ ansible_all_ipv4_addresses }} " dest=/tmp/vars.ans

八、roles

ansible自1.2版本引入的新特性,用於層次性、結構化地組織playbook。roles能夠根據層次型結構自動轉載變量文件、tasks以及handlers等。要使用roles只需要在playbook中使用include指令即可。簡單來講,roles就是通過分別將變量、文件、任務、模板以及處理器放置於單獨的目錄中,並可以便捷地include他們的一種機制。角色一般用於基於主機構建服務的場景中,但也可以使用於構建守護進程的場景中

一個roles的案例如下所示:

site.yml
webserver.yml
fooserver.yml
roles/
    common/
        files/
        templates/
        tasks/
        handlers/
        vars/
        meta/
    webserver/
        files/
        templates/
        tasks/
        handlers/
        vars/
        meta/

而在playbook中,可以這樣使用roles

- hosts: webserver
  roles:    - common      - webserver

也可以向roles傳遞參數,例如:

- hosts: webserver
  roles:    - common
    - { role: foo_app_instance, dir:'/opt/a',port:5000}    - { role: foo_app_instance, dir:'/opt/b',port:5001}

甚至也可以條件式地使用roles,例如:

- hosts:webserver
  roles:    - { role: some_role, when: "ansible_so_family == 'RedHat" }

8.1 創建role的步驟

  1. 創建以roles命名的目錄:

  2. 在roles目錄中分別創建以各角色命名的目錄,如webserver等

  3. 在每個角色命名的目錄中分別創建files、handlers、meta、tasks、templates和vars目錄;用不到的目錄可以創建爲空目錄,也可以不創建

  4. 在playbook文件中,調用各角色

8.2 role內各目錄中可應用的文件

  • task目錄:至少應該包含一個爲main.yml的文件,其定義了此角色的任務列表;此文件可以使用include包含其它的位於此目錄中的task文件;

  • file目錄:存放由copy或script等模板塊調用的文件;

  • template目錄:template模塊會自動在此目錄中尋找jinja2模板文件;

  • handlers目錄:此目錄中應當包含一個main.yml文件,用於定義此角色用到的各handlers,在handler中使用inclnude包含的其它的handlers文件也應該位於此目錄中;

  • vars目錄:應當包含一個main.yml文件,用於定義此角色用到的變量

  • meta目錄:應當包含一個main.yml文件,用於定義此角色的特殊設定及其依賴關係;ansible1.3及其以後的版本才支持;

  • default目錄:應當包含一個main.yml文件,用於爲當前角色設定默認變量時使用此目錄;

# mkdir -pv ansible_playbooks/roles/{webserver,dbserver}/{tasks,files,templates,meta,handlers,vars} # cp /etc/httpd/conf/httpd.conf files/  # pwd/root/ansible_playbooks/roles/webserver 
# cat tasks/main.yml - name: install httpd package
  yum: name=httpd state=present
- name: install configuretion file
  copy: src=httpd.conf dest=/etc/httpd/conf/httpd.conf
  tags:
  - conf
  notify:
  - restart httpd
- name: start httpd
  service: name=httpd state=started# cat handlers/main.yml - name: restart httpd
  service: name=httpd state=restarted    
# pwd;ls/root/ansible_playbooks
roles  site.yml 
# cat site.yml - hosts: webserver
  remote_user: root
  roles:
  - webserver# ansible-playbook site.yml

九、Tags

tags用於讓用戶選擇運行或跳過playbook中的部分代碼。ansible具有冪等性,因此會自動跳過沒有變化的部分,即便如此,有些代碼爲測試其確實沒有發生變化的時間依然會非常的長。此時,如果確信其沒有變化,就可以通過tags跳過此些代碼片段。

tags:在playbook可以爲某個或某些任務定義一個"標籤",在執行此playbook時,通過爲ansible-playbook命令使用--tags選項能耐實現僅運行指定的tasks而非所有的;

# cat apache.yml - hosts: webserver
  remote_user: root
  vars:
  - package: httpd
  - service: httpd
  tasks:
  - name: install httpd package
    yum: name={{ package }} state=latest
  - name: install configuration file for httpd
    template: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf
    tags:
    - conf
    notify: 
    - restart httpd
  - name: start httpd service
    service: enabled=true name={{ service }} state=started
  
  handlers:
  - name: restart httpd
    service: name=httpd state=restarted

# ansible-playbook apache.yml --tags='conf'

特殊tags:always #無論如何都會運行

文章轉自:https://my.oschina.net/kangvcar/blog/1830155


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章