案例:升级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

copyyum模块不能使用notify,而command模块可以使用notify

建议不要使用rm命令,改为使用file模块的state=absent,因为执行时候有提示 [WARNING]: Consider using file module with state=absent rather than running rm

改进后的playbook

删除目录下多个文件的技巧

参考ansible - delete unmanaged files from directory?,解决的方法是先ls目录下文件,将得到的文件存入变量,然后用这个变量来做absent

从远程目录下载多个文件

How to fetch multiple files from remote machine to local with Ansible也是用了相似的方式,将远程目录下多个文件下载到本地

另外,synchronise module使用了rsync来

创建远程目录

How to create a directory using Ansible?

更多file模块选项

rpm安装

前例中设置了安装EPEL以便安装必要的第三方软件包

执行

sudo

如果ansible的控制台登录到被管理服务器上的帐号是非root的其他帐号,如admin,需要通过sudo指令来执行系统程序安装,则需要在ansible的playbook中设置使用sudo: true

参考通过sudo安装rpm包

参考

Last updated

Was this helpful?