ansible 常用模塊

playbook的模塊與在ansible命令行下使用的模塊有一些不同。這主要是因爲在playbook中會使用到一些facts變量和一些通過setup模塊從遠程主機上獲取到的變量。有些模塊沒法在命令行下運行,就是因爲它們需要這些變量。而且即使那些可以在命令行下工作的模塊也可以通過playbook的模塊獲取一些更高級的功能。

1、template

在實際應用中,我們的配置文件有些地方可能會根據遠程主機的配置的不同而有稍許的不同,template可以使用變量來接收遠程主機上setup收集到的facts信息,針對不同配置的主機,定製配置文件。用法大致與copy模塊相同。

常用參數:

backup:如果原目標文件存在,則先備份目標文件

dest:目標文件路徑

force:是否強制覆蓋,默認爲yes

group:目標文件屬組

mode:目標文件的權限

owner:目標文件屬主

src:源模板文件路徑

validate:在複製之前通過命令驗證目標文件,如果驗證通過則複製

官方簡單示例:

  • template: src=/mytemplates/foo.j2 dest=/etc/file.conf owner=bin group=wheel mode=0644
  • template: src=/mytemplates/foo.j2 dest=/etc/file.conf owner=bin group=wheel mode="u=rw,g=r,o=r"
  • template: src=/mine/sudoers dest=/etc/sudoers validate='visudo -cf %s'
    named.conf配置文件的jinja2模板示例:
