设为首页 收藏本站
查看: 1034|回复: 0

[经验分享] 【Ansible】02、Ansible深入

[复制链接]

尚未签到

发表于 2018-7-30 10:41:37 | 显示全部楼层 |阅读模式
一、简介
  YAML 语言(发音 /jml/ )的设计目标,就是方便人类读写。它实质上是一种通用的数据串行化格式。
  它的基本语法规则如下。


  •   大小写敏感
  •   使用缩进表示层级关系  # 结构
  •   缩进时不允许使用Tab键,只允许使用空格。
  •   缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  # 表示注释,从这个字符一直到行尾,都会被解析器忽略。
  YAML 支持的数据结构有三种。


  •   对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
  •   数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
  •   纯量(scalars):单个的、不可再分的值
  以下分别介绍这三种数据结构。
二、对象
  对象的一组键值对,使用冒号结构表示。
animal: pets
  Yaml 也允许另一种写法,将所有键值对写成一个行内对象。
hash: { name: Steve, foo: bar }
三、数组
  一组连词线开头的行,构成一个数组。
- Cat  
- Dog
  
- Goldfish
  数据结构的子成员是一个数组,则可以在该项下面缩进一个空格。
-  
- Cat
  
- Dog
  
- Goldfish
  数组也可以采用行内表示法。
animal: [Cat, Dog]
  
  一、YAML
  1、YAML介绍
  YAML是一个可读性高的用来表达资料序列的格式。
  YAML参考了其他多种语言,包括:XML、C语言、Python、Perl以及电子邮件格式RFC2822等。Clark Evans在2001年在首次发表了这种语言,另外Ingy dt 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
  2、YAML语法
  YAML的语法和其他高阶语言类似,并且可以简单表达清单、散列表、标量等数据结构。
  其结构(Structure)通过空格来展示,
  序列(Sequence)(同一类数据)里的项用"-"来代表,
  Map里的键值对用":"分隔。
  下面是一个示例:
name: John Smith                   # 键值对  
age: 41                 # 键值对
  
gender: Male              # 键值对
  
spouse:                         # 键值对,值又是一组键值对,使用空格来表示键的值有多项,空格不能随意缩减,否则会报错
  
    name: Jane Smith
  
    age: 37
  
    gender: Female
  
children:
  
    -   name: Jimmy Smith    # 序列,表示同一类数据
  
        age: 17
  
        gender: Male
  
    -   name: Jenny Smith
  
        age 13
  
        gender: Female
  YAML文件扩展名通常为.yml和.yaml,如example.yaml。
  3、在ansible中常用的数据类型
  1)list
  列表的所有元素均使用“-”打头
  例如:
# A list of tasty fruits  
- Apple
  
- Orange
  
- Strawberry
  
- Mango
  2)dictionary
  字典通过key与valuef进行标识
  例如:
# An employee record  
name: Example Developer
  
job: Developer
  
skill: Elite
  也可以将key:value放置于{}中进行表示
  例如:
# An employee record  
{name: Example Developer, job: Developer, skill: Elite}
  二、Ansible中使用的YAML基础元素
  1、变量
  1)变量命名
  变量名仅能由字母、数字和下划线组成,且只能以字母开头。
  2)facts
  facts是由正在通信的远程目标主机发回的信息,这些信息被保存在ansible变量中,可以直接引用。要获取指定的远程主机所支持的所有facts
  可使用如下命令进行:
  # ansible hostname -m setup
  3)register 注册器   # 很少用
  把任务的输出定义为变量,然后用于其他任务
  示例如下:
  tasks:
  - shell: /usr/bin/foo
  register: foo_result
  ignore_errors: True
  4)通过命令行传递变量
  在运行playbook的时候也可以传递一些变量供playbook使用
  使用选项:-e EXTRA_VARS, --extra-vars=EXTRA_VARS
  示例如下:
  # ansible-playbook test.yml  -e  "hosts=www  user=mageedu"
  5)通过roles传递变量
  当给一个主机应用角色的时候可以传递变量,然后在角色内使用这些变量
  示例如下:
  - hosts: webservers
  roles:
  - common
  - { role: foo_app_instance, dir: '/web/htdocs/a.com',  port: 8080 }
  2、Inventory
  ansible的主要功用在于批量主机操作,为了便捷地使用其中的部分主机,可以在inventory file中将其分组命名。默认的inventory file为/etc/ansible/hosts。
  inventory file可以有多个,且也可以通过Dynamic Inventory来动态生成。
  1)inventory文件格式
  inventory文件遵循ini文件风格,中括号中的字符为组名。可以将同一个主机同时归并到多个不同的组中;此外,当如若目标主机使用了非默认的SSH端口,还可以在主机名称之后使用冒号加端口号来标明。
  例如:
