安装完CentOS之后首次升级整个操作系统,不过,升级前先修改repo配置,确保改成正确的版本
- 修改配置文件
对于简单的配置文件修改可以采用复制方法,复杂的替换需要使用模块。
参考 Which is the best way to make config changes in conf files in ansible
- 使用
command
模块执行命令(复杂命令使用shell
模块) - 使用
yum
模块进行升级
- 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
- 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=directory
- 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 10
如果ansible的控制台登录到被管理服务器上的帐号是非root
的其他帐号,如admin
,需要通过sudo
指令来执行系统程序安装,则需要在ansible
的playbook中设置使用sudo: true
- name: upgrade all packages
sudo: true
yum: name=* state=latest