options {
listen-on port 53 {
127.0.0.1;
{% for ip in ansible_all_ipv4_addresses %}
{{ ip }};
{% endfor %}
};
listen-on-v6 port 53 { ::1; };
directory "/var/named";
dump-file "/var/named/data/cache_dump.db";
statistics-file "/var/named/data/named_stats.txt";
memstatistics-file "/var/named/data/named_mem_stats.txt";
};
zone "." IN {
type hint;
file "named.ca";
};
include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";
{# Variables for zone config #}
{% if 'authorativenames' in group_names %}
{% set zone_type = 'master' %}
{% set zone_dir = 'data' %}
{% else %}
{% set zone_type = 'slave' %}
{% set zone_dir = 'slaves' %}
{% endif %}
zone "internal.example.com" IN {
type {{ zone_type }};
file "{{ zone_dir }}/internal.example.com";
{% if 'authorativenames' not in group_names %}
masters { 192.168.2.2; };
{% endif %}
};
playbook的引用該模板配置文件的方法示例:
- name: Setup BIND
  host: allnames
  tasks:
    - name: configure BIND
      template: src=templates/named.conf.j2 dest=/etc/named.conf owner=root group=named mode=0640

2、set_fact

set_fact模塊可以自定義facts,這些自定義的facts可以通過template或者變量的方式在playbook中使用。如果你想要獲取一個進程使用的內存的百分比,則必須通過set_fact來進行計算之後得出其值,並將其值在playbook中引用。

下面是一個配置mysql innodb buffer size的示例:

  • name: Configure MySQL
    hosts: mysqlservers
    tasks:
    • name: install MySql
      yum: name=mysql-server state=installed
    • name: Calculate InnoDB buffer pool size
      set_fact: innodb_buffer_pool_size_mb="{{ ansible_memtotal_mb / 2 }}"
    • name: Configure MySQL
      template: src=templates/my.cnf dest=/etc/my.cnf owner=root group=root mode=0644
      notify: restart mysql
    • name: Start MySQL
      service: name=mysqld state=started enabled=yes
      handlers:
    • name: restart mysql
      service: name=mysqld state=restarted

my.cnf的配置示例:

{{ ansible_managed }}

[mysqld]

datadir=/var/lib/mysql

socket=/var/lib/mysql/mysql.sock

Disabling symbolic-links is recommended to prevent assorted

security risks

symbolic-links=0

Configure the buffer pool

innodb_buffer_pool_size = {{ innodb_buffer_pool_size_mb|int }}M

[mysqld_safe]

log-error=/var/log/mysqld.log

pid-file=/var/run/mysqld/mysqld.pid

3、pause

在playbook執行的過程中暫停一定時間或者提示用戶進行某些操作

常用參數:

minutes:暫停多少分鐘

seconds:暫停多少秒

prompt:打印一串信息提示用戶操作

示例:

  • name: wait on user input

    pause: prompt="Warning! Detected slight issue. ENTER to continue CTRL-C a to quit"

  • name: timed wait

    pause: seconds=30

4、wait_for

在playbook的執行過程中,等待某些操作完成以後再進行後續操作

常用參數:

connect_timeout:在下一個任務執行之前等待連接的超時時間

delay:等待一個端口或者文件或者連接到指定的狀態時,默認超時時間爲300秒,在這等待的300s的時間裏,wait_for模塊會一直輪詢指定的對象是否到達指定的狀態,delay即爲多長時間輪詢一次狀態。

host:wait_for模塊等待的主機的地址,默認爲127.0.0.1

port:wait_for模塊待待的主機的端口

path:文件路徑,只有當這個文件存在時,下一任務纔開始執行,即等待該文件創建完成

state:等待的狀態,即等待的文件或端口或者連接狀態達到指定的狀態時,下一個任務開始執行。當等的對象爲端口時,狀態有started,stoped,即端口已經監聽或者端口已經關閉;當等待的對象爲文件時,狀態有present或者started,absent,即文件已創建或者刪除;當等待的對象爲一個連接時,狀態有drained,即連接已建立。默認爲started

timeout:wait_for的等待的超時時間,默認爲300秒

示例:

  • wait_for: port=8080 state=started #等待8080端口已正常監聽,纔開始下一個任務,直到超時

  • wait_for: port=8000 delay=10 #等待8000端口正常監聽,每隔10s檢查一次,直至等待超時

  • wait_for: host=0.0.0.0 port=8000 delay=10 state=drained #等待8000端口直至有連接建立

  • wait_for: host=0.0.0.0 port=8000 state=drained exclude_hosts=10.2.1.2,10.2.1.3 #等待8000端口有連接建立,如果連接來自10.2.1.2或者10.2.1.3,則忽略。

  • wait_for: path=/tmp/foo #等待/tmp/foo文件已創建

  • wait_for: path=/tmp/foo search_regex=completed #等待/tmp/foo文件已創建,而且該文件中需要包含completed字符串

  • wait_for: path=/var/lock/file.lock state=absent #等待/var/lock/file.lock被刪除

  • wait_for: path=/proc/3466/status state=absent #等待指定的進程被銷燬

  • local_action: wait_for port=22 host="{{ ansible_ssh_host | default(inventory_hostname) }}" search_regex=OpenSSH delay=10 #等待openssh啓動,10s檢查一次

5、assemble

用於組裝文件,即將多個零散的文件,合併一個大文件

常用參數:

src:原文件(即零散文件)的路徑

dest:合併後的大文件路徑

group:合併後的大文件的屬組

owner:合併後的大文件的屬主

mode:合併後的大文件的權限

validate:與template的validate相同,指定命令驗證文件

ignore_hidden:組裝時,是否忽略隱藏文件,默認爲no,該參數在2.0版本中新增

示例:

  • hosts: all

    tasks:

    • name: Make a Directory in /opt

      file: path=/opt/sshkeys state=directory owner=root group=root mode=0700

    • name: Copy SSH keys over

      copy: src=keys/{{ item }}.pub dest=/opt/sshkeys/{{ item }}.pub owner=root group=root mode=0600

      with_items:

      • dan

      • kate

      • mal
    • name: Make the root users SSH config directory

      file: path=/root/.ssh state=directory owner=root group=root mode=0700

    • name: Build the authorized_keys file

      assemble: src=/opt/sshkeys/ dest=/root/.ssh/authorized_keys owner=root group=root mode=0700 #將/opt/sshkeys目錄裏所有的文件合併到/root/.ssh/authorized_keys一個文件中

6、add_host

在playbook執行的過程中,動態的添加主機到指定的主機組中

常用參數:

groups:添加主機至指定的組

name:要添加的主機名或IP地址

示例:

  • name: add a host to group webservers

    hosts: webservers

    tasks:

    • add_host name={{ ip_from_ec2 }} group=webservers foo=42 #添加主機到webservers組中,主機的變量foo的值爲42

7、group_by

在playbook執行的過程中,動態的創建主機組

示例:

  • name: Create operating system group

    hosts: all

    tasks:

    • groupby: key=os{{ ansible_distribution }} #在playbook中設置一個新的主機組
  • name: Run on CentOS hosts only

    hosts: os_CentOS

    tasks:

    • name: Install Apache

      yum: name=httpd state=latest

  • name: Run on Ubuntu hosts only

    hosts: os_Ubuntu

    tasks:

    • name: Install Apache

      apt: pkg=apache2 state=latest

8、debug

調試模塊,用於在調試中輸出信息

常用參數:

msg:調試輸出的消息

var:將某個任務執行的輸出作爲變量傳遞給debug模塊,debug會直接將其打印輸出

verbosity:debug的級別

示例:

Example that prints the loopback address and gateway for each host- debug: msg="System {{ inventory_hostname }} has uuid {{ ansible_product_uuid }}"

  • debug: msg="System {{ inventory_hostname }} has gateway {{ ansible_default_ipv4.gateway }}"
    when: ansible_default_ipv4.gateway is defined

  • shell: /usr/bin/uptime
    register: result

  • debug: var=result verbosity=2 #直接將上一條指令的結果作爲變量傳遞給var,由debug打印出result的值

  • name: Display all variables/facts known for a host
    debug: var=hostvars[inventory_hostname] verbosity=4

9、fail

用於終止當前playbook的執行,通常與條件語句組合使用,當滿足條件時,終止當前play的運行。可以直接由failed_when取代。

選項只有一個:

msg:終止前打印出信息

示例:

  • fail: msg="The system may not be provisioned according to the CMDB status."
    when: cmdb_status != "to-be-staged"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章