ntp.magedu.com  

  
[webservers]
  
www1.magedu.com:2222
  
www2.magedu.com
  

  
[dbservers]
  
db1.magedu.com
  
db2.magedu.com
  
db3.magedu.com
  如果主机名称遵循相似的命名模式,还可以使用列表的方式标识各主机
  例如:
[webservers]  
www[01:50].example.com
  

  
[databases]
  
db-[a:f].example.com
  2)主机变量
  可以在inventory中定义主机时为其添加主机变量以便于在playbook中引用。
  例如:
[webservers]  
www1.magedu.com http_port=80 maxRequestsPerChild=808
  
www2.magedu.com http_port=8080 maxRequestsPerChild=909
  3)组变量
  组变量是指赋予给指定组内所有主机上的在playbook中可用的变量。
  例如:
[webservers]  
www1.magedu.com
  
www2.magedu.com
  

  
[webservers:vars]
  
ntp_server=ntp.magedu.com
  
nfs_server=nfs.magedu.com
  4)组嵌套
  inventory中,组还可以包含其它的组,并且也可以向组中的主机指定变量。不过,这些变量只能在ansible-playbook中使用,而ansible命令不支持。
  例如:
[apache]  
httpd1.magedu.com
  
httpd2.magedu.com
  

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

  
[webservers:children]    # 固定格式,表示webservers组包含以下组
  
apache
  
nginx
  

  
[webservers:vars]
  
ntp_server=ntp.magedu.com
  3、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.
  所以这里可以使用另一种主机认证方式:
[root@localhost ansible]# cat hosts  
# This is the default ansible 'hosts' file.
  
#
  
# It should live in /etc/ansible/hosts
  
#
  
#   - Comments begin with the '#' character
  
#   - Blank lines are ignored
  
#   - Groups of hosts are delimited by [header] elements
  
#   - You can enter hostnames or ip addresses
  
#   - A hostname/ip can be a member of multiple groups
  

  
10.0.250.203
  
10.0.250.202 ansible_ssh_user=root ansible_ssh_pass=HY111!(123456)
  4、条件测试
  如果需要根据变量、facts或此前任务的执行结果来做为某task执行与否的前提时要用到条件测试。
  when语句
  在task后添加when子句即可使用条件测试;when语句支持Jinja2表达式语法。
  例如:
  tasks:
  - name: "shutdown Debian flavored systems"
  command: /sbin/shutdown -h now
  when: ansible_os_family == "Debian"
  when语句中还可以使用Jinja2的大多“filter”,例如要忽略此前某语句的错误并基于其结果(failed或者sucess)运行后面指定的语句,可使用类似如下形式:
  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中定义的变量。
  5、迭代
  当有需要重复性执行的任务时,可以使用迭代机制。
  其使用格式为将需要迭代的内容定义为item变量引用,并通过with_items语句来指明迭代的元素列表即可。
  例如:
- name: add several users  
  user: name={{ item }} state=present groups=wheel
  
                                    # item是固定用法,会自动重复执行他的所有值
  
  with_items:
  
     - testuser1
  
     - testuser2
  上面语句的功能等同于下面的语句:
- name: add user testuser1  
  user: name=testuser1 state=present groups=wheel
  
- name: add user testuser2
  
  user: name=testuser2 state=present groups=wheel
  事实上,with_items中可以使用元素还可为hashes,列表值也可以是字典,但引用item.KEY
  例如:
- 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
  三、ansible playbooks
  1、ansible playbookes简介
  playbook是由一个或多个“play”组成的列表。play的主要功能在于将事先归并为一组的主机装扮成事先通过ansible中的task定义好的角色。
  从根本上来讲,所谓task无非是调用ansible的一个module。将多个play组织在一个playbook中,即可以让它们联同起来按事先编排的机制同唱一台大戏。
  下面是一个简单示例:
- hosts: webnodes  
  vars:           # 定义变量,在后面可以使用{{ 变量名 }} 格式来引用
  
   - package: httpd
  
   - service: httpd
  
  remote_user: root         # 定义执行的用户
  
  tasks:           # 定义任务
  
    - name: ensure apache is at the latest version    # 自定义一个任务名称
  
    yum: name=`package` state=latest                        # 任务内容
  
    - name: ensure apache is running
  
    service: name=`service` state=started
  
  handlers:            # 处理器
  
        - name: restart apache
  
      service: name=httpd state=restarted
  2、playbook基础组件
  可以对比上面的示例来理解
  Inventory           # 主机清单,应用在哪些主机上
  Modules            # 调用哪些模块
  Ad Hoc Commands       # 运行的命令
  Playbooks
  Tasks          # 任务,即调用模块完成的某操作
  Variables        # 变量
  Templates        # 模版
  Handlers         # 处理器,由某事件触发执行的操作
  Tags           # 标签
  Roles           # 角色
  1)Hosts和Users
  playbook中的每一个play的目的都是为了让某个或某些主机以某个指定的用户身份执行任务。hosts用于指定要执行指定任务的主机,其可以是一个或多个由冒号分隔主机组;remote_user则用于指定远程主机上的执行任务的用户。如上面示例中的
  -hosts: webnodes
  remote_user: root
  不过,remote_user也可用于各task中。也可以通过指定其通过sudo的方式在远程主机上执行任务,其可用于play全局或某任务;此外,甚至可以在sudo时使用sudo_user指定sudo时切换的用户。
