Linux之ansible(playbook)超详解

目录

1.给定数据如下: 使用loop来输出My name is zhangsan/lisi My age is 18/20

给定数据Services,要求使用loop来重启服务:提示:将services定义为变量         可以使用lookup('dict', services)来进行转换或者使用{{ services | dict2items }}

2.使用when,当条件成立时才执行任务:        测试给定一个0/1

给定一个未定义的变量

给定一个变量当变量>10时才执行

使用and 和 or来连接两个条件: True and False , True or False

loop和when联合使用 1 中,当name == firewalld时不执行任务

3.notify和handler的使用定义一个任务:使用shell模块执行 echo "123", 使用notify通知handler 任务 debug info

定义handler: 包含一个任务:debug info: 执行 输出: I handled the notify

4.tags使用:定义三个任务:分别打上标签:tag1, tag2, tag2执行playbook, 且指定只执行tag2

5.处理任务失败:    ignore_errors的使用: 定义任务使用command模块执行 

再定义一个任务:使用debug模块输出: This is test for ignore errors(确保这个任务可以正常执行)

failed_when: 定义一个任务: 使用shell模块执行echo 123, 将此任务设置为执行失败

changed_when: 定义一个任务: 使用shell模块执行echo 123 > /root/changed_test, 将此任务的changed状态改为0

block, rescue, always: 在block定义两个任务,在rescue中定义两个任务,在always中定义两个任务,去执行

让rescue中的任务可以执行

6.forks和serial的区别

Forks

Serial

7.导入playbook和task

建立一个import_playbook.yml 然后将其导入另一个playbook: main_playbook.yml 

建立一个import_task.yml里面只写任务:将其导入main_task_playbook.yml中


1.给定数据如下: 使用loop来输出My name is zhangsan/lisi My age is 18/20

  users:
     - name: zhangsan
       age: 18
     - name: lisi
        age: 20

[root@rhcsa ~]# vim playbook1.yml 
- name:
  hosts: rhce
  tasks:
    - name:
      shell: "{{ item }}"
      loop:
        - name: zhangsan
          age: 18
        - name: lisi
          age: 20
[root@rhcsa ~]# ansible-playbook -C playbook1.yml

PLAY [rhce] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [shell] *******************************************************************
skipping: [rhce] => (item={'name': 'zhangsan', 'age': 18}) 
skipping: [rhce] => (item={'name': 'lisi', 'age': 20}) 

PLAY RECAP *********************************************************************
rhce                       : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   

给定数据Services,要求使用loop来重启服务:
提示:将services定义为变量
         可以使用lookup('dict', services)来进行转换或者使用{{ services | dict2items }}

services: 
       httpd:
           name: httpd
           state: restarted
       firewalld: 
         name: firewalld
         state: restarted 

[root@rhcsa ~]# vim playbook2.yml
- name:
  hosts: rhce
  tasks:
    - name:
      service:
        name: "{{ item.name }}"
        state: "{{ item.state}}"
      loop:
        - name: httpd
          state: restarted
        - name: firewalld
          state: restarted
[root@rhcsa ~]# ansible-playbook -C playbook2.yml

PLAY [rhce] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [service] *****************************************************************
changed: [rhce] => (item={'name': 'httpd', 'state': 'restarted'})
changed: [rhce] => (item={'name': 'firewalld', 'state': 'restarted'})

PLAY RECAP *********************************************************************
rhce                       : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

2.使用when,当条件成立时才执行任务:
        测试给定一个0/1

#给1
- name: Simple Boolean task Demo
  hosts: rhce
  vars:
    run_my_task: 1
  tasks:
    - name: httpd package is installed
      yum:
        name: httpd
      when: run_my_task
#给0
- name: Simple Boolean task Demo
  hosts: rhce
  vars:
    run_my_task: 0
  tasks:
    - name: httpd package is installed
      yum:
        name: httpd
      when: run_my_task
[root@rhcsa ~]# ansible-playbook -C playbook3.yml

PLAY [Simple Boolean task Demo] ************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [httpd package is installed] **********************************************
ok: [rhce]

PLAY RECAP *********************************************************************
rhce                       : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

[root@rhcsa ~]# vim playbook3.yml 
[root@rhcsa ~]# ansible-playbook -C playbook3.yml

PLAY [Simple Boolean task Demo] ************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [httpd package is installed] **********************************************
skipping: [rhce]

PLAY RECAP *********************************************************************
rhce                       : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   

给定一个未定义的变量

