我正在构建一个Ansible剧本,如果需要升级软件,我想在其中备份数据库。为此,我想将可用的最高版本号与已安装的版本号进行比较。如果最新版本比已安装的版本高,我将备份数据库。
但是,问题是我找不到在Ansible中对版本号进行排序的好方法。标准排序过滤器对字符串而不是数字/版本进行排序。
这就是我现在正在做的事情:
- name: Get package version
yum:
list: package
register: software_version
- name: Read which version is installed and available
set_fact:
software_version_installed: "{{ software_version | json_query(\"results[?yumstate=='installed'].version\") | sort | last }}"
software_version_available: "{{ software_version | json_query(\"results[?yumstate=='available'].version\") | sort | last }}"
- name: Backup old database file on remote host
copy:
src: "{{ software.database_path }}"
dest: "{{ software.database_path }}_{{ ansible_date_time.date }}_v{{ software_version_installed }}"
remote_src: yes
when: software_version_installed is version(software_version_available, "<")
只要版本号停留在数字10下方(例如1.2.3,但不是1.10.1),上述剧本就可以工作,因为排序就像字符串一样进行。当版本号必须排序时1.2.3和1.10.1,它将以1.2.3作为最新版本。
显示问题:
- name: Read which version is installed and available
set_fact:
software_versions: [ "2.5.0", "2.9.0", "2.10.0", "2.11.0" ]
- name: Debug
debug:
var: software_versions | sort
TASK [grafana : Debug]**********************************
ok: [localhost] => {
"software_versions | sort": [
"2.10.0",
"2.11.0",
"2.5.0",
"2.9.0"
]
}
有人知道在Ansible中对版本号进行排序的好方法吗?
答案 0 :(得分:0)
我无法确认您的经历:
排序就像字符串一样。
请参见下面的示例
vars:
version_installed: "1.10.1"
versions:
- "1.1.3"
- "1.2.3"
- "1.7.5"
- "1.10.7"
tasks:
- debug: msg="{{ item }} is newer than {{ version_installed }}"
loop: "{{ versions }}"
when: item is version(version_installed, '>')
> ansible-playbook test-versions.yml | grep msg
"msg": "1.10.7 is newer than 1.10.1"
答案 1 :(得分:0)
现在已经以另一种方式解决了。我没有对版本进行排序,而是将当前版本与所有可用版本进行了比较。
仅当update变量为true时,才执行备份任务。
- name: Get package version
yum:
list: package
register: software_version
- name: Read which version is installed and available
set_fact:
software_update: false
software_version_installed: "{{ software_version | json_query(\"results[?yumstate=='installed'].version\") | last }}"
software_version_available: "{{ software_version | json_query(\"results[?yumstate=='available'].version\") }}"
- name: Check if upgrade is needed
set_fact:
software_update: true
when: software_version_installed is version(item, "<")
with_items: "{{ software_version_available }}"
- name: Backup old database file on remote host
copy:
src: "{{ software.database_path }}"
dest: "{{ software.database_path }}_{{ ansible_date_time.date }}_v{{ software_version_installed }}"
remote_src: yes
when: software_update