- hosts: webnodes  
  remote_user: mageedu
  
  tasks:
  
    - name: test connection
  
      ping:
  
      remote_user: mageedu
  
      sudo: yes
  2)任务列表和action
  play的主体部分是task list。task list中的各任务按次序逐个在hosts中指定的所有主机上执行,即在所有主机上完成第一个任务后再开始第二个。在运行自上而下某playbook时,如果中途发生错误,所有已执行任务都可能回滚,因此,在更正playbook后重新执行一次即可。
  task的目的是使用指定的参数执行模块,而在模块参数中可以使用变量。模块执行是幂等的,这意味着多次执行是安全的,因为其结果均一致。
  每个task都应该有其name,用于playbook的执行结果输出,建议其内容尽可能清晰地描述任务执行步骤。如果未提供name,则action的结果将用于输出。
  定义task的可以使用“action: module options”或“module: options”的格式,推荐使用后者以实现向后兼容。如果action一行的内容过多,也中使用在行首使用几个空白字符进行换行。
  tasks:
  - name: make sure apache is running
  service: name=httpd state=running
  在众多模块中,只有command和shell模块仅需要给定一个列表而无需使用“key=value”格式
  例如:
  tasks:
  - name: disable selinux
  command: /sbin/setenforce 0
  如果命令或脚本的退出码不为零(可能会阻止playbook继续运行),可以使用如下方式替代:
  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
  简单例子:
[root@Node6 ~]# cat xxj.yml          # 注意:yaml格式对空格很严格,不能多打和少打  
- hosts: xj,192.168.10.4
  
  remote_user: root
  
  tasks:
  
  - name: create xxj group
  
    group: name=xxj system=yes gid=808
  
  - name: create xxj user
  
    user: name=xxj system=yes createhome=no uid=808 group=808
  

  
###  这就是1个play,即1场戏;也可以有多个play,就是上面的结构再定义另一个
  

  
[root@Node6 ~]# ls -l xxj.yml
  
-rw-r--r-- 1 root root 226 Apr  3 22:20 xxj.yml
  

  
[root@Node6 ~]# ansible-playbook xxj.yml   # 使用ansible-playbook 命令执行剧本
  

  
PLAY [xj,192.168.10.4] *********************************************************
  

  
TASK [setup] *******************************************************************
  
                            # 1 play
  
ok: [192.168.10.1]
  
ok: [192.168.10.2]
  
ok: [192.168.10.4]
  

  
TASK [create xxj group] ********************************************************
  
                            # 2 play
  
changed: [192.168.10.4]
  
changed: [192.168.10.2]
  
changed: [192.168.10.1]
  

  
TASK [create xxj user] *********************************************************
  
                            # 3 play
  
changed: [192.168.10.2]
  
changed: [192.168.10.1]
  
changed: [192.168.10.4]
  

  
PLAY RECAP *********************************************************************
  
192.168.10.1               : ok=3    changed=2    unreachable=0    failed=0
  
192.168.10.2               : ok=3    changed=2    unreachable=0    failed=0
  
192.168.10.4               : ok=3    changed=2    unreachable=0    failed=0
  

  

  
[root@Node6 ~]# cat xxj.yml
  
- hosts: all
  
  remote_user: root
  
  tasks:
  
#  - name: create xxj group
  
   - group: name=xxj system=yes gid=808
  
#  - name: create xxj user
  
   - user: name=xxj system=yes createhome=no
  

  
[root@Node6 ~]# ansible-playbook xxj.yml
  

  
PLAY [all] *********************************************************************
  

  
TASK [setup] *******************************************************************
  
ok: [192.168.10.4]
  
ok: [192.168.10.1]
  
ok: [192.168.10.2]
  

  
TASK [group] *******************************************************************
  
ok: [192.168.10.4]
  
ok: [192.168.10.2]
  
ok: [192.168.10.1]
  

  
TASK [user] ********************************************************************
  
ok: [192.168.10.2]
  
ok: [192.168.10.4]
  
