ansible 时间同步 实例

目录结构

hosts
deployment
    - timesyncclient.yml
roles
    - timesyncclient
        - tasks
              -main.yml
        - templater
        - files

vim hosts

[timesyncclient]
192.168.106.130 hostname=rocky90-106-130
[aliyuan]
192.168.106.130 hostname=rocky90-106-130
[init]
192.168.106.130 hostname=rocky90-106-130

[all:vars]
ansible_ssh_user=root
ansible_ssh_pass=kc@123456
ansible_ssh_port=22

deployment/timesyncclient.yml

---
- hosts: timesyncclient
  sudo: yes
  roles: 
    - ../roles/timesyncclient

vim roles/timesyncclient/tasks/main.yml

---
### 安装并配置 chrony 客户端
########### to centos or rockylinux #############
# 安装
- name: Cenots7.x_Rocky9.x_install_chrony
  yum:
    name: chrony
    state: present
  when: ansible_distribution=="CentOS" or ansible_distribution=="Rocky"
# 删除^pool.*行
- name: Cenots7.x_Rocky9.x_delete_chrony.conf '^pool.*' string line
  lineinfile:
    path: /etc/chrony.conf
    regexp: '^pool.*'
    state: absent
   when: ansible_distribution=="CentOS" or ansible_distribution=="Rocky"
# 删除行server.*行
- name: Cenots7.x_Rocky9.x_delete_chrony.conf '^server.*' string line
  lineinfile:
    path: /etc/chrony.conf
    regexp: '^server.*'
    state: absent
  when: ansible_distribution=="CentOS" or ansible_distribution=="Rocky"
# 添加时间时间服务器
- name: Cenots7.x_Rocky9.x_add_time_server TIME_SERVER1 and TIME_SERVER2
  lineinfile:
    path: /etc/chrony.conf
    insertafter: '^# Please consider .*'
    line: "server {{ time_sync_service_url_1 }} iburst\nserver {{ time_sync_service_url_2 }} iburst"
  when: ansible_distribution=="CentOS" or ansible_distribution=="Rocky"
# 重启 chrony 服务
- name: Cenots7.x_Rocky9.x_restart_chrony_service
  service:
    name: chronyd
    state: restarted
    enabled: yes

############### to ubuntu server ##################
# 删除锁文件
- name: Ubuntu_delete_lock_files
  file:
    path: "{{ item }}"
    state: absent
  loop:
    - /var/lib/dpkg/lock
    - /var/lib/apt/lists/lock
    - /var/cache/apt/archives/lock
  when: ansible_distribution=="Ubuntu"
# 更新源
- name: Ubuntu_apt_update
  apt:
    update_cache: yes 
    force: yes 
  when: ansible_distribution=="Ubuntu"
# 安装
- name: Ubuntu_install_chrony
  apt:
    name: chrony
    force: yes
  when: ansible_distribution=="Ubuntu"
# 删除^pool.*行
- name: Ubuntu_delete_chrony.conf '^pool.*' string line
  lineinfile:
    path: /etc/chrony/chrony.conf
    regexp: '^pool.*'
    state: absent
  when: ansible_distribution=="Ubuntu"
# 添加时间时间服务器
- name: Ubuntu_add_time_server TIME_SERVER1 and TIME_SERVER2
  lineinfile:
    path: /etc/chrony.conf
    insertafter: '^# Please consider .*'
    line: "server {{ time_sync_service_url_1 }} iburst\nserver {{ time_sync_service_url_2 }} iburst"
# 开机启动 chronyd
- name: start chronyd
  systemd:
    name: chronyd
    state: restarted
    #state: started
    enabled: yes

执行命令

ansible-playbook -i hosts deployment/timesyncclient.yml

posted on 2025-10-28 11:24  luokeli  阅读(0)  评论(0)    收藏  举报

导航