Ansible流程控制先容
1. 条件判断
when
when用于根据条件决定是否实行使命。
- - hosts: all
- tasks:
- - name: Install package only on RedHat
- package:
- name: httpd
- state: present
- when: ansible_os_family == "RedHat"
复制代码 2. 循环
loop
loop用于遍历列表或聚集。
- - hosts: all
- tasks:
- - name: Install multiple packages
- package:
- name: "{{ item }}"
- state: present
- loop:
- - vim
- - git
- - curl
复制代码 with_items
较老的循环方式,遍历列表。
- - hosts: all
- tasks:
- - name: Install packages using with_items
- package:
- name: "{{ item }}"
- state: present
- with_items:
- - vim
- - git
复制代码 with_dict
用于遍历字典。
- - hosts: all
- tasks:
- - name: Print dictionary items
- debug:
- msg: "Key: {{ item.key }}, Value: {{ item.value }}"
- with_dict:
- item1: value1
- item2: value2
复制代码 with_sequence
天生序列并遍历。
- - hosts: all
- tasks:
- - name: Create files using with_sequence
- file:
- path: "/tmp/file{{ item }}"
- state: touch
- with_sequence: start=1 end=5
复制代码 with_fileglob
遍历匹配文件名的文件。
- - hosts: all
- tasks:
- - name: Read files from directory
- debug:
- msg: "Found file: {{ item }}"
- with_fileglob:
- - /tmp/*.txt
复制代码 with_together
并行遍历多个列表。
- - hosts: all
- tasks:
- - name: Combine items from two lists
- debug:
- msg: "Item from list1: {{ item.0 }}, Item from list2: {{ item.1 }}"
- with_together:
- - ['a', 'b', 'c']
- - [1, 2, 3]
复制代码 3. 循环控制
loop_control
提供更细粒度控制。
- - hosts: all
- tasks:
- - name: Custom loop variable
- debug:
- msg: "Current item: {{ custom_item }}"
- loop:
- - a
- - b
- loop_control:
- loop_var: custom_item
复制代码 在Ansible中,loop_control是一个用于提供循环过程中更细粒度控制的选项。它允许你自界说循环变量名、设置循环的标签、限定循环的并行实行数量等。这使得在处置处罚循环时可以更加机动和精确。
下面是一个使用loop_control的示例,展示了怎样自界说循环变量名:
- - hosts: all
- tasks:
- - name: Custom loop variable
- debug:
- msg: "Current item: {{ custom_item }}"
- loop:
- - a
- - b
- loop_control:
- loop_var: custom_item
复制代码 在这个例子中,loop_control用于指定循环变量的名称。默认情况下,Ansible中的循环变量名为item,但通过loop_control,你可以将其更改为任何你想要的名称,比如这里的custom_item。如许,在循环体内部,就可以使用{{ custom_item }}来引用当前迭代的元素。
这种自界说循环变量的功能在必要在循环内部引用多个循环变量或在复杂的脚本中进步代码的可读性时非常有效。通过loop_control,你可以更精确地控制循环的举动,使其更符合你的特定需求。
4. 错误处置处罚
ignore_errors
在使命失败时继承实行后续使命。
- - hosts: all
- tasks:
- - name: Failing task
- command: /bin/false
- ignore_errors: yes
- - name: This will run despite the previous failure
- debug:
- msg: "The previous task failed, but this still runs."
复制代码 failed_when
自界说使命失败的条件。
- - hosts: all
- tasks:
- - name: Custom failure condition
- command: /bin/true
- register: result
- - name: Check the result
- debug:
- msg: "This task will fail if the command did not return 0."
- failed_when: result.rc != 0
复制代码 5. 包罗和导入
include_tasks
动态包罗使命文件。
- - hosts: all
- tasks:
- - name: Include tasks based on a condition
- include_tasks: my_tasks.yml
- when: ansible_os_family == "Debian"
复制代码 import_tasks
静态导入使命文件。
- - hosts: all
- tasks:
- - import_tasks: my_imported_tasks.yml
复制代码 6. 块和非常处置处罚
block
将一组使命组合在一起,便于管理和错误处置处罚。
- - hosts: all
- tasks:
- - block:
- - name: Task 1
- command: /bin/true
- - name: Task 2
- command: /bin/false
- rescue:
- - name: Handle failure
- debug:
- msg: "One of the tasks failed, handling the error."
- # 当block中的任务错误时,会执行rescue中的任务
复制代码 7. 脚色的流程控制
在脚色中构造和控制使命实行。
- # roles/myrole/tasks/main.yml
- - name: Task in role
- command: /bin/echo "This is a task in a role"
- - include_tasks: another_tasks.yml
复制代码 这些示例展示了Ansible中的各种流程控制功能,资助你在主动化使命和设置管理中实现更复杂的逻辑。
*include_tasks、import_tasks_include之间的区别
在Ansible中,include_tasks、import_tasks和include指令都是用来构造和重用代码的,但它们在用法和上下文中有一些区别:
- include_tasks:
- 动态包罗使命文件:include_tasks可以根据条件动态地包罗一个使命列表文件。
- 使用场景:当你必要基于某些条件(如使用体系、情况变量等)来决定是否实行一组使命时,可以使用include_tasks。
- 示例:
- - hosts: all
- tasks:
- - name: Include tasks based on a condition
- include_tasks: my_tasks.yml
- when: ansible_os_family == "Debian"
复制代码
- import_tasks:
- 静态导入使命文件:import_tasks用于静态地导入一个使命列表文件,它不会根据条件来决定是否导入。
- 使用场景:当你必要在当前使命列表中静态地包罗一组使命时,可以使用import_tasks。
- 示例:
- ```yaml
- - hosts: all
- tasks:
- - import_tasks: my_imported_tasks.yml
- ```
复制代码
- include:
- 包罗变量或文件:include用于包罗变量文件或脚色文件。
- 使用场景:当你必要在当前脚本中包罗一个变量文件或脚色文件时,可以使用include。
- 示例:
- ```yaml
- - hosts: all
- vars_files:
- - vars.yml
- ```
复制代码 这些指令在Ansible中提供了机动的代码构造和重用机制,使得脚本更加模块化和可维护。
include指令在Ansible中重要用于包罗变量文件、使命文件、模板文件等,它的作用不但限于使命列表,还包罗其他资源范例。以下是include指令的一些额外阐明:
- 变量文件:
- include_vars:用于包罗变量文件,这些变量可以在使掷中使用。
- 示例:
- ```yaml
- - hosts: all
- vars_files:
- - vars.yml
- ```
复制代码
- 使命文件:
- 固然include_tasks用于动态包罗使命文件,但include也可以用于静态包罗使命文件,这通常用于脚色中。
- 示例:
- ```yaml
- - include: tasks/main.yml
- ```
复制代码
- 模板文件:
- include可以用于包罗模板文件,这些文件可以用于天生设置文件等。
- 示例:
- ```yaml
- - name: Include a template file
- include: my_template.j2
- ```
复制代码
- 文件路径:
- include指令支持相对路径和绝对路径。
- 相对路径是相对于当前脚本文件的路径。
- 绝对路径是从文件体系的根目次开始的路径。
- 条件包罗:
- 固然include自己不支持条件包罗,但可以通过在包罗的文件中使用条件语句来实现条件包罗的结果。
- 循环包罗:
- include指令可以与loop一起使用,实现循环包罗文件。
- 示例:
- - hosts: all
- tasks:
- - name: Include tasks from a list
- include: "{{ item }}"
- with_first_found:
- - "tasks/{{ ansible_os_family }}.yml"
- - "tasks/default.yml"
复制代码
- 错误处置处罚:
- 如果include指定的文件不存在,Ansible会报错。
- 脚色中的使用:
- 在Ansible脚色中,include指令通常用于包罗使命文件、变量文件或模板文件。
- 静态与动态:
- include通常是静态的,意味着它在脚本剖析时就确定了要包罗的文件。
- 与include_tasks相比,include不提供动态包罗的本事。
- 与import的区别:
- import指令在Ansible的早期版本中用于包罗使命,但现在保举使用import_tasks。
include指令是Ansible脚本编写中非常机动和强大的工具,可以有效地构造和管理代码。
条件语句再细说
使用when指令
且、或、非、是
且:and
或:or
非:!=
是:==
含糊条件
使用is match
- ...
- yum:
- name:
- - xxx
- - xxx
- when: ansible_hostname is match 'web*'
- ...
复制代码 when指令的具体使用方法
在Ansible中,when指令用于条件判断,允许你根据特定条件决定是否实行某个使命。它可以根据变量的值、注册的结果或其他条件举行判断。
- 根本语法:
- - name: Task name
- command: your_command
- when: condition
复制代码 - 条件可以是:
- 变量比力:when: variable_name == 'value'
- 布尔值:when: some_boolean_variable
- 列表查抄:when: item in my_list
- 注册变量结果:when: result_variable is succeeded
以下是一个简朴示例,展示怎样使用when指令:
- ---
- - hosts: all
- tasks:
- - name: Check if a file exists
- stat:
- path: /tmp/myfile.txt
- register: file_stat
- - name: Create a file if it does not exist
- file:
- path: /tmp/myfile.txt
- state: touch
- when: not file_stat.stat.exists
- - name: Notify if the file was created
- debug:
- msg: "The file was created!"
- when: file_stat.stat.exists == false
复制代码 上面是示例的表明:
- stat模块:查抄/tmp/myfile.txt是否存在,并将结果注册到file_stat。
- 创建文件使命:仅在文件不存在时实行(when: not file_stat.stat.exists)。
- 调试使命:如果文件被创建,输出一条消息。
变量比力
假设你有一个变量my_os,它存储了目的呆板的使用体系范例。你只想在使用体系为Ubuntu时实行某个使命。
- - name: Install package if OS is Ubuntu
- apt: name=nginx state=present
- when: my_os == 'Ubuntu'
复制代码 布尔值
如果你有一个布尔变量install_nginx,你想根据这个变量的值来决定是否安装Nginx。
- - name: Install Nginx if the condition is true
- command: apt-get install nginx
- when: install_nginx
复制代码 列表查抄
如果你有一个列表packages_to_install,而且你只想在列表中包罗nginx时安装它。
- - name: Install nginx if it is in the list
- command: apt-get install nginx
- when: 'nginx' in packages_to_install
复制代码 注册变量结果
假设你已经运行了一个使命来安装某些软件包,而且你将结果注册到了变量install_result中。只有当安装乐成时,你才想实行下一个使命。
- - name: Install some software
- command: apt-get install some_software
- register: install_result
- - name: Run configuration script if software installed successfully
- command: ./configure_software.sh
- when: install_result is succeeded
复制代码 组合条件
你也可以组合多个条件来创建更复杂的逻辑。
- - name: Install nginx only if it's not installed and the OS is Ubuntu
- command: apt-get install nginx
- when: nginx_not_installed and my_os == 'Ubuntu'
复制代码 在这个例子中,nginx_not_installed是一个布尔变量,表现Nginx是否已经安装。只有当Nginx未安装而且使用体系是Ubuntu时,才会实行安装Nginx的下令。
再探究一下Ansible中的“列表查抄”和“注册变量”的条件:
一、 列表查抄(List Checking)
在Ansible中,你可以使用in关键字来查抄一个值是否存在于一个列表中。这在你必要基于一组预界说的值来决定是否实行某个使命时非常有效。
比方,假设你有一个变量my_list,它是一个包罗多个元素的列表,你想查抄某个特定的值item是否在这个列表中:
- - name: Check if item is in the list
- command: echo "Item is in the list"
- when: item in my_list
复制代码 在这个例子中,如果变量item的值存在于变量my_list中,那么echo "Item is in the list"下令将被实行。
二、 注册变量(Registered Variables)
在Ansible中,你可以使用register关键字来生存使命的输出,如许你就可以在后续的使掷中引用这个输出。注册的变量通常用于条件判断,以决定是否实行后续的使命。
比方,你有一个使命,它实行一个下令并注册了其结果:
- - name: Run a command and register the result
- command: ls /nonexistent
- register: command_result
- ignore_errors: yes
复制代码 在这个例子中,ignore_errors: yes告诉Ansible纵然命令失败也继承实行。register: command_result将下令的输出生存到变量command_result中。
然后,你可以使用when语句来查抄这个注册变量的状态,并决定是否实行后续的使命:
- - name: Check if the command was successful
- command: echo "Command was successful"
- when: command_result is succeeded
复制代码 在这个例子中,如果ls /nonexistent下令乐成实行(纵然它现实上没有找到任何文件,由于我们使用了ignore_errors: yes),那么echo "Command was successful"下令将被实行。
注册变量可以包罗多种信息,包罗下令的退出状态、尺度输出和尺度错误输出等。你可以根据这些信息来构建复杂的条件判断。比方,你可以查抄下令是否失败:
- - name: Check if the command failed
- command: echo "Command failed"
- when: command_result is failed
复制代码 在这个例子中,如果ls /nonexistent下令失败(这是预期的,由于/nonexistent目次不存在),那么echo "Command failed"下令将被实行。
更多的例子:
例 1:根据使用体系范例实行使命
- ---
- - hosts: all
- tasks:
- - name: Install packages based on OS
- package:
- name:
- - "{{ item }}"
- state: present
- loop:
- - vim
- - wget
- when: ansible_os_family == 'Debian'
复制代码 表明:
这个使命会在Debian家属的使用体系(如Ubuntu)上安装vim和wget,只在when条件满足时实行。
例 2:根据变量值举行条件判断
- ---
- - hosts: all
- vars:
- environment: production
- tasks:
- - name: Deploy application only in production
- shell: deploy_script.sh
- when: environment == 'production'
复制代码 表明:
此使命仅在environment变量即是production时实行,确保应用步伐只在生产情况中摆设。
例 3:根据注册变量的结果实行使命
- ---
- - hosts: all
- tasks:
- - name: Check if a service is running
- shell: systemctl is-active my_service
- register: service_status
- ignore_errors: yes
- - name: Start the service if it is not running
- service:
- name: my_service
- state: started
- when: service_status.stdout != 'active'
复制代码 表明:
这个示例起首查抄服务my_service是否正在运行。如果服务未运行(即service_status.stdout不是active),则会启动该服务。
例 4:使用多条件判断
- ---
- - hosts: all
- vars:
- app_installed: true
- app_version: '1.0.0'
- tasks:
- - name: Run upgrade if app is installed and version is less than 2.0.0
- shell: upgrade_script.sh
- when: app_installed == true and app_version | version_compare('2.0.0', '<')
复制代码 表明:
这个使命在应用步伐已安装且版本低于2.0.0时实行升级脚本。使用version_compare函数举行版本比力。
循环语句再细说
怎样使用
使用item变量团结with_items或loop指令
在Ansible中,with_items和loop都是用来迭代列表或聚集的指令,但它们有一些具体的区别和使用场景。以下是这两者的具体比力:
一、 1. 根本概念
- with_items:是Ansible的一个古老的循环结构,用于遍历列表。它的语法较为简朴,但功能较为有限。
- loop:是Ansible中更当代的循环语法,提供了更强大的功能和机动性。它是with_items的保举更换品。
二、 2. 语法比力
with_items 示例
- - name: Install packages using with_items
- yum:
- name: "{{ item }}"
- state: present
- with_items:
- - vim
- - wget
- - curl
复制代码 loop 示例
- - name: Install packages using loop
- yum:
- name: "{{ item }}"
- state: present
- loop:
- - vim
- - wget
- - curl
复制代码 三、 3. 功能区别
- 可嵌套:
- loop支持嵌套循环,可以与其他循环指令团结使用,而with_items则不支持。
- - name: Loop over a list of lists
- debug:
- msg: "{{ item }}"
- loop:
- - [1, 2, 3]
- - [4, 5, 6]
- loop_control:
- subelements: 0
复制代码
- 更好的变量支持:
- loop可以与其他的控制指令(如loop_control)团结使用,可以更机动地控制迭代过程。
四、 4. 性能和可读性
- 性能:
- 在某些情况下,loop的性能大概会稍好,特殊是在处置处罚大型数据集时。
- 可读性:
- loop的语法更划一,易于明确,尤其是在复杂的场景下。保举在新项目中使用loop。
五、 5. 使用发起
- 保举使用loop:由于loop是Ansible的当代循环方式,功能更强大且机动性更高,因此在新项目中应优先选择loop。
- with_items的使用:对于一些简朴的使命,可以继承使用with_items,但应留意其在未来大概会被弃用。
六、 总结
只管with_items和loop都可以实现相似的功能,loop在机动性、功能和可读性方面具有显着的上风。因此,发起在编写Ansible脚本时优先选择使用loop。
loop需在安装Ansible2X版本后才气使用
item变量有固定子元素?
在Ansible中,item变量通常用于循环(如with_items或loop)来表现当前迭代的元素。具体来说,item可以用来访问循环中每个元素的子元素,特殊是在处置处罚字典或列表时。
- - name: Example with list of dictionaries
- debug:
- msg: "Name is {{ item.name }}, Age is {{ item.age }}"
- loop:
- - { name: 'Alice', age: 30 }
- - { name: 'Bob', age: 25 }
复制代码 在这个例子中,item是每个字典,可以通过item.name和item.age访问它的子元素。
- - name: Example with dictionary containing a list
- debug:
- msg: "Fruit is {{ item }} and Price is {{ prices[item] }}"
- vars:
- prices:
- apple: 1.2
- banana: 0.5
- loop:
- - apple
- - banana
复制代码 这里,item是循环中的水果名,使用prices[item]来获取对应代价。
- item是动态的,具体内容取决于当前循环的上下文。
- 可以在循环中使用item的子元素访问来处置处罚复杂数据结构,比方列表和字典的组合。
- 团结with_items或loop使用,可以使设置和使命更加机动和可重复。
实例-服务器安装根本情况优化
需求
优化一台刚安装完的捏造机:
- 改网卡信息
- 换新堆栈
- 安装根本软件包(包罗时间同步软件)
- 优化文件形貌符
- *防火墙设置
部门实现
换指定新堆栈
- ---
- - name: the play1
- hosts: all
- become: no
- tasks:
- - name: task:备份原来的仓库
- include: /path/to/task_backup_old_repos.yaml
- - name: task:安装新仓库
- include: /path/to/task_install_new_repos.yaml
复制代码 可使用get_url加此中的列表循环的方式安装新堆栈:
固然也可以使用shell模块,内里使用wget下令
安装根本软件包
- ---
- - name: the play1
- hosts: all
- tasks:
- - name: 安装好些个基础软件包
- yum:
- name: {{item}}
- state: present
- loop:
- - chrony
- - aaa
- - bbb
- - ccc
- - ddd
- ...
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!qidao123.com:ToB企服之家,中国第一个企服评测及软件市场,开放入驻,技术点评得现金 |