ok: [192.168.10.1]
  

  
PLAY RECAP *********************************************************************
  
192.168.10.1               : ok=3    changed=0    unreachable=0    failed=0
  
192.168.10.2               : ok=3    changed=0    unreachable=0    failed=0
  
192.168.10.4               : ok=3    changed=0    unreachable=0    failed=0
  3)handler
  用于当关注的资源发生变化时采取一定的操作
  “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
  即:在handlers中定义动作,在notify中调用
  例子:
[root@Node6 ~]# cat httpd.yml  
- hosts: all
  
  remote_user: root
  
  tasks:
  
  - name: install httpd
  
    yum: name=httpd
  
  - name: configuration httpd
  
    copy: src=/tmp/httpd.conf dest=/etc/httpd/conf/httpd.conf
  
  - name: start httpd service
  
    service: name=httpd enabled=true state=started
  

  
[root@Node6 ~]# ansible-playbook httpd.yml
  

  
PLAY [all] *********************************************************************
  

  
TASK [setup] *******************************************************************
  
ok: [192.168.10.2]
  
ok: [192.168.10.4]
  
ok: [192.168.10.1]
  

  
TASK [install httpd] ***********************************************************
  
ok: [192.168.10.2]
  
ok: [192.168.10.1]
  
ok: [192.168.10.4]
  

  
TASK [configuration httpd] *****************************************************
  
changed: [192.168.10.1]
  
changed: [192.168.10.4]
  
changed: [192.168.10.2]
  

  
TASK [start httpd service] *****************************************************
  
changed: [192.168.10.1]
  
changed: [192.168.10.2]
  
changed: [192.168.10.4]
  

  
PLAY RECAP *********************************************************************
  
192.168.10.1               : ok=4    changed=2    unreachable=0    failed=0
  
192.168.10.2               : ok=4    changed=2    unreachable=0    failed=0
  
192.168.10.4               : ok=4    changed=2    unreachable=0    failed=0
  

  
[root@Node6 ~]# ansible all -m shell -a "netstat -tan|grep 8080"
  
192.168.10.2 | SUCCESS | rc=0 >>
  
tcp        0      0 :::8080                     :::*                        LISTEN
  

  
192.168.10.4 | SUCCESS | rc=0 >>
  
tcp        0      0 :::8080                     :::*                        LISTEN
  

  
192.168.10.1 | SUCCESS | rc=0 >>
  
tcp        0      0 :::8080                     :::*                        LISTEN
  现在需要实现:修改httpd监听的端口后,重启httpd服务
### 将/tmp/httpd.conf文件中httpd监听的端口改为8090  

  
[root@Node6 ~]# cat httpd.yml
  
- hosts: all
  
  remote_user: root
  

  
  tasks:
  
  - name: install httpd
  
    yum: name=httpd
  

  
  - name: configuration httpd
  
    copy: src=/tmp/httpd.conf dest=/etc/httpd/conf/httpd.conf
  
    notify:
  
    - restart httpd
  

  
  - name: start httpd service
  
    service: name=httpd enabled=true state=started
  

  
  handlers:
  
  - name: restart httpd
  
    service: name=httpd state=restarted
  

  

  
[root@Node6 ~]# ansible-playbook httpd.yml
  

  
PLAY [all] *********************************************************************
  

  
TASK [setup] *******************************************************************
  
ok: [192.168.10.2]
  
ok: [192.168.10.1]
  
ok: [192.168.10.4]
  

  
TASK [install httpd] ***********************************************************
  
ok: [192.168.10.2]
  
ok: [192.168.10.4]
  
ok: [192.168.10.1]
  

  
TASK [configuration httpd] *****************************************************
  
changed: [192.168.10.1]
  
changed: [192.168.10.4]
  
changed: [192.168.10.2]
  

  
TASK [start httpd service] *****************************************************
  
ok: [192.168.10.1]
  
ok: [192.168.10.2]
  
ok: [192.168.10.4]
  

  
RUNNING HANDLER [restart httpd] ************************************************
  
changed: [192.168.10.2]
  
changed: [192.168.10.4]
  
changed: [192.168.10.1]
  

  
PLAY RECAP *********************************************************************
  
192.168.10.1               : ok=5    changed=2    unreachable=0    failed=0
  
192.168.10.2               : ok=5    changed=2    unreachable=0    failed=0
  
192.168.10.4               : ok=5    changed=2    unreachable=0    failed=0
  

  
[root@Node6 ~]# ansible all -m shell -a "netstat -tan|grep 8080"
  
192.168.10.2 | FAILED | rc=1 >>
  

  

  
192.168.10.1 | FAILED | rc=1 >>
  

  

  
192.168.10.4 | FAILED | rc=1 >>
  

  

  
[root@Node6 ~]# ansible all -m shell -a "netstat -tan|grep 8090"
  
