在Ubuntu中使用Ansible安装Apache和Certbot

146次阅读
没有评论

问题描述

提出了一个关于在Ubuntu中使用Ansible安装Apache和Certbot的问题,他已经有了一段使用命令行的代码,并想将其转换成Ansible代码。但是他遇到了一个问题,命令中的sudo letsencrypt --apache需要用户交互,并且他希望能够在Ansible的清单文件中指定网站和电子邮件。

解决方案

请注意以下操作注意版本差异及修改前做好备份。

使用Ansible Role(推荐)

在这个问题中,有一个更简单的解决方案是使用Ansible Galaxy上现有的角色,如https://galaxy.ansible.com/030/certbot/。这是一个专门为Certbot设计的角色,可以在Ansible中轻松安装和配置Certbot。

以下是使用Ansible Galaxy角色的步骤:
1. 使用ansible-galaxy命令来安装Certbot角色(如果尚未安装):
shell
ansible-galaxy install 030.certbot

2. 创建一个Ansible Playbook,使用刚刚安装的Certbot角色,同时设置网站和电子邮件变量。示例如下:
yaml
- name: Install Apache and Certbot
hosts: your_target_hosts
become: yes
roles:
- name: 030.certbot
vars:
certbot_admin_email: your@email.com
certbot_domain: www.web.tk

请替换your_target_hosts为目标主机,your@email.com为你的电子邮件地址,www.web.tk为你的网站域名。

手动转换成Ansible

如果你坚持手动转换你的代码为Ansible,以下是需要注意的几点:

  1. sudo letsencrypt --apache命令中,使用--agree-tos--noninteractive选项以禁用用户交互。这样Certbot不会询问用户是否同意服务条款。
  2. 使用apt_repository模块来添加Certbot的PPA源。
  3. 使用apt模块来安装Apache和Certbot。
  4. 确保在Ansible的清单文件中设置网站和电子邮件变量。

以下是一个示例的Ansible Playbook,将上述步骤转换成Ansible代码:

- name: Install Apache and Certbot
  hosts: your_target_hosts
  become: yes
  tasks:
    - name: Add Certbot PPA repository
      apt_repository:
        repo: 'ppa:certbot/certbot'

    - name: Install required packages
      apt:
        name: "{{ item }}"
        update_cache: yes
      with_items:
        - apache2
        - python-letsencrypt-apache
        - python-software-properties
        - software-properties-common
        - python-certbot-apache

    - name: Disable user interaction for Certbot
      command: >
        certbot --apache
        --agree-tos
        --noninteractive
        --email your@email.com
        --webroot-path /var/www/html
        -d www.web.tk

请替换your_target_hosts为目标主机,your@email.com为你的电子邮件地址,www.web.tk为你的网站域名。

注意事项

  • 以上示例中的your_target_hosts需要替换为你的目标主机,确保Ansible可以连接到这些主机。
  • 需要在执行操作前备份服务器上的相关数据,以防万一。

以上是解决在Ubuntu中使用Ansible安装Apache和Certbot的方案。如果你遇到问题或需要进一步帮助,请随时提问。

正文完