ansible之playbook常用模块

template

set_fact

pause

wait_for

assemble

add_host

group_by

get_url

debug

fail

template模块是Ansible中最常用的模块之一。它可以让你设计一个框架式的配置文件,如何把Anisble需要的值插入到合适的位置。其中Jinja2模板尤为复杂,其中可以包含条件、循环、宏

tasks:

- name: copy config file to remote server

template: src=named.conf.j2 dest=/etc/named.conf
named.conf.j2

# {{ ansible_managed }}                                        

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 %}

};

set_fact模块可以让你在远程受管机器上执行脚本的过程中来计算我们需要的值,这些值可以被用在模板或者变量中。这些值有点类似setup模块中的参数,只不过setup模块是以单台主机为单位的。

- 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.j2 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.j2

[mysqld]

datadir=/var/lib/mysql

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

symbolic-links=0

innodb_buffer_pool_size = {{ innodb_buffer_pool_size_mb|default(128) }}M

[mysqld_safe]

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

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



# Example setting host facts using key=value pairs

- set_fact: one_fact="something" other_fact="{{ local_var * 2 }}"

# Example setting host facts using complex arguments

- set_fact:

     one_fact: something

     other_fact: "{{ local_var * 2 }}"

# As of 1.8, Ansible will convert boolean strings ('true', 'false', 'yes', 'no')

# to proper boolean values when using the key=value syntax, however it is still

# recommended that booleans be set using the complex argument style:

- set_fact:

    one_fact: true

    other_fact: false

暂停模块可以让我们在playbook中暂停一段时间,可以指定一个时间段,或者提示用户继续。在命令行模式中,这没什么用,但是在playbook中,这很有用处。

暂停模块通常被用在当我们需要用户来提供一个确认来继续的时候,或者在一个特殊的时间点手动确认。比如你更新一个web应用程序之后,你需要用户在接受用户的连接之前,手工确认一切Ok。这也可以用来提示用户一些可能出现的问题,并提供选项继续。Ansible会打印出服务器的名字,要求用户确认之后继续。如果在目标选项中设置了串行参数,Ansible会询问组里面的每一个主机。这种方式可以让用户在部署的时候,灵活的控制整个节奏,并监控整个交互过程

- name: wait on user input

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

- name: timed wait

  pause: seconds=30

wait_for模块用来检测一个tcp端口是否准备好接收远程连接,这是由远程主机来完成的。如果你只指定了端口,或者主机参数被设置为localhost,它会尝试连接远程受管主机。你可以用local_action参数来指定从控制机器来运行命令,并使用ansible_hostname做为主机参数来连接远程受管主机。这个模块在后台运行某些程序,或者启动某些进程需要一些时间的时候特别有用。

- hosts: webapps

  tasks:

     - name: Install Tomcat

       yum: name=tomcat6 state=installed

     - name: Start Tomcat

       service: name=tomcat6 state=started

    - name: Wait for Tomcat to start

      wait_for: port=8080 state=started

assemble组装模块把多个受管主机的文件合并成一个文件,当配置文件不允许包含的时候,这非常有用,特别是在设置root用户的authorized_keys文件的时候。

- 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

add_host 添加主机模块是playbook中一个强大的模块,它可以让你动态的添加受管主机到一个play中。我们可以使用uri模块从CMDB中获得主机信息然后添加他们。它还可以将主机加到组里面,如果组不存在的话还会自动创建它。这个模块仅需要主机名和组名2个参数,跟主机库存清单的配置一样,我们还可以添加扩展的参数像ansible_ssh_user , ansible_ssh_port等等。

group_by 模块可以让我们根据主机的真实特性来进行分组,真实特性可以通过add_fact来实现(前面已经介绍过set_fact)。group_by模块只接受一个参数,key,同样组名的机器就被分到一个组里面。如果我们在这里使用变量,我们就可以把同一个操作系统类型、同一个拓扑结构的、或者其他我们希望的拥有同样特性的主机分成一组,组可以在子play中、模板中的目标选项被使用。

---

- name: Create operating system group

  hosts: all

  tasks:

    - group_by: key=os_{{ ansible_distribution }}

    - 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

get_url模块

- name: download foo.conf

  get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf mode=0440

- name: download file with sha256 check

  get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf sha256sum=b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c

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

- name: Display all variables/facts known for a host

  debug: var=hostvars[inventory_hostname]

fail模块

# Example playbook using fail and when together

- fail: msg="The system may not be provisioned according to the CMDB status."

  when: cmdb_status != "to-be-staged"

ansible之playbook常用模块
http://www.jcwit.com/article/216/
作者
Carlos
发布于
2018年7月24日
许可协议