ansible剧本

一、ansible playbook

1、概述

1、什么是playbook

  • 一系列ad-hoc的集合,剧本可以同时执行多个任务

  • 定义主机组执行一系列模块的操作

  • 里面可以定义多个任务,多个ad-hoc,比较的方便

  • 剧本发生了错误,会立刻停止执行,修改后,继续执行,之前执行过的任务,不会有影响

2、yaml语言

playbook里面都是yaml语言定义的

  • yaml特性

    • 很高的可读性

    • 极强的扩展性

    • 较强的易用性

  • 严格的要求

    • 严格区分大小写

    • 使用空格来作为缩进项,不能使用tab,相同层级的元素要对齐

    • 使用-表示列表,key:value 的键值对表示字典

3、剧本执行流程

  • 从上往下执行

  • 如果执行了一半出现了错误,就会终止,下次执行的时候,就会从错误的地方继续执行

  • 如果有多个主机node1,node2,node1剧本出现了错误,不会影响到node2主机,仍然会继续执行

2、playbook的组成部分

1、基础部分

  • hosts:定义被控主机列表

  • variables: 定义调用的变量

  • tasks: 指定被执行的任务,是一个任务列表

  • templates:模块,内部嵌套,对playbook中的变量进行渲染成具体的值

  • hadnlers和notify:配合使用,用于任务配置触发条件(触发特定条件,handlers是一组特殊任务,notify是监听器)

  • tags: 是任务标签,可以通过标签选择执行特定的任务

[devops@server ansible]$ cat test1.yml 
- name: test play1
  hosts: node1  # 定义被控节点
  vars:  # 定义变量
    use_name: bob
    age: 123
  tags: u1   # 定义标签
  tasks: # 定义一系列任务,因此后面使用模块时,前面都需要有-表示列表
    - name: use msg
      debug:  # 使用模块
        msg: "{{use_name}}"  # 模块的参数
    - name: use var
      debug:
        var: age

2、handlers字段

是ansible一个特殊的任务与tasks层级一样

  • 当剧本中所有的tasks任务执行完成后,最后才会执行这个handlers定义的任务

  • 且监听的模块必须是chaged的状态才行

[devops@server ansible]$ cat test3.yml 
- hosts: node1
  tasks:
    - shell: "touch /opt/123.txt"  
      notify: get_status  # 监听的任务
    - shell: "ls /opt"
  handlers: # handlers定义的任务
    - name: get_status  
      shell: "ls /opt"

[devops@server ansible]$ ansible-playbook test3.yml 

PLAY [node1]  在node1 上面执行 ***************************************************************************

TASK [Gathering Facts] 收集事实变量,默认是开启*****************************************************************
ok: [node1]

TASK [shell]  第一个任务 ***************************************************************************
changed: [node1]  # 都是chaged状态

TASK [shell]  第二个任务 ***************************************************************************
changed: [node1]

RUNNING HANDLER [get_status] 执行这个handlers任务,因为这个监听的是chaged状态 ***********************************************************
changed: [node1]

PLAY RECAP *****************************************************************************
node1                      : ok=4    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


思考一个问题,如果当剧本中发生了错误,handlers是一个什么样的情况呢?

  • 会立刻停止执行,不会执行handlers任务
[devops@server ansible]$ cat test3.yml 
- hosts: node1
  tasks:
    - shell: "touch /opt/123.txt"
      notify: get_status  # 状态是chaged
    - shell: "ls /op"  # 出现错误,会立刻停止执行
  handlers:  # 会触发这个handlers任务,但是了,因为前面出现了错误,就会直接终止
    - name: get_status
      shell: "ls /opt"

即使出现了错误,也能执行handlers任务吗?

  • 可以的,使用这个force_handlers: true 执行
[devops@server ansible]$ cat test3.yml 
- hosts: node1
  force_handlers: true  # 即使出现了错误,也会执行handlers任务
  tasks:
    - shell: "touch /opt/123.txt"
      notify: get_status
    - shell: "ls /op"  # 出现了错误
  handlers:
    - name: get_status
      shell: "ls /opt"

# 如果第一个shell和第二个shell交换顺序,不会执行handlers任务,因为剧本出现了错误就会立刻终止

# 上面的之所以会执行handlers任务,因为监听的状态是chaged,即使后面剧本出现了错误,也能执行handlers任务

# 得出一个结论,监听的任务放在前面才行
  • handlers任务

    • 监听的模块必须是chaged状态,才能触发handlers任务

    • 除了监听的模块之外出现了错误的话,就需要force_handlers来强制执行

