Skip to content

Ansible 2.9 的使用

按照官方推荐,尽量使用 ansible 的内置模块
所有模块地址:https://docs.ansible.com/ansible/2.9/modules/list_of_all_modules.html

1. 配置文件

  • 配置文件名称:ansible.cfg
  • 示例内容:
ini
[defaults]
inventory=./hosts

# 指定 hosts
inventory=./hosts

# 指定私钥文件
private_key_file=.ssh/id_rsa_op

# 关闭新机器的 yes/no 确认
host_key_checking=False

2. 常用模块与插件

shell - 执行 shell 命令

https://docs.ansible.com/ansible/2.9/modules/shell_module.html

yaml
- hosts: all
  remote_user: root
  gather_facts: no
  tasks:
  
  - name: restart service
    shell: cd /data/www && git pull && pm2 restart 0
    
  - name: git pull
    shell:
      cmd: git reset --hard && git pull
      chdir: /data/www

copy - 拷贝文件到远程

https://docs.ansible.com/ansible/2.9/modules/copy_module.html

  • 拷贝本地或远程文件到远程;默认是从本地到远程,可通过 remote_src 参数来指定
yaml
- hosts: all
  remote_user: root
  gather_facts: no
  tasks:

  - name: cp nginx conf
    copy:
      src: ./nginx.conf
      dest: /etc/nginx/conf.d/python-abc.xyz.conf

register - 注册变量

https://docs.ansible.com/ansible/2.9/user_guide/playbooks_variables.html#registering-variables

yaml
  - name: nginx test
    shell: nginx -t
    register: nginx_test

  - name: nginx reload
    shell: nginx -s reload
    when: nginx_test.rc == 0

ignore_errors - 忽略报错

https://docs.ansible.com/ansible/2.9/user_guide/playbooks_error_handling.html#ignoring-failed-commands

yaml
  - name: set PasswordAuthentication to no
    lineinfile:
      path: /etc/pam.d/system-auth
      regexp: '^password    requisite'
      line: 'password    requisite     am_cracklib.so retry=3 difok=3 minlen=10 ucredit=-1 lcredit=-2 dcredit=-1 ocredit=-1'
    # ubuntu 中没有 /etc/pam.d/system-auth 这个文件,所以这个忽略错误
    ignore_errors: yes

lineinfile - 修改文件单行

https://docs.ansible.com/ansible/2.9/modules/lineinfile_module.html

  • 用于修改文件中的其中一行数据,不适用多行
  • state=absent (state: absent)可用于删除匹配行
  • 插入匹配行前后使用 insertbefore 和 insertafter
yaml
- hosts: all
  remote_user: root
  gather_facts: no
  tasks:

  - name: set PASS_MAX_DAYS to 150
    lineinfile:
      path: /etc/login.defs
      # 如果匹配不到,则会添加一行
      regexp: '^PASS_MAX_DAYS'
      line: 'PASS_MAX_DAYS   150'

  - name: set PasswordAuthentication to no
    lineinfile:
      path: /etc/ssh/sshd_config
      regexp: '^PasswordAuthentication'
      line: 'PasswordAuthentication no'

service - 服务管理

https://docs.ansible.com/ansible/2.9/modules/service_module.html

  • started stopped restarted reloaded
yaml
  - name: restart sshd
    # shell: service sshd restart
    service:
      name: sshd
      state: restarted

lookup - 本地查找

https://docs.ansible.com/ansible/2.9/plugins/lookup.html

yaml
- hosts: all
  remote_user: root
  gather_facts: no

  vars:
    # 读取 pub 文件内容到 sshkey 变量
    sshkey: "{{ lookup('file', '/home/op/.ssh/jumpserver.pub') }}"

  tasks:

  - debug:
      msg: "{{ sshkey }}"

  - name: add jumpserver sshkey
    lineinfile:
      path: /root/.ssh/authorized_keys
      line: "{{ sshkey }} # 堡垒机"

file - 文件目录属性,软链,删除

