【2023】ansible-高级任务控制

简单介绍

Tag:任务标签

tag用于标记一个或多个任务(task)或是一个或多个角色(role),以便在执行playbook时只运行被标记的任务或角色。这可以帮助我们精细控制playbook的执行范围,只执行我们想要执行的任务或角色,提高执行效率和安全性。

  • 一个任务打一个标签
  • 一个任务打多个标签
  • 多个任务打一个标签

使用标签时:

  • -t:指定某个标签
  • –skip-tags:执行除此标签外的所有标签

示例:

- name: install nginx
  yum:
    name: nginx
    state: latest
  tags: 
    - nginx
ansible-playbook playbook.yml --tags nginx

Include:任务复用

Include用于将一个或多个文件或任务列表包含到当前任务或playbook中。它可以帮助我们组织和重用任务和playbook,提高代码的可读性和可维护性。

比如:A项目需要重启某服务,B项目也需要重启这个服务。那么就可以使用Include来减少工作量

案例:多任务调用相同task

  • 定义一个restart的yml文件
vim restart_nginx.yml

- name: Restart nginx
  systemd:
    name: nginx
    state: restarted
  • A项目调用restart_nginx.yml
- hosts: web
  tasks:
    - name: A project
      command: echo "A"
    - name: Restart nginx
      include: restart_nginx.yml
  • B项目调用restart_nginx.yml
- hosts: web
  tasks:
    - name: B project
      command: echo "B"
    - name: Restart nginx
      include: restart_nginx.yml

Ignore_errors:错误处理关键字

当在执行Ansible任务时,设置"ignore_errors"参数为True,表示在执行该任务时,如果遇到错误,Ansible不会终止任务的执行,而是会将错误记录下来,然后继续执行后续任务。
这个参数通常用于在某些情况下,某些任务的失败并不会影响整个任务链的执行,需要继续执行后续任务的场景中。

示例:

---
- hosts:
  remote_user: root
  tasks:
    - name: Ignore False
      command: /bin/false
      ignore_errors: yes
    - name: touch file
      file: patch=/tmp/yyang.txt state=touch

这个示例是说,第一个name执行失败后,继续执行后面name,而不是停止。

force_handlers

中途的task执行失败,强制执行handlers。

示例:

- hosts:
  force_handlers: yes
  tasks:
    - name: Touch file
      file: path=/tmp/handles state=touch
      notify: Restart nginx server
    - name: Installed packages
      yum: 
        name: aaa
        state: latest
  handlers:
    - name: Restart nginx server
      systemd: name=nginx state=restarted

此示例说明第二个name执行会报错,但是依然会执行handlers。

change_when

change_when参数用于控制在何种条件下报告任务状态的更改。

默认情况下,如果任务对被管理系统进行了任何修改,Ansible会将任务报告为“已更改”。但是,有些情况下,您只希望在特定条件下才将任务报告为“已更改”,而不对被控端做出修改时输出ok。

changed_when: false

vault:数据加密

将敏感的数据文件进行加密,而非存放在明文的playbook中。

示例:

[root@localhost roles]# echo "hello world" >>hello.yml
[root@localhost roles]# ansible-vault-2 encrypt hello.yml 
New Vault password: 
Confirm New Vault password: 
Encryption successful
[root@localhost roles]# cat hello.yml 
$ANSIBLE_VAULT;1.1;AES256
35353638363039623231623338646562613363623031663262653162306664633939306437306134
3039666238623039383237623233613639646666346233360a663864313638636562333931656232
37616163323765373339376262343862396661363933613539646239636361663066653235663738
3362653964373464360a353030386536386238613932313936633765383232326237393566633430
3766

输入密码后再查看文件只能看到加密后的数据。

查看内容:需要输入密码

[root@localhost roles]# ansible-vault-2 view hello.yml 
Vault password: 
hello world

解除加密:需要输入密码

[root@localhost roles]# ansible-vault-2 decrypt hello.yml 
Vault password: 
Decryption successful
[root@localhost roles]# cat hello.yml 
hello world

猜你喜欢

转载自blog.csdn.net/qq_42527269/article/details/129564685
今日推荐