3、tags标签

就是一个剧本中定义了多个tasks任务时,可以选择一些来执行,并不是全部要执行的

[devops@server ansible]$ cat test4.yml 
- hosts: node1
  tags:  # 定义第一个任务的标签
     - u12
  tasks:
    - debug:
        msg: "u1"
      tags: u1  # 定义模块的标签
    - debug:
        msg: "u2"
      tags: u2
- hosts: node1
  tags:
    - u34  # 定义第二个任务的标签
  tasks:
    - debug:
        msg: "u3"
      tags: u3
    - debug:
        msg: "u4"
      tags: u4

执行指定的标签

# 只执行这个u1标签的模块内容
[devops@server ansible]$ ansible-playbook -t u1 test4.yml 

执行多个标签

[devops@server ansible]$ ansible-playbook -t "u1,u3" test4.yml 
  • always标签,当任务打上了这个标签的话,无论用户是否指定标签,以及指定标签是否与这个一致,这个任务都会执行,因此always将其始终执行的任务

  • never标签,无论用户是否执行,永远不执行该任务,除非指定了never标签才会执行

[devops@server ansible]$ cat test5.yml 
- hosts: node1
  tasks:
    - debug:
        msg: "u1"
      tags: always
    - debug:
        msg: "u2"
      tags: never
    - debug:
        msg: "u3"
      tags: u3

# 执行always和u1标签,不会执行never标签
[devops@server ansible]$ ansible-playbook -t u3 test5.yml

# 执行never标签,同时也会执行always标签
[devops@server ansible]$ ansible-playbook -t never test5.yml 

3、ansible-playbook常用选项

列出s所有任务和标签

# 列出所有play,以及paly中的任务和标签,never标签不会显示
[devops@server ansible]$ ansible-playbook test5.yml --list-tasks

playbook: test5.yml

  play #1 (node1): node1	TAGS: []
    tasks:
      debug	TAGS: [always]
      debug	TAGS: [u3]

列出剧本中的主机

[devops@server ansible]$ ansible-playbook test5.yml --list-hosts

playbook: test5.yml

  play #1 (node1): node1	TAGS: []
    pattern: ['node1']
    hosts (1):
      node1

列出剧本中的所有的tags


[devops@server ansible]$ ansible-playbook test5.yml --list-tags

playbook: test5.yml

  play #1 (node1): node1	TAGS: []
      TASK TAGS: [always, u3]

测试检查,剧本是否有语法错误, --syntax-check

[devops@server ansible]$ ansible-playbook test5.yml --sy

playbook: test5.yml

测试运行,不会影响这个被控端

[devops@server ansible]$ ansible-playbook test5.yml -C

从剧本中指定某个任务开始执行剧本

[devops@server ansible]$ cat test5.yml 
- hosts: node1
  gather_facts: false
  tasks:
    - name: uu1
      debug:
        msg: "u1"
    - name: uu2
      debug:
        msg: "u2"

# 从uu2这里开始执行剧本
[devops@server ansible]$ ansible-playbook --start-at-task "uu2" test5.yml 

指定剧本运行的主机,只在node1上面运行

[devops@server ansible]$ cat test5.yml 
- hosts: all 
  gather_facts: false
  tasks:
    - name: uu1
      debug:
        msg: "u1"
    - name: uu2
      debug:
        msg: "u2"

# 指定node1运行主机
[devops@server ansible]$ ansible-playbook --limit node1 test5.yml 

[devops@server ansible]$ ansible-playbook --help
usage: ansible-playbook [-h] [--version] [-v] [-k] [--private-key PRIVATE_KEY_FILE] [-u REMOTE_USER] [-c CONNECTION] [-T TIMEOUT]
                        [--ssh-common-args SSH_COMMON_ARGS] [--sftp-extra-args SFTP_EXTRA_ARGS] [--scp-extra-args SCP_EXTRA_ARGS]
                        [--ssh-extra-args SSH_EXTRA_ARGS] [--force-handlers] [--flush-cache] [-b] [--become-method BECOME_METHOD]
                        [--become-user BECOME_USER] [-K] [-t TAGS] [--skip-tags SKIP_TAGS] [-C] [--syntax-check] [-D] [-i INVENTORY]
                        [--list-hosts] [-l SUBSET] [-e EXTRA_VARS] [--vault-id VAULT_IDS]
                        [--ask-vault-pass | --vault-password-file VAULT_PASSWORD_FILES] [-f FORKS] [-M MODULE_PATH] [--list-tasks]
                        [--list-tags] [--step] [--start-at-task START_AT_TASK]
                        playbook [playbook ...]

