使用 any_errors_fatal 设置失败退出
不同账号执行
- 在Ansible配置文件
ansible.cfg中设置remote_user
remote_user 可以在Ansible的主配置文件 ansible.cfg 中进行全局设置。在这个文件中,你可以通过设置 remote_user 关键字来指定默认的远程用户账户。例如:
[defaults]
remote_user = ansibleuser
这样,当你运行Ansible命令时,如果没有在其他地方显式指定远程用户,那么就会使用这个默认的用户账户
- 在Inventory文件中设置
remote_user
Inventory文件是Ansible用来指定操作的主机的配置文件。在这个文件中,你可以为每个主机或主机组指定一个远程用户。例如:
[webservers]
web1.example.com ansible_ssh_user=www-data
web2.example.com ansible_ssh_user=www-data
在这个例子中,所有的Web服务器都会以 www-data 用户的身份进行操作
- 在Playbook文件中设置
remote_user
在Playbook文件中,你可以在每个Play或Task级别上指定 remote_user。这允许你在不同的Play或Task中使用不同的用户账户。例如:
- name: Deploy application
hosts: webservers
remote_user: deployuser
tasks:
- name: Ensure Nginx is running
service:
name: nginx
state: started
在这个Playbook中,所有的任务都会以 deployuser 用户的身份在 webservers 主机组上执行
- 特权升级(Privilege Escalation)
在某些情况下,你可能需要在远程主机上以更高的权限执行某些任务。Ansible提供了 become、become_method 和 become_user 参数来实现这一点。例如:
- name: Restart the firewall
hosts: all
remote_user: ansibleuser
become: yes
become_method: sudo
become_user: root
tasks:
- name: Restart firewalld
systemd:
name: firewalld
state: restarted
在这个例子中,Ansible会在远程主机上以 root 用户的身份执行重启防火墙的服务任务
使用serial 参数
在 Ansible 中确保任务在一台服务器上执行完成后再在另一台服务器上执行,可以使用 serial 参数,可以指定每次只向有序列表中的一台服务器发送指令。需要在 Playbook 中加入 serial 参数并指定一个小于等于有序列表长度的数值
- name: Run commands on webservers
hosts: webservers
serial: 1 #表示一次执行一台机器,按列表顺序执行
tasks:
- name: Do a thing
shell: /path/to/command
使用 failed_when 参数
在 Ansible 的任务(task)中,可以使用 failed_when 参数来指定任务失败的条件。例如,如果希望当某个命令的返回值非0时任务标记为失败,可以这样写:
Yaml
复制
- name: Run a command
command: /path/to/command
register: result
failed_when: result.rc != 0
在这个例子中,result.rc 是命令的返回值,如果返回值不等于0,任务将被视为失败4。
使用 ignore_errors 和 rescue 块
如果希望在任务失败时不中断整个 playbook 的执行,可以使用 ignore_errors 参数。但这通常需要配合 rescue 块一起使用,以便在任务失败时执行一些清理或恢复操作。例如:
Yaml
复制
- name: Run a command
command: /path/to/command
ignore_errors: yes
register: result
- name: Rescue block
debug:
msg: "Command failed with return code {{ result.rc }}"
when: result.rc != 0
在这个例子中,即使命令失败(返回值非0),ignore_errors: yes 会让 Ansible 继续执行后续任务。rescue 块会在任务失败时执行,打印出错误信息4。
使用 until 循环
如果希望某个任务在成功之前不断重试,可以使用 until 循环。例如:
Yaml
复制
- name: Run a command until it succeeds
command: /path/to/command
register: result
until: result.rc == 0
retries: 5
delay: 5
在这个例子中,任务会一直重试直到返回值为0,或者达到最大重试次数(retries)4。
结合 when 条件
也可以在任务中使用 when 条件来控制任务的执行。例如,只有当前一个任务成功时才执行下一个任务:
Yaml
复制
- name: Run a command
command: /path/to/command
register: result
- name: Only run this if the previous command succeeded
command: /path/to/next/command
when: result.rc == 0
在这个例子中,第二个任务只有在第一个任务成功(返回值为0)时才会执行