- name: Simple Boolean task Demo
  hosts: rhce
  #vars:
  # run_my_task: 
  tasks:
    - name: httpd package is installed
      yum:
        name: httpd
      when: run_my_task
[root@rhcsa ~]# ansible-playbook -C playbook3.yml

PLAY [Simple Boolean task Demo] ************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [httpd package is installed] **********************************************
fatal: [rhce]: FAILED! => {"msg": "The conditional check 'run_my_task' failed. The error was: error while evaluating conditional (run_my_task): 'run_my_task' is undefined\n\nThe error appears to be in '/root/playbook3.yml': line 7, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n  tasks:\n    - name: httpd package is installed\n      ^ here\n"}

PLAY RECAP *********************************************************************
rhce                       : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   

给定一个变量当变量>10时才执行

[root@rhcsa ~]# vim playbook3.yml
#给10
- name: Simple Boolean task Demo
  hosts: rhce
  vars:
    run_my_task: 10
  tasks:
    - name: httpd package is installed
      yum:
        name: httpd
      when: run_my_task > 10
#给11
- name: Simple Boolean task Demo
  hosts: rhce
  vars:
    run_my_task: 11
  tasks:
    - name: httpd package is installed
      yum:
        name: httpd
      when: run_my_task > 10
[root@rhcsa ~]# ansible-playbook -C playbook3.yml

PLAY [Simple Boolean task Demo] ************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [httpd package is installed] **********************************************
skipping: [rhce]

PLAY RECAP *********************************************************************
rhce                       : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   

[root@rhcsa ~]# vim playbook3.yml 
[root@rhcsa ~]# ansible-playbook -C playbook3.yml

PLAY [Simple Boolean task Demo] ************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [httpd package is installed] **********************************************
ok: [rhce]

PLAY RECAP *********************************************************************
rhce                       : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

使用and 和 or来连接两个条件: True and False , True or False

#and
- name:
  hosts: rhce
  vars:
    run_my_task: qwe
    test: 121
  tasks:
    - name:
      yum:
        name: httpd
      when: run_my_task == 'qwe' and test == '123'
#or
- name:
  hosts: rhce
  vars:
    run_my_task: qwe
    test: 121
  tasks:
    - name:
      yum:
        name: httpd
      when: run_my_task == 'qwe' or test == '123'
#and
[root@rhcsa ~]# ansible-playbook -C playbook3.yml

PLAY [rhce] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [yum] *********************************************************************
skipping: [rhce]

PLAY RECAP *********************************************************************
rhce                       : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
#or
[root@rhcsa ~]# ansible-playbook -C playbook3.yml

PLAY [rhce] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [yum] *********************************************************************
ok: [rhce]

PLAY RECAP *********************************************************************
rhce                       : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

loop和when联合使用 1 中,当name == firewalld时不执行任务

- name:
  hosts: rhce
  tasks:
    - name:
      service:
        name: "{{ item.name }}"
        state: stopped
      loop:
        - name: httpd
        - name: firewalld
      when: item.name == 'httpd'
[root@rhcsa ~]# ansible-playbook -C playbook3.yml

PLAY [rhce] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [service] *****************************************************************
ok: [rhce] => (item={'name': 'httpd'})
skipping: [rhce] => (item={'name': 'firewalld'}) 

PLAY RECAP *********************************************************************
rhce                       : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

3.notify和handler的使用
定义一个任务:使用shell模块执行 echo "123", 使用notify通知handler 任务 debug info

- name:
  hosts: rhce
  tasks:
    - name:
      debug:
      notify:
        - debug info
  handlers:
    - name: debug info
      shell: echo"123"
[root@rhcsa ~]# ansible-playbook -C playbook4.yml

PLAY [rhce] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [debug] *******************************************************************
ok: [rhce] => {
    "msg": "Hello world!"
}

PLAY RECAP *********************************************************************
rhce                       : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

定义handler: 包含一个任务:debug info: 执行 输出: I handled the notify

- name:
  hosts: rhce
  tasks:
    - name:
      debug:
        msg: I handled the notify
      notify:
        - debug info
  handlers:
    - name: debug info
      shell: echo"123"
[root@rhcsa ~]# ansible-playbook -C playbook4.yml

PLAY [rhce] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [debug] *******************************************************************
ok: [rhce] => {
    "msg": "I handled the notify"
}

PLAY RECAP *********************************************************************
rhce                       : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

4.tags使用:定义三个任务:分别打上标签:tag1, tag2, tag2
执行playbook, 且指定只执行tag2