192.168.10.4 | SUCCESS | rc=0 >>
  
tcp        0      0 :::8090                     :::*                        LISTEN
  

  
192.168.10.2 | SUCCESS | rc=0 >>
  
tcp        0      0 :::8090                     :::*                        LISTEN
  

  
192.168.10.1 | SUCCESS | rc=0 >>
  
tcp        0      0 :::8090                     :::*                        LISTEN
  4)template  模版
  定义一个模版在其中使用变量,为其赋不同的值,使得分发给各节点的文件都不同
  例如:
  准备模版文件:
[root@Node6 ~]# mv /tmp/httpd.conf /tmp/httpd.conf.j2  
                       ### 改名只是为了标识此文件是模版文件
  
[root@Node6 ~]# vim /tmp/httpd.conf.j2
  

  
[root@Node6 ~]# grep -i '^\(listen\|servername\)' /tmp/httpd.conf.j2
  
Listen `http_port`          # Listen的值使用变量代替
  
ServerName `ansible_fqdn`   # ServerName的值使用变量代替
  这个变量来自facts、主机清单文件、或playbook文件(不方便为1个变量赋每个主机不同的值)中定义的
  这里我使用在主机清单中定义该变量:
[root@Node6 ~]# tail -7 /etc/ansible/hosts  
#################################################
  

  
192.168.10.4
  

  
[xj]
  
192.168.10.1:22 http_port=801
  
192.168.10.2    http_port=802
  准备playbook文件:
[root@Node6 ~]# cat httpd.yml  
- hosts: all
  
  remote_user: root
  

  
  tasks:
  
  - name: install httpd
  
    yum: name=httpd
  

  
  - name: configuration httpd
  
#    copy: src=/tmp/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
  
                           ### 注意这里不能使用copy模块,使用copy模块 变量不会用值替换
  
    template: src=/tmp/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
  
    notify:
  
    - restart httpd
  

  
  - name: start httpd service
  
    service: name=httpd enabled=true state=started
  

  
  handlers:
  
  - name: restart httpd
  
    service: name=httpd state=restarted
  
[root@Node6 ~]# ansible-playbooke httpd.yml
  
-bash: ansible-playbooke: command not found
  
[root@Node6 ~]# ansible-playbook httpd.yml
  

  
PLAY [all] *********************************************************************
  

  
TASK [setup] *******************************************************************
  
ok: [192.168.10.2]
  
ok: [192.168.10.4]
  
ok: [192.168.10.1]
  

  
TASK [install httpd] ***********************************************************
  
ok: [192.168.10.1]
  
ok: [192.168.10.4]
  
ok: [192.168.10.2]
  

  
TASK [configuration httpd] *****************************************************
  
fatal: [192.168.10.4]: FAILED! => {"changed": false, "failed": true, "msg": "AnsibleUndefinedVariable: 'http_port' is undefined"}
  
changed: [192.168.10.1]
  
changed: [192.168.10.2]
  

  
TASK [start httpd service] *****************************************************
  
ok: [192.168.10.1]
  
ok: [192.168.10.2]
  

  
RUNNING HANDLER [restart httpd] ************************************************
  
changed: [192.168.10.2]
  
changed: [192.168.10.1]
  to retry, use: --limit @/root/httpd.retry
  

  
PLAY RECAP *********************************************************************
  
192.168.10.1               : ok=5    changed=2    unreachable=0    failed=0
  
192.168.10.2               : ok=5    changed=2    unreachable=0    failed=0
  
192.168.10.4               : ok=2    changed=0    unreachable=0    failed=1
  

  
### 10.4失败是因为在主机清单文件中没有定义http_port变量,报错,后续的配置也没继续完成
  5)Tags 标签
  tags用于让用户选择运行或跳过playbook中的部分代码。ansible具有幂等性,因此会自动跳过没有变化的部分,即便如此,有些代码为测试其确实没有发生变化的时间依然会非常地长。此时,如果确信其没有变化,就可以通过tags跳过此些代码片断。
[root@Node6 ~]# cat httpd.yml  
- hosts: xj
  
  remote_user: root
  

  
  tasks:
  
  - name: install httpd
  
    yum: name=httpd
  

  
  - name: configuration httpd
  
#    copy: src=/tmp/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
  
    template: src=/tmp/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
  
    tags:                    ### 添加一个 conf 标签
  
    - conf
  
    notify:
  
    - restart httpd
  

  
  - name: start httpd service
  
    service: name=httpd enabled=true state=started
  

  
  handlers:
  
  - name: restart httpd
  
    service: name=httpd state=restarted
  

  

  
