ansible工作目录

下面是整理后、结构清晰的 Ansible 全局配置及环境变量使用文档,便于阅读和参考。


Ansible 全局配置与环境变量说明

1. 配置文件路径优先级

Ansible 会按以下顺序查找并使用配置文件:

优先级配置文件路径说明
1 当前目录 ./ansible.cfg 运行命令时优先查找
2 用户家目录 ~/.ansible.cfg 当前目录无配置时使用
3 系统级 /etc/ansible/ansible.cfg 最后查找全局默认配置

2. ansible.cfg 配置示例

[defaults]
# 全局默认设置
remote_tmp = /tmp/ansible/            # 远程临时目录
remote_user = tiantao01               # 默认远程用户
inventory = /etc/ansible/hosts        # Inventory 文件路径
pipelining = True                     # 是否启用 pipelining 加速

[ssh_connection]
# SSH 连接相关设置
control_path_dir = /home/tiantao01/ansible/cp
ssh_args = -o ControlMaster=auto -o ControlPersist=60s

3. 环境变量覆盖配置

Ansible 支持通过环境变量覆盖配置文件中的设置。常用环境变量示例如下:

export ANSIBLE_REMOTE_USER=tiantao01
export ANSIBLE_REMOTE_TMP=/tmp/ansible/
export ANSIBLE_SSH_CONTROL_PATH_DIR=/home/tiantao01/ansible/cp

# 运行 ansible 命令时自动生效
ansible all -m ping

常用环境变量与对应配置参数

环境变量ansible.cfg 参数说明
ANSIBLE_REMOTE_USER remote_user 默认远程登录用户
ANSIBLE_REMOTE_TMP remote_tmp 远程临时目录
ANSIBLE_SSH_CONTROL_PATH control_path_dir SSH 控制套接字目录
ANSIBLE_CONFIG - 指定自定义 ansible.cfg 路径

4. 配置生效优先级总结

优先级配置方式说明
1 命令行参数 ansible all -u tiantao01
2 环境变量 ANSIBLE_REMOTE_USER
3 当前目录 ansible.cfg 项目目录配置
4 用户家目录 ~/.ansible.cfg 用户级配置
5 系统级 /etc/ansible/ansible.cfg 全局默认配置

5. 验证配置生效

方法1:查看当前生效的配置项(只显示有改动的)

ansible-config dump --only-changed

示例输出:

DEFAULT_REMOTE_USER(env: ANSIBLE_REMOTE_USER) = tiantao01
DEFAULT_REMOTE_TMP(env: ANSIBLE_REMOTE_TMP) = /tmp/ansible/

方法2:查看 Ansible 使用的配置文件路径

ansible --version

示例输出:

ansible [core 2.12.3]
  config file = /etc/ansible/ansible.cfg  # 当前生效配置文件路径

6. Inventory 文件中常用变量示例

可以在 Inventory 文件中为主机或组定义参数,覆盖全局配置:

[all]
server1 ansible_host=192.168.0.1 ansible_ssh_user=xx ansible_ssh_pass=@12345678 ansible_sudo_user=root ansible_ssh_extra_args='-o StrictHostKeyChecking=no' ansible_remote_tmp=/tmp/ansible/ ansible_ssh_control_path_dir=/tmp/ansible/ ansible_pipelining=True
变量名说明
ansible_ssh_user SSH 登录用户
ansible_ssh_pass SSH 密码(建议使用 vault 管理)
ansible_sudo_user sudo 切换用户
ansible_ssh_extra_args SSH 额外参数
ansible_remote_tmp 远程临时目录
ansible_ssh_control_path_dir SSH 控制套接字目录
ansible_pipelining 是否开启 pipelining

7. 目录权限建议

确保你指定的目录存在且权限正确:

mkdir -p /home/tiantao01/ansible/cp /tmp/ansible/
chmod 700 /home/tiantao01/ansible/cp
chmod 777 /tmp/ansible/

8. 总结配置示例(ansible.cfg)

[defaults]
remote_tmp = /tmp/ansible/
remote_user = xx
inventory = /etc/ansible/hosts
pipelining = True

[ssh_connection]
control_path_dir = /tmp/ansible/
ssh_args = -o StrictHostKeyChecking=no

如果你需要,我也可以帮你写一个完整的示例文件或脚本来生成这些配置。需要告诉我!

posted on 2025-08-04 14:43  吃草的青蛙  阅读(17)  评论(0)    收藏  举报

导航