压箱底的Ansible使用小技巧
2023-06-23 本文已影响0人
小餐包
var code = "ee730933-4cef-4440-95ca-b44eee8b2b9e"
配置
可以在当前项目目录下或者 /etc/ansible
目录下创建一个 ansible.cfg
,配置如下:
[defaults]
# 设置fact的收集方式及过期时间
# gathering = batch
# fact_caching_timeout = 86400
# 指定fact缓存的实现方式并加速其收集速度
# fact_caching = jsonfile
# fact_caching_connection = /tmp/ansible_fact_cache
# 开启日志
# log_path=/path/to/logfile
# 如果你对每个任务的执行时长有兴趣,可以开启下面的开关
# callback_whitelist = profile_tasks
# 默认的json输出可读性不如这个,这个是强烈推荐的配置
stdout_callback = debug
# 同时并发执行的host个数,默认是3
# forks = 30
FAQ
如何在本地执行任务
有时你可能需要在本地执行某个特定任务(比如任务调试或者不希望到处安装依赖包时)可以使用delegate_to
语句:
- name: install pymysql to use mysql_db module
pip: pymysql
delegate_to: localhost
- name: create a new database with name "test"
mysql_db:
database: demo
state: present
delegate_to: localhost
当变量未赋值时给出提示
可以使用vars_prompt
, 比如:
---
- name: test_prompt_variable
hosts: localhost
vars_prompt:
- name: build_number
prompt: input the build number
private: no
when: build_number is not defined
default: 1.1.0
roles:
- database
使用SSH KEY的方式登录主机以避免在每次登录时输入密码
# 使用ssh-keygen的生成一对密钥对,密钥文件通常保存在~/.ssh/目录下以id_rsa和id_rsa.pub命名,带pub后缀的时公钥
ssh-keygen
# 使用如下方式将公钥添加到远程主机的authorized_keys文件中
ssh-copy-id -i ~/.ssh/mykey user@host -p port
使用命令行执行特定模块
# syntax
ansible <pattern-of-hosts> -i [hosts-file] -e <environment setting> -m <module> -a <arguments of module>
# e.g.
ansible web -i myhosts -e '{"ansible_port":12345, "ansible_user":"myuser"}' -m shell -a "pwd"
务必掌握的几个常见模块
文件相关
fetch:从host下载文件到本地
例子:
- name: Storing in a path relative to the playbook
fetch:
src: /tmp/uniquefile
dest: special/prefix-{{ inventory_hostname }}
flat: yes
copy:从本地拷贝文件到host
例子:
- name: Copy file with owner and permission, using symbolic representation
copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: u=rw,g=r,o=r
template:讲本地的模板文件拷贝到host
例子:
- name: Copy a version of named.conf that is dependent on the OS. setype obtained by doing ls -Z /etc/named.conf on original file
template:
src: named.conf_{{ ansible_os_family}}.j2
dest: /etc/named.conf
group: named
setype: named_conf_t
mode: 0640
执行
script:执行脚本文件
- name: Run a script using an executable in a system path
script: /some/local/script.py
args:
executable: python3
command:执行特定命令
- name: Change the working directory to somedir/ and run the command as db_owner if /path/to/database does not exist.
command: /usr/bin/make_database.sh db_user db_name
become: yes
become_user: db_owner
args:
chdir: somedir/
creates: /path/to/database
shell:执行特定shell命令
- name: This command will change the working directory to somedir/
ansible.builtin.shell:
cmd: ls -l | grep log
chdir: somedir/
shell和command模块很多时候可以互换,区别在于:command模块更加安全且高效,是官方推崇的方式,但是不支持shell特有的诸如管道的语法。
推荐读物
-
Ansible: Up and running, 2nd Edition
-
Ansible官方教程