Ansible Playbook

1.YAML介绍

YAML是一个可读性高的用来表达资料序列的格式,YAML参考了其它多种语言

  • YAML的可读性好
  • YAML和脚本语言的交互性好
  • YAML有一个一致的信息模型
  • YAML易于实现
  • YAML可以基于流来处理
  • YAML表达能力强,扩展性好

2.YAML语法

YAML的语法和其它高阶语言类似,并且可以简单表达清单,散列表,标量等数据结构,其结构通过空格来展示,序列里的项用"-" 来代表,Map里的键值对用“:”分隔。

2.1 list

列表的所有元素均使用“-”打头,例如:

- apple
- Orange
- Strawberry

2.2 字典 dictionary

字典通过key与valuef进行标识。例如:

name: tom
job: Developer

也可以将key:value放置于{}中进行表示

{name: tom,job: Developer, skill: Elite}

3.Ansible基础元素

3.1 变量

  • 主机变量

可以在inventory中定义主机时为其添加主机变量以便于在playbook中使用。

[webservers]
www1.deeam.com http_port=80 maxRequestsPerChild=808
www2.deeam.com http_port=8080 maxRequestsPerChild=909
  • 组变量

组变量是指赋予给指定组内所有主机上的在playbook中可用的变量

[webservers]
www1.deeam.com
www2.deeam.com

[webservers:vars]           :vars固定格式;变量表示对webserver组中所有主机都生效
ntp_server=ntp.deeam.com
nfs_server=nfs.deeam.com
  • 组嵌套

inventory中,组可以包含其它的组,并且也可以向组中的主机指定变量,不过,这些变量只能在ansible-playbook中使用,而ansible不支持。

[apache]
httpd1.deeam.com
httpd2.deeam.com

[nginx]
ngx1.deeam.com
ngx2.deeam.com

[webservers:children]   children表示子组;webservers包括所有apache组和nignx组中的所有主机
apache
nginx

[webservers:vars]
ntp_server=ntp.deeam.com
  • inventory参数

ansible基于ssh连接inventory中指定的远程主机时,还可以通过参数指定其交互方式;这些参数如下所示:

ansible_ssh_host
  The name of the host to connect to, if different from the alias you wish to give to it.
ansible_ssh_port
  The ssh port number, if not 22
ansible_ssh_user
  The default ssh user name to use.
ansible_ssh_pass
  The ssh password to use (this is insecure, we strongly recommend using --ask-pass or SSH keys)
ansible_sudo_pass
  The sudo password to use (this is insecure, we strongly recommend using --ask-sudo-pass)
ansible_connection
  Connection type of the host. Candidates are local, ssh or paramiko.  The default is paramiko before Ansible 1.2, and 'smart' afterwards which detects whether usage of 'ssh' would be feasible based on whether ControlPersist is supported.
ansible_ssh_private_key_file
  Private key file used by ssh.  Useful if using multiple keys and you don't want to use SSH agent.
ansible_shell_type
  The shell type of the target system. By default commands are formatted using 'sh'-style syntax by default. Setting this to 'csh' or 'fish' will cause commands executed on target systems to follow those shell's syntax instead.
ansible_python_interpreter
  The target host python path. This is useful for systems with more
  than one Python or not located at "/usr/bin/python" such as *BSD, or where /usr/bin/python
  is not a 2.X series Python.  We do not use the "/usr/bin/env" mechanism as that requires the remote user's
  path to be set right and also assumes the "python" executable is named python, where the executable might
  be named something like "python26".
ansible\_*\_interpreter
  Works for anything such as ruby or perl and works just like ansible_python_interpreter.
  This replaces shebang of modules which will run on that host.

4. ansible-playbook

playbook是由一个或多个“play”组成的列表。play的主要功能在于将事先归并为一组的主机装扮成事先通过ansible中的task定义好的角色。从根本上来讲,所谓task无非是调用ansible的一个module。将多个play组织在一个playbook中,即可以让它们联同起来按事先编排的机制同唱一台大戏

- hosts: webnodes               此剧本对此webnodes组生效
  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

4.1 palybook中的基础组件

  • 组成结构

    Inventory
    Modules
    Ad Hoc Commands
    Playbooks
    Tasks: 任务
    Variables:变量
    Templates:模板
    Handlers:处理器;由某事件触发并执行的操作
    Roles:角色

  • 基本结构

    • hosts: websrvs
      remote_user:
      tasks:

      • name: job_name
        Modulename:
    • hosts: dbsrvs
      remote_user:
      tasks:

      • name: job_name
        Modulename:
  • (1)Hosts和Users

aybook中的每一个play的目的都是为了让某个或某些主机以某个指定的用户身份执行任务。hosts用于指定要执行指定任务的主机,其可以是一个或多个由冒号分隔主机组;remote_user则用于指定远程主机上的执行任务的用户

- hosts: webnodes
  remote_user: root

不过,remote_user也可用于各task中。也可以通过指定其通过sudo的方式在远程主机上执行任务,其可用于play全局或某任务;此外,甚至可以在sudo时使用sudo_user指定sudo时切换的用户

- hosts: webnodes
  remote_user: deeam
  tasks:
  - name: test connection
	ping:
	remote_user: deeam
	sudo: yes
  • (2)任务列表和action