- hosts: cache
remote_user: root
tasks:
- name: copy
copy: content="apple" dest=/tmp/mama.txt
tags: tag1 # 标签名是 tag1,在下面执行文件时会用到
- name: copy
copy: content="banana" dest=/tmp/mama.txt
tags: tag2 # 标签名是 tag2,在下面执行文件时会用到- name: copy
copy: content="egg" dest=/tmp/mama.txt
tags: tag3 # 标签名是 tag3,在下面执行文件时会用到
#ansible-playbook -t tag1 pbook.yml #执行文件中第二条 tag1 命令

5.处理任务失败:
    ignore_errors的使用: 定义任务使用command模块执行 

- name:
  hosts: rhce
  tasks:
    - name:
      command:
      ignore_errors: yes
    - name:
      service:
        name: httpd
        state: started
[root@rhcsa ~]# ansible-playbook -C playbook5.yml

PLAY [rhce] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [command] *****************************************************************
fatal: [rhce]: FAILED! => {"changed": false, "cmd": null, "delta": null, "end": null, "msg": "no command given", "rc": 256, "start": null, "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
...ignoring

TASK [service] *****************************************************************
changed: [rhce]

PLAY RECAP *********************************************************************
rhce                       : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=1   

再定义一个任务:使用debug模块输出: This is test for ignore errors(确保这个任务可以正常执行)

- name:
  hosts: rhce
  tasks:
     - name:
       command:
       ignore_errors: yes
     - name:
       debug:
         msg: This is test for ignore errors
[root@rhcsa ~]# ansible-playbook -C playbook6.yml

PLAY [rhce] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [command] *****************************************************************
fatal: [rhce]: FAILED! => {"changed": false, "cmd": null, "delta": null, "end": null, "msg": "no command given", "rc": 256, "start": null, "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
...ignoring

TASK [debug] *******************************************************************
ok: [rhce] => {
    "msg": "This is test for ignore errors"
}

PLAY RECAP *********************************************************************
rhce                       : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=1   

failed_when: 定义一个任务: 使用shell模块执行echo 123, 将此任务设置为执行失败

- name:
  remote_user: root
  hosts: rhce
  tasks:
     - name:
       shell: echo "123"
       register: command_result
       failed_when: "'123' in command_result.stdout"
[root@rhcsa ~]# ansible-playbook playbook6.yml

PLAY [rhce] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [shell] *******************************************************************
fatal: [rhce]: FAILED! => {"changed": true, "cmd": "echo \"123\"", "delta": "0:00:00.003329", "end": "2022-08-09 11:36:31.884746", "failed_when_result": true, "msg": "", "rc": 0, "start": "2022-08-09 11:36:31.881417", "stderr": "", "stderr_lines": [], "stdout": "123", "stdout_lines": ["123"]}

PLAY RECAP *********************************************************************
rhce                       : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0 

changed_when: 定义一个任务: 使用shell模块执行echo 123 > /root/changed_test, 将此任务的changed状态改为0

- name:
  hosts: rhce
  tasks:
    - name:
      shell: echo "123" > /root/changed_test
      changed_when: false
[root@rhcsa ~]# ansible-playbook playbook7.yml

PLAY [rhce] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [rhce]

TASK [shell] *******************************************************************
ok: [rhce]

PLAY RECAP *********************************************************************
rhce                       : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

block, rescue, always: 在block定义两个任务,在rescue中定义两个任务,在always中定义两个任务,去执行

• block: 定义要运行的主要的任务。
• rescue: 定义要在 block 子句中定义的任务失败时运行的任务。
• always:定义始终都独立运行的任务,不论 block 和 rescue 子句中定义的任务
是否成功还是失败。

[root@rhcsa ~]# vim playbook1.yml

            msg: "This is block1"
        - name:
          debug:
            msg: "This is block2"
      rescue:
        - name:
          debug:
            msg: "This is rescue1"
        - name:
          debug:
            msg: "This is rescue2"
      always:
        - name:
          debug:
            msg: "This is always1"
        - name:
          debug:
            msg: "This is always2"
[root@rhcsa ~]# ansible-playbook playbook1.yml

PLAY [rhce] **********************************************************************

TASK [Gathering Facts] ***********************************************************
ok: [rhce]

TASK [debug] *********************************************************************
ok: [rhce] => {
    "msg": "This is block1"
}

TASK [debug] *********************************************************************
ok: [rhce] => {
    "msg": "This is block2"
}

TASK [debug] *********************************************************************
ok: [rhce] => {
    "msg": "This is always1"
}

TASK [debug] *********************************************************************
ok: [rhce] => {
    "msg": "This is always2"
}

PLAY RECAP ***********************************************************************
rhce                       : ok=5    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

让rescue中的任务可以执行

[root@rhcsa ~]# vim playbook1.yml

- name:
  hosts: rhce
  tasks:
    - name:
      block:
        - name:
          debug:
            msg: "This is block1"
          failed_when: 'This is block1'
        - name:
          debug:
            msg: "This is block2"
          failed_when: 'This is block2'
      rescue:
        - name:
          debug:
            msg: "This is rescue1"
        - name:
          debug:
            msg: "This is rescue2"
[root@rhcsa ~]# ansible-playbook playbook1.yml

PLAY [rhce] **********************************************************************

TASK [Gathering Facts] ***********************************************************
ok: [rhce]

TASK [debug] *********************************************************************
fatal: [rhce]: FAILED! => {
    "msg": "This is block1"
}

TASK [debug] *********************************************************************
ok: [rhce] => {
    "msg": "This is rescue1"
}

TASK [debug] *********************************************************************
ok: [rhce] => {
    "msg": "This is rescue2"
}

TASK [debug] *********************************************************************
ok: [rhce] => {
    "msg": "This is always1"
}

TASK [debug] *********************************************************************
ok: [rhce] => {
    "msg": "This is always2"
}

PLAY RECAP ***********************************************************************
rhce                       : ok=5    changed=0    unreachable=0    failed=0    skipped=0    rescued=1    ignored=0   

6.forks和serial的区别

Forks

forks用来设置同一时刻与目的主机连接数,也可以理解为主机并行数,默认值比较保守为5。在生产中,多数情况下我们会更改这个参数。如果控制节点的CPU和网络性能够用,设置几十上百个也是可以的。

在ansible.cfg设置forks的全局默认值:

# ansible.cfg
[defaults]
forks  = 15

命令行设置forks的数量,即在执行playbook时,通过「--forks」或「-f」指定: 

lab-ansible ansible-playbook playbooks/test_forks.yaml --fork 10

Serial

serial用于控制一个play内的主机并行数,这个并行数不能超过forks,超过后则serial不会生效。

定义方法如下:

--
- hosts: nodes
  serial: 2
  tasks:

本质上,serial作用范围是一个play,受限于forks,但比forks控制的更加细节。假如我们的forks设置为100,但是想让某个play里的所有任务并行数为50的执行,此时我们应该想到serial这个调优方法。

7.导入playbook和task

建立一个import_playbook.yml 然后将其导入另一个playbook: main_playbook.yml 

[root@rhcsa ~]# vim import_playbook.yml

---
- name: this is import_play
  hosts: rhce
  tasks:
    - name: stopped httpd
      service:
        name: httpd
        state: stopped
#####################################
[root@rhcsa ~]# vim main_playbook.yml

- name: import
  import_playbook: import_playbook.yml
- name: this is main_play
  hosts: all
  tasks:
    - name: start firewalld
      service:
        name: firewalld
        state: stopped
        enabled: no
[root@rhcsa ~]# ansible-playbook main_playbook.yml -C

PLAY [this is import_play] *********************************************************

TASK [Gathering Facts] *************************************************************
ok: [rhce]

TASK [stopped httpd] ***************************************************************
ok: [rhce]

PLAY [this is main_play] ***********************************************************

TASK [Gathering Facts] *************************************************************
ok: [rhel]
ok: [rhce]

TASK [start firewalld] *************************************************************
ok: [rhel]
ok: [rhce]

PLAY RECAP *************************************************************************
rhce                       : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
rhel                       : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

建立一个import_task.yml里面只写任务:将其导入main_task_playbook.yml中

[root@rhcsa ~]# vim import_task.yml

- name: this is import_play
  hosts: rhce
  tasks:
    - name: stopped httpd
      service:
        name: httpd
        state: stopped
######################################
[root@rhcsa ~]# vim main_task_playbook.yml

- name: import
  import_playbook: import_task.yml
- name: this is main_task_play
  hosts: rhce
  tasks:
    - name: start firewalld
      service:
        name: firewalld
        state: stopped
        enabled: no
[root@rhcsa ~]# ansible-playbook main_task_playbook.yml -C

PLAY [this is import_play] *********************************************************

TASK [Gathering Facts] *************************************************************
ok: [rhce]

TASK [stopped httpd] ***************************************************************
ok: [rhce]

PLAY [this is main_task_play] ******************************************************

TASK [Gathering Facts] *************************************************************
ok: [rhce]

TASK [start firewalld] *************************************************************
ok: [rhce]

PLAY RECAP *************************************************************************
rhce                       : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gur.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值