Runs Ansible playbooks, executing the defined tasks on the targeted hosts.

positional arguments:
  playbook              Playbook(s)

optional arguments:
  --ask-vault-pass      ask for vault password  # 需要输入加密密码
  --flush-cache         clear the fact cache for every host in inventory
  --force-handlers      run handlers even if a task fails  # 强制执行handlers任务
  --list-hosts          outputs a list of matching hosts; does not execute anything else  # 列出所有的主机
  --list-tags           list all available tags  # 列出所有的标签
  --list-tasks          list all tasks that would be executed  # 列出所有的任务
  --skip-tags SKIP_TAGS
                        only run plays and tasks whose tags do not match these values
  --start-at-task START_AT_TASK  # 从那个地方开始执行剧本
                        start the playbook at the task matching this name
  --step                one-step-at-a-time: confirm each task before running
  --syntax-check        perform a syntax check on the playbook, but do not execute it  # 检测语法
  --vault-id VAULT_IDS  the vault identity to use
  --vault-password-file VAULT_PASSWORD_FILES  # 存放加密文件的地方
                        vault password file
  --version             show program's version number, config file location, configured module search path, module location, executable
                        location and exit
  -C, --check           don't make any changes; instead, try to predict some of the changes that may occur  # 预执行
  -D, --diff            when changing (small) files and templates, show the differences in those files; works great with --check
  -M MODULE_PATH, --module-path MODULE_PATH
                        prepend colon-separated path(s) to module library
                        (default=~/.ansible/plugins/modules:/usr/share/ansible/plugins/modules)
  -e EXTRA_VARS, --extra-vars EXTRA_VARS  # 定义变量
                        set additional variables as key=value or YAML/JSON, if filename prepend with @
  -f FORKS, --forks FORKS
                        specify number of parallel processes to use (default=5)
  -h, --help            show this help message and exit
  -i INVENTORY, --inventory INVENTORY, --inventory-file INVENTORY
                        specify inventory host path or comma separated host list. --inventory-file is deprecated
  -l SUBSET, --limit SUBSET   # 选择特定主机执行
                        further limit selected hosts to an additional pattern
  -t TAGS, --tags TAGS  only run plays and tasks tagged with these values  # 指定标签
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable connection debugging)  # 显示详细详细信息

Connection Options:
  control as whom and how to connect to hosts

  --private-key PRIVATE_KEY_FILE, --key-file PRIVATE_KEY_FILE
                        use this file to authenticate the connection
  --scp-extra-args SCP_EXTRA_ARGS
                        specify extra arguments to pass to scp only (e.g. -l)
  --sftp-extra-args SFTP_EXTRA_ARGS
                        specify extra arguments to pass to sftp only (e.g. -f, -l)
  --ssh-common-args SSH_COMMON_ARGS
                        specify common arguments to pass to sftp/scp/ssh (e.g. ProxyCommand)
  --ssh-extra-args SSH_EXTRA_ARGS
                        specify extra arguments to pass to ssh only (e.g. -R)
  -T TIMEOUT, --timeout TIMEOUT
                        override the connection timeout in seconds (default=10)
  -c CONNECTION, --connection CONNECTION
                        connection type to use (default=smart)
  -k, --ask-pass        ask for connection password  # 输入密码
  -u REMOTE_USER, --user REMOTE_USER  # 连接被控节点时的用户
                        connect as this user (default=devops)

Privilege Escalation Options:
  control how and which user you become as on target hosts

  --become-method BECOME_METHOD
                        privilege escalation method to use (default=sudo), use `ansible-doc -t become -l` to list valid choices.
  --become-user BECOME_USER
                        run operations as this user (default=root)
  -K, --ask-become-pass
                        ask for privilege escalation password
  -b, --become          run operations with become (does not imply password prompting)

4、剧本出现错误补救方式

在任务失败的时候,playbook依然执行下去不要停止

1、针对命令执行模块出现错误

linux命令执行后返回值为0,则命令执行成功,用/bin/true 这样返回值就会一直为0

[devops@server ansible]$ cat test6.yml 
- hosts: node1
  tasks:
    - shell: "ls /123 || /bin/true"

2、使用ignore_errors 忽略任务的报错

[devops@server ansible]$ cat test6.yml 
- hosts: node1
  tasks:
    - shell: ls /123
      ignore_errors: yes 

posted @ 2026-03-04 16:12  乔的港口  阅读(1)  评论(0)    收藏  举报