https://docs.ansible.com/ansible/2.9/modules/file_module.html

yaml
- hosts: all
  tasks:

  - name: 创建 node 目录
    file:
      path: /usr/local/node
      state: directory

  - name: 创建软链
    file:
      src: '/usr/local/node/node-v14.4.0-linux-x64/bin/{{ item }}'
      dest: '/usr/bin/{{ item }}'
    loop:
      - node
      - npm
      - npx

npm / yum - 安装

yaml
  - name: 安装 pm2
    npm:
      name: pm2
      global: yes

  - name: Install a list of packages with a list variable
    yum:
      name: "{{ packages }}"
    vars:
      packages:
      - httpd
      - httpd-tools
      
  - name: Install the latest version of Apache
    yum:
      name: httpd
      state: latest

unarchive - 拷贝并解压

https://docs.ansible.com/ansible/2.9/modules/unarchive_module.html

  • 默认会将本地压缩包拷贝到远程服务器上
yaml
  - name: 拷贝软件并解压
    unarchive:
      src: /home/op/ansible/package/node-v14.4.0-linux-x64.tar.xz
      dest: /usr/local/node/

systemd - 控制远程主机上的 systemd 服务

https://docs.ansible.com/ansible/2.9/modules/systemd_module.html

yaml
- name: Make sure a service is running
  systemd:
    state: started
    name: httpd

- name: stop service cron on debian, if running
  systemd:
    name: cron
    state: stopped

3. playbook.yml 文件内容示例

安装 prometheus 的 node_exporter

yaml
- hosts: all
  remote_user: root
  gather_facts: no

  tasks:

  - name: 拷贝安装包并解压
    unarchive:
      src: node_exporter-1.0.1.linux-amd64.tar.gz
      dest: /usr/local/

  - name: 重命名
    shell:
      cmd: mv node_exporter-1.0.1.linux-amd64 node_exporter
      chdir: /usr/local/

  - name: 拷贝 node_exporter.service 文件到远程
    copy:
      src: node_exporter.service
      dest: /etc/systemd/system/

  - name: 设置开机自启
    systemd:
      name: node_exporter
      enabled: yes

  - name: 启动
    systemd:
      state: started
      name: node_exporter
      daemon_reload: yes
txt
.
├── ansible.cfg
├── hosts
├── node_exporter-1.0.1.linux-amd64.tar.gz
├── node_exporter.service
└── playbook.yml

0 directories, 5 files
ini
Description=node_exporter
After=network-online.target

[Service]
Restart=on-failure
ExecStart=/usr/local/node_exporter/node_exporter

[Install]
WantedBy=multi-user.target

安装 nginx

yaml
- hosts: all
  remote_user: root
  gather_facts: no

  tasks:

    - name: add group
      group:
        name: nginx

    - name: add user
      user:
        name: nginx
        groups: nginx
        shell: /sbin/nologin
        create_home: no

    - name: yum packages
      yum:
        name: "{{item}}"
      with_items:
        - GeoIP
        - GeoIP-devel
        - GeoIP-data
        - libxslt-devel
        - gd-devel

    - name: creates directory
      file:
        path: /data/logs/nginx
        state: directory

    - name: copy nginx
      unarchive:
        src: files/nginx.tar.gz
        dest: /data

    - name: link nginx
      file:
        src: /data/nginx/sbin/nginx
        dest: /usr/sbin/nginx
        state: link

    - name: link nginx_conf
      file:
        src: /data/nginx/conf
        dest: /etc/nginx
        state: link

    - name: nginx log cut crontab
      cron:
        name: "log cut"
        job: "/bin/bash /data/nginx/script/nginxlog_cut.sh"
        hour: 0
        minute: 0
        state: present

    - name: copy nginx.service
      copy:
        src: files/nginx.service
        dest: /usr/lib/systemd/system/nginx.service

    - name: systemctl nginx
      shell:
        cmd: "systemctl daemon-reload && systemctl enable nginx"