sudo yum install epel-release
sudo yum install ansible
sudo apt update
sudo apt install software-properties-common
sudo apt-add-repository --yes --update ppa:ansible/ansible
sudo apt install ansible
sudo pip install ansible
ansible --version
mkdir -p ~/ansible/{inventory,group_vars,host_vars,roles,playbooks}
编辑 /etc/ansible/ansible.cfg
或创建 ~/.ansible.cfg
:
[defaults]
inventory = ~/ansible/inventory/hosts
remote_user = root
private_key_file = ~/.ssh/id_rsa
host_key_checking = False
创建 ~/ansible/inventory/hosts
文件:
[web_servers]
web1.example.com ansible_host=192.168.1.10
web2.example.com ansible_host=192.168.1.11
[db_servers]
db1.example.com ansible_host=192.168.1.20
[all:vars]
ansible_python_interpreter=/usr/bin/python3
ansible all -m ping
创建 ~/ansible/playbooks/first_playbook.yml
:
---
- name: My first playbook
hosts: web_servers
become: yes
tasks:
- name: Ensure Nginx is installed
apt:
name: nginx
state: present
when: ansible_os_family == "Debian"
- name: Ensure Nginx is running
service:
name: nginx
state: started
enabled: yes
ansible-playbook ~/ansible/playbooks/first_playbook.yml
ansible-vault create ~/ansible/group_vars/production/vault.yml
cd ~/ansible/roles
ansible-galaxy init nginx
sudo pip install boto3
问题1: SSH连接失败 - 确保SSH密钥已正确配置 - 检查目标主机的SSH服务是否运行 - 验证防火墙设置
问题2: Python解释器问题 - 在Inventory文件中指定正确的Python路径 - 确保目标主机安装了Python
问题3: 权限问题
- 使用become: yes
提升权限
- 配置正确的sudo权限
通过以上步骤,您应该能够在Linux系统上成功配置和使用Ansible进行自动化部署。