[root@Node6 ~]# ansible-playbook httpd.yml --list-tasks   # 列出playbook中所有任务
  

  
playbook: httpd.yml
  

  
  play #1 (xj): xjTAGS: []
  
    tasks:
  
      install httpdTAGS: []
  
      configuration httpdTAGS: [conf]
  
      start httpd serviceTAGS: []
  

  
[root@Node6 ~]# ansible-playbook httpd.yml --list-tags   # 列出playbook中所有标签
  

  
playbook: httpd.yml
  

  
  play #1 (xj): xjTAGS: []
  
      TASK TAGS: [conf]
  

  

  
[root@Node6 ~]# ansible-playbook httpd.yml --tags=conf    # 只运行conf标签 任务
  

  
PLAY [xj] **********************************************************************
  

  
TASK [setup] *******************************************************************
  
ok: [192.168.10.2]
  
ok: [192.168.10.1]
  

  
TASK [configuration httpd] *****************************************************
  
changed: [192.168.10.2]
  
changed: [192.168.10.1]
  

  
RUNNING HANDLER [restart httpd] ************************************************
  
changed: [192.168.10.1]
  
changed: [192.168.10.2]
  

  
PLAY RECAP *********************************************************************
  
192.168.10.1               : ok=3    changed=2    unreachable=0    failed=0
  
192.168.10.2               : ok=3    changed=2    unreachable=0    failed=0
  执行多个tags:
[root@localhost tmp]# ansible-playbook test3.yml --tags=test2,test3  
                                                  ### 执行标签test2,test3
  

  
PLAY [all] ********************************************************************
  

  
GATHERING FACTS ***************************************************************
  
ok: [10.0.250.202]
  
ok: [10.0.250.203]
  

  
TASK: [test2] *****************************************************************
  
changed: [10.0.250.202]
  
changed: [10.0.250.203]
  

  
TASK: [test3] *****************************************************************
  
changed: [10.0.250.202]
  
changed: [10.0.250.203]
  

  
PLAY RECAP ********************************************************************
  
10.0.250.202               : ok=3    changed=2    unreachable=0    failed=0
  
10.0.250.203               : ok=3    changed=2    unreachable=0    failed=0
  

  

  
[root@localhost tmp]# ansible-playbook test3.yml --skip-tags=test2
  
                                              ### 跳过标签test2
  

  
PLAY [all] ********************************************************************
  

  
GATHERING FACTS ***************************************************************
  
ok: [10.0.250.202]
  
ok: [10.0.250.203]
  

  
TASK: [test1] *****************************************************************
  
changed: [10.0.250.202]
  
changed: [10.0.250.203]
  

  
TASK: [test3] *****************************************************************
  
changed: [10.0.250.202]
  
changed: [10.0.250.203]
  

  
PLAY RECAP ********************************************************************
  
10.0.250.202               : ok=3    changed=2    unreachable=0    failed=0
  
10.0.250.203               : ok=3    changed=2    unreachable=0    failed=0
  四、roles 角色
  1、roles 概述
  ansilbe自1.2版本引入的新特性,用于层次性、结构化地组织playbook。roles能够根据层次型结构自动装载变量文件、tasks以及handlers等。要使用roles只需要在playbook中使用include指令即可。
  简单来讲,roles就是通过分别将变量、文件、任务、模块及处理器放置于单独的目录中,并可以便捷地include它们的一种机制。
  角色一般用于基于主机构建服务的场景中,但也可以是用于构建守护进程等场景中。
  一个roles的案例如下所示:
site.yml             #主文件  
webservers.yml       #副文件
  
fooservers.yml       #副文件
  
