案例:升级CentOS操作系统
说明
安装完CentOS之后首次升级整个操作系统,不过,升级前先修改repo配置,确保改成正确的版本
修改配置文件
对于简单的配置文件修改可以采用复制方法,复杂的替换需要使用模块。
参考 Which is the best way to make config changes in conf files in ansible
使用
command模块执行命令(复杂命令使用shell模块)使用
yum模块进行升级
初步的playbook
- hosts: new
tasks:
- name: clean no need repo config
command: rm -f /etc/yum.repos.d/*
notify:
- Remove all old repo config
- name: cp rhel.repo
copy: src=rhel.repo dest=/etc/yum.repos.d/rhel.repo owner=root group=root mode=0644
- name: upgrade all packages
yum: name=* state=latest
copy和yum模块不能使用notify,而command模块可以使用notify建议不要使用
rm命令,改为使用file模块的state=absent,因为执行时候有提示[WARNING]: Consider using file module with state=absent rather than running rm
改进后的playbook
- hosts: new
tasks:
- shell: ls -1 /etc/yum.repos.d
register: contents
- file: path=/etc/yum.repos.d/{{ item }} state=absent
with_items: contents.stdout_lines
- name: cp rhel.repo
copy: src=rhel.repo dest=/etc/yum.repos.d/rhel.repo owner=root group=root mode=0644
- name: upgrade all packages
yum: name=* state=latest
- name: cp epel.rpm
copy: src=epel-release-latest-7.noarch.rpm dest=/tmp/epel-release-latest-7.noarch.rpm
- name: Install package.
yum:
name: /tmp/epel-release-latest-7.noarch.rpm
state: present删除目录下多个文件的技巧
参考ansible - delete unmanaged files from directory?,解决的方法是先ls目录下文件,将得到的文件存入变量,然后用这个变量来做absent
- shell: ls -1 /some/dir
register: contents
- file: path=/some/dir/{{ item }} state=absent
with_items: contents.stdout_lines
when: item not in managed_files从远程目录下载多个文件
How to fetch multiple files from remote machine to local with Ansible也是用了相似的方式,将远程目录下多个文件下载到本地
- shell: (cd /remote; find . -maxdepth 1 -type f) | cut -d'/' -f2
register: files_to_copy
- fetch: src=/remote/{{ item }} dest=/local/
with_items: files_to_copy.stdout_lines另外,synchronise module使用了rsync来
创建远程目录
- name: Creates directory
file: path=/src/www state=directoryrpm安装
- name: Copy rpm file to server
copy:
src: package.rpm
dest: /tmp/package.rpm
- name: Install package.
yum:
name: /tmp/package.rpm
state: present前例中设置了安装EPEL以便安装必要的第三方软件包
执行
ansible-playbook upgrade_centos.yml -f 10sudo
如果ansible的控制台登录到被管理服务器上的帐号是非root的其他帐号,如admin,需要通过sudo指令来执行系统程序安装,则需要在ansible的playbook中设置使用sudo: true
- name: upgrade all packages
sudo: true
yum: name=* state=latest参考
Last updated
Was this helpful?