play的主体部分是task list。task list中的各任务按次序逐个在hosts中指定的所有主机上执行,即在所有主机上完成第一个任务后再开始第二个。在运行自下而下某playbook时,如果中途发生错误,所有已执行任务都将回滚,因此,在更正playbook后重新执行一次即可

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

	在众多模块中,只有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

简单实列:

  • 安装httpd

    • hosts: all
      remote_user: root
      tasks:
      • name: install httpd
        yum: name=httpd state=installed
      • name: copy httpd.conf to all
        copy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/ 在本机提供所需的配置文件
      • name: started httpd
        service: name=httpd state=started enabled=on
  • (3)handlers

用于当关注的资源发生变化时采取一定的操作;“notify”这个action可用于在每个play的最后被触发,这样可以避免多次有改变发生时每次都执行指定的操作,取而代之,仅在所有的变化发生完成后一次性地执行指定操作。在notify中列出的操作称为handler,也即notify中调用handler中定义的操作

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

handler是task列表,这些task与前述的task并没有本质上的不同

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

简单实列:

1.当本机的配置文件发生改变就会触发notify
- hosts: all
  remote_user: root
  tasks:
  - name: install httpd
    yum: name=httpd state=installed
  - name: copy httpd.conf to all
    copy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/
    notify:             一旦文件发生改变;我们就触发 - restart httpd            
    - restart httpd
  - name: started httpd
    service: name=httpd state=started enabled=on
  handlers:                     和tasks用一级别
  - name: restart httpd         
    service: name=httpd state=restarted
    
2.变量的实列
- hosts: all
remote_user: root
vars:
- packge: pcre-devel,zlib-devel
tasks:
- name: install
  yum: name={{ packge }}    使用{{ vars_name }}进行调用

3.也可以在主机清单中定义变量
[root@ansible-server ~]# cat /etc/ansible/hosts 
[webserver]
192.168.100.103 testvar="/tmp/"
[dbserver]
192.168.100.104

- hosts: 192.168.100.103
  remote_user: root
  tasks:
  - name: copy file
    copy: src=/etc/fstab dest={{ testvar }}

4.2 条件表达式

when ansible_vars_name == " value" 当满足条件时才执行任务

  - hosts: all
  remote_user: root
  tasks:
  - name: copy node3 index.html
    copy: src=/root/node1/index.html dest=/var/www/html/
    when: ansible_nodename == "centos7.node3.cn"
  - name: copy node4 index.html
    copy: src=/root/node2/index.html dest=/var/www/html/
    when: ansible_nodename == "centos7.node4.cn"

4.3 迭代(循环)

当有需要重复执行的任务时,可以使用迭代机制,其使用格式为将需要迭代的内容定义为item变量引用,并通过with_items语句来指明迭代的元素列表即可

1.迭代一个
- hosts: 192.168.100.103
  remote_user: root
  tasks:
  - name: add several users
    user: name={{ item }} groups=wheel  迭代的内容定义为item变量引用
    with_items:                         通过with_items语句来指明迭代的元素列表
       - testuser1
       - testuser2

2.迭代多个
with_items中的列表值也可以是字典,但引用时要使用item.KEY

- hosts: 192.168.100.103
  remote_user: root
  tasks:
  - name: add several users
    user: name={{ item.user }} groups={{ item.group }}  用
    with_items:                         
       - { name: 'testuser1', groups: 'wheel' }
       - { name: 'testuser2', groups: 'root' }    

4.4 使用template模块

可以在主机清单中设置指定的变量值;并在配置文件中 通过 {{ vars_name }};进行调用

1.设置主机清单
[root@ansible-server ~]# cat /etc/ansible/hosts 
[webserver]
192.168.100.103 http_port=80
[dbserver]
192.168.100.104 http_port=8080




2.修改配置文件模板
[root@ansible-server ~]# cat -n /etc/httpd/conf/httpd.conf  | grep "http_port|ansible"
42	Listen {{ http_port }}
95	ServerName {{ ansible_nodename }}:80

3.编写安装httpd的playbook
- hosts: all
  remote_user: root
  tasks:
  - name: install httpd
    yum: name=httpd state=installed
  - name: copy httpd.conf to all
    template: src=/etc/httpd/conf/httpd.conf dest=/etc/httpd/conf/
    notify:
    - restart httpd
  - name: started httpd
    service: name=httpd state=started enabled=on
  handlers:
  - name: restart httpd
    service: name=httpd state=restarted
    
4.验证结构
192.168.100.103 监听在80  192.168.100.103 监听在8080  

4.5 tag

标签作用:在每个task任务的name下,为其设置一个tag标签值,在ansible-playbook命令执行时,可以执行单独执行此任务,或者跳过此任务;

语法:ansible-playbook /root/httpd.yaml -t 标签名 ##单独运行此任务
ansible-playbook /root/httpd.yaml --skip-tags=标签名 ##跳过运行此任务

1.编辑
  - hosts: all
  remote_user: root
  tasks:
  - name: install httpd
    yum: name=httpd state=installed
  - name: copy httpd.conf to all
    copy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/ 
    notify:
    - restart httpd
    tags: copy          为此任务打上标签名字是 copy
  - name: started httpd
    service: name=httpd state=started enabled=on
  handlers:
  - name: restart httpd
    service: name=httpd state=restarted

2.执行
[root@ansible-server ~]# ansible-playbook httpd.yml -t copy
指定标签名 只会执行此copy任务
原文地址:https://www.cnblogs.com/precipitation/p/15098162.html