roles/
  
   common/         #角色1
  
     files/          #角色下的文件
  
     templates/        #模版文件
  
     tasks/                    #任务文件
  
     handlers/                 #处理器文件
  
     vars/                     #变量文件
  
     meta/           #元数据文件
  

  
   webservers/       #角色2
  
     files/
  
     templates/
  
     tasks/
  
     handlers/
  
     vars/
  
     meta/
  而在playbook中,可以这样使用roles:
  ---
  - hosts: webservers
  roles:             # 直接调用各roles
  - common
  - webservers
  也可以向roles传递参数,例如:
  ---
  - hosts: webservers
  roles:
  - common
  - { role: foo_app_instance, dir: '/opt/a',  port: 5000 }
  - { role: foo_app_instance, dir: '/opt/b',  port: 5001 }
  甚至也可以条件式地使用roles,例如:
  ---
  - hosts: webservers
  roles:
  - { role: some_role, when: "ansible_os_family == 'RedHat'" }
  2、创建role的步骤
  1) 创建以roles命名的目录;  # 默认已存在
  2) 在roles目录中分别创建以各角色名称命名的目录,如webservers等;
  3) 在每个角色命名的目录中分别创建files、handlers、meta、tasks、templates和vars目录;用不到的目录可以创建为空目录,也可以不创建;
  4) 在playbook文件中,调用各角色;
  3、role内各目录中可用的文件
  tasks目录:
  至少应该包含一个名为main.yml的文件,其定义了此角色的任务列表;此文件可以使用include包含其它的位于此目录中的task文件;
  files目录:
  存放由copy或script等模块调用的文件;
  templates目录:
  template模块会自动在此目录中寻找Jinja2模板文件;
  handlers目录:
  此目录中应当包含一个main.yml文件,用于定义此角色用到的各handler;在handler中使用include包含的其它的handler文件也应该位于此目录中;
  vars目录:
  应当包含一个main.yml文件,用于定义此角色用到的变量;
  meta目录:
  应当包含一个main.yml文件,用于定义此角色的特殊设定及其依赖关系;ansible 1.3及其以后的版本才支持;
  default目录:
  为当前角色设定默认变量时使用此目录;应当包含一个main.yml文件;
  
  实例:
  1、环境
  192.168.10.1  安装 httpd + ntpdate
  192.168.10.2  安装 httpd + ntpdate + mysql
  2、步骤
  1)创建各角色和其相关目录
[root@localhost ~]# cd /etc/ansible/  
[root@localhost ansible]# ls
  
ansible.cfg  hosts  roles
  
[root@localhost ansible]# cd roles/
  
[root@localhost roles]# mkdir -pv {httpd,mysql}/{tasks,files,templates,meta,handlers,vars}
  
mkdir: created directory `httpd'
  
mkdir: created directory `httpd/tasks'
  
mkdir: created directory `httpd/files'
  
mkdir: created directory `httpd/templates'
  
mkdir: created directory `httpd/meta'
  
mkdir: created directory `httpd/handlers'
  
mkdir: created directory `httpd/vars'
  
mkdir: created directory `mysql'
  
mkdir: created directory `mysql/tasks'
  
mkdir: created directory `mysql/files'
  
mkdir: created directory `mysql/templates'
  
mkdir: created directory `mysql/meta'
  
mkdir: created directory `mysql/handlers'
  
mkdir: created directory `mysql/vars'
  2)准备各文件
  file目录准备需要用到的文件:
[root@localhost roles]# ls  
httpd  mysql
  
[root@localhost roles]# cd httpd/
  
[root@localhost httpd]# ls
  
files  handlers  meta  tasks  templates  vars
  
[root@localhost httpd]# cp /etc/httpd/conf/httpd.conf.rpmsave  files/httpd.conf
  
[root@localhost httpd]# ls files/
  
httpd.conf
  tasks目录定义任务文件:
[root@localhost httpd]# cat tasks/main.yml  
- name: install httpd package
  
  yum: name=httpd
  
- name: install configuration file
  
  copy: src=httpd.conf dest=/etc/httpd/conf/httpd.conf
  
  tags:
  
  - conf
  
  notify:
  
  - restart httpd
  
- name: start httpd
  
  service: name=httpd state=started
  handlers目录文件:
[root@localhost httpd]# cat handlers/main.yml  
- name: restart httpd
  
  service: name=httpd state=restarted
  创建主yml文件:    # 要在roles目录外
[root@localhost httpd]# cd ..  
[root@localhost roles]# cd ..
  
[root@localhost ansible]# vi site.yml
  

  
[root@localhost ansible]# cat site.yml
  
- hosts: 10.0.250.203
  
  remote_user: root
  
  roles:
  
  - httpd
[root@localhost ansible]# ansible-playbook site.yml  

  
PLAY [10.0.250.203] ***********************************************************
  

  
GATHERING FACTS ***************************************************************
  
ok: [10.0.250.203]
  

  
TASK: [httpd | install httpd package] *****************************************
  
changed: [10.0.250.203]
  

  
TASK: [httpd | install configuration file] ************************************
  
changed: [10.0.250.203]
  

  
TASK: [httpd | start httpd] ***************************************************
  
changed: [10.0.250.203]
  

  
NOTIFIED: [httpd | restart httpd] *********************************************
  
changed: [10.0.250.203]
  

  
PLAY RECAP ********************************************************************
  
10.0.250.203               : ok=5    changed=4    unreachable=0    failed=0
  第一个节点已经部署完毕,现在来部署第二个节点:  # 应该直接在一个site.yml文件中
[root@localhost ansible]# cd roles/  
httpd/ mysql/
  
[root@localhost ansible]# cd roles/mysql/
  
[root@localhost mysql]# ls
  
files  handlers  meta  tasks  templates  vars
  
[root@localhost mysql]# cp /etc/my.cnf files/
  
