中文文档:http://www.ansible.com.cn/docs/intro_installation.html#apt-ubuntu
sudo apt update
sudo apt-get install ansible
安装成功后,执行命令验证 ansible
的版本
ansible --version
ansible默认的主配置文件位置:
/etc/ansible/ansible.cfg
ansible主机清单:/etc/ansible/hosts
如果没有的话需要自行创建
mkdir demo
cd ~/demo
wget https://raw.githubusercontent.com/ansible/ansible/stable-2.9/examples/ansible.cfg
[defaults]
inventory = /home/demo/inventory
host_key_checking = False
[privilege_escalation]
become=True
become_method=sudo
become_user=root
become_ask_pass=False
inventory
文件vim inventory
// 本地测试,只添加本机localhost
[local]
localhost ansible_connection=local
ansible --version
ansible all -m ping
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that
the implicit localhost does not match 'all'
原因是没有默认的inventory
,需要指定-i
选项来明确指定主机文件的位置
ansible all -m ping -i ~/demo/inventory
ls -l ~/demo/inventory
yaml
文件作为剧本vim demo.yaml
---
- hosts: local
name: local test
tasks:
- name: Check disk usage
command: df -h
ansible-playbook
命令运行剧本ansible-playbook demo.yml
报错"module_stderr": "sudo: a password is required\n"
在ansible
中执行需要提升权限的任务时需要sudo
权限,但是没有提供密码
修改yaml
文件,添加权限指定sudo密码
---
- hosts: local
name: local test
become: true
become_method: sudo
vars:
ansible_become_password: xxxxxx
tasks:
- name: Check disk usage
command: df -h
https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_privilege_escalation.html
---
- hosts: local
name: local test
become: true
become_method: sudo
vars:
ansible_become_password: 123456
tasks:
- name: Check disk usage
command: df -h
register: disk_usage # 注册变量以存储命令输出
- name: Show disk usage
debug:
msg: "{{ disk_usage.stdout_lines }}" # 使用debug模块显示输出
ansible-vault create secret.yml
ansible_become_password: your_password
查看创建后的文件内容
---
- hosts: local
name: local test
become: true
become_method: sudo
vars_files:
- secret.yaml
tasks:
- name: Check disk usage
command: df -h
register: disk_usage # 注册变量以存储命令输出
- name: Show disk usage
debug:
msg: "{{ disk_usage.stdout_lines }}" # 使用debug模块显示输出
--ask-vault-pass
运行playbook
ansible-playbook demo.yaml --ask-vault-pass