[root@localhost mysql]# vi tasks/main.yml
  

  
[root@localhost mysql]# cat tasks/main.yml
  
- name: install mysql-server package
  
  yum: name=mysql-server
  
- name: install configuration file
  
  copy: src=my.cnf dest=/etc/my.cnf
  
  tags:
  
  - mycof
  
  notify:
  
  - restart myslqd
  
- name: start mysqld service
  
  service: name=mysqld state=started
  

  
  [root@localhost mysql]# cat handlers/main.yml
  
- name: restart mysqld
  
  service: name=mysqld state=restarted
  

  
  [root@localhost mysql]# cd ../..
  
[root@localhost ansible]# ls
  
ansible.cfg  hosts  roles  site.yml
  
[root@localhost ansible]# vi site.yml
  

  

  
[root@localhost ansible]# cat site.yml
  
- hosts: 10.0.250.203
  
  remote_user: root
  
  roles:
  
  - httpd
  

  
- hosts: 10.0.250.202
  
  remote_user: root
  
  roles:
  
  - httpd
  
  - mysql
  执行:
[root@localhost ansible]# ansible-playbook site.yml  

  
PLAY [10.0.250.203] ***********************************************************
  

  
GATHERING FACTS ***************************************************************
  
ok: [10.0.250.203]
  

  
TASK: [httpd | install httpd package] *****************************************
  
ok: [10.0.250.203]
  

  
TASK: [httpd | install configuration file] ************************************
  
ok: [10.0.250.203]
  

  
TASK: [httpd | start httpd] ***************************************************
  
ok: [10.0.250.203]
  

  
PLAY [10.0.250.202] ***********************************************************
  

  
GATHERING FACTS ***************************************************************
  
ok: [10.0.250.202]
  

  
TASK: [httpd | install httpd package] *****************************************
  
changed: [10.0.250.202]
  

  
TASK: [httpd | install configuration file] ************************************
  
changed: [10.0.250.202]
  

  
TASK: [httpd | start httpd] ***************************************************
  
changed: [10.0.250.202]
  

  
TASK: [mysql | install mysql-server package] **********************************
  
changed: [10.0.250.202]
  

  
TASK: [mysql | start mysqld service] ******************************************
  
failed: [10.0.250.202] => {"failed": true}
  
msg: ERROR: 1004  Can't create file '/tmp/#sql2941_1_0.frm' (errno: 13)
  
160122 12:27:40 [ERROR] Aborting
  

  
160122 12:27:40 [Note] /usr/libexec/mysqld: Shutdown complete
  

  

  

  
FATAL: all hosts have already failed -- aborting
  

  
PLAY RECAP ********************************************************************
  
           to retry, use: --limit @/root/site.retry
  

  
10.0.250.202               : ok=5    changed=4    unreachable=0    failed=1
  
10.0.250.203               : ok=4    changed=0    unreachable=0    failed=0
  注意:这里有一个报错,是因为在/etc/ansible/roles/mysql/tasks/main.yml中有语法错误,上面贴出来的已经改过了。
  修正后再运行一次:
[root@localhost ansible]# ansible-playbook site.yml  

  
PLAY [10.0.250.203] ***********************************************************
  

  
GATHERING FACTS ***************************************************************
  
ok: [10.0.250.203]
  

  
TASK: [httpd | install httpd package] *****************************************
  
ok: [10.0.250.203]
  

  
TASK: [httpd | install configuration file] ************************************
  
ok: [10.0.250.203]
  

  
TASK: [httpd | start httpd] ***************************************************
  
ok: [10.0.250.203]
  

  
PLAY [10.0.250.202] ***********************************************************
  

  
GATHERING FACTS ***************************************************************
  
ok: [10.0.250.202]
  

  
TASK: [httpd | install httpd package] *****************************************
  
ok: [10.0.250.202]
  

  
TASK: [httpd | install configuration file] ************************************
  
ok: [10.0.250.202]
  

  
TASK: [httpd | start httpd] ***************************************************
  
ok: [10.0.250.202]
  

  
TASK: [mysql | install mysql-server package] **********************************
  
ok: [10.0.250.202]
  

  
TASK: [mysql | install configuration file] ************************************
  
ok: [10.0.250.202]
  

  
TASK: [mysql | start mysqld service] ******************************************
  
ok: [10.0.250.202]
  

  
PLAY RECAP ********************************************************************
  
10.0.250.202               : ok=7    changed=0    unreachable=0    failed=0
  
10.0.250.203               : ok=4    changed=0    unreachable=0    failed=0
  可以看出roles方便多次调用相同的步骤

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-543471-1-1.html 上篇帖子: 【Ansible】01、Ansible基础 下篇帖子: ansible详解
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表