ansible入门指南 - ansible的常用命令

ansible的常用命令

运行ansible命令的时候会使用 ansible.cfg 配置文件
配置文件优先级为 ANSIBLE_CONFIG 指定的文件 > ~/.ansible.cfg > /etc/ansible/ansible.cfg

ansible

ansible命令可以用来运行 ad-hoc 指令

ansible-config

配置文件相关的功能, 可以运行以下命令生成一个默认的配置文件

ansible-config init --disabled > ansible.cfg

ansible-console

交互式的解释器, 用来指向ansible tasks, 可以用来同时在多个服务器上执行同一个命令

(base) ➜ chino@chino-igs  ~/examples/ansible  ansible-console -i inventory.yaml all
Welcome to the ansible console. Type help or ? to list commands.

chino@all (3)[f:5]$ echo $USER
tomcat | CHANGED | rc=0 >>
chino
tomcat2 | CHANGED | rc=0 >>
chino
tomcat1 | CHANGED | rc=0 >>
chino
chino@all (3)[f:5]$ pwd
tomcat1 | CHANGED | rc=0 >>
/home/chino
tomcat2 | CHANGED | rc=0 >>
/home/chino
tomcat | CHANGED | rc=0 >>
/home/chino
chino@all (3)[f:5]$

也可以使用--become-user, 在所有机器上同时以root用户身份执行任务


(base) ➜ chino@chino-igs  ~/repos/examples/ansible  ansible-console -i inventory.yaml all --become-user root --become
Welcome to the ansible console. Type help or ? to list commands.

chino@all (3)[f:5]# whoami
tomcat | CHANGED | rc=0 >>
root
tomcat2 | CHANGED | rc=0 >>
root
tomcat1 | CHANGED | rc=0 >>
root
chino@all (3)[f:5]#

ansible-doc

ansible-doc 命令用来查看模块的信息

# 查看user模块的输入输出
ansible-doc user
# 查看user模块的playbook片段
ansible-doc -s user

ansible-galaxy

用来操作role或者collection

ansible-inventory

查看inventory信息

(base) ➜ chino@chino-igs  ~/repos/examples/ansible  ansible-inventory -i inventory.yaml --graph
@all:
  |--@ungrouped:
  |--@prod:
  |  |--tomcat1
  |  |--tomcat2
  |--@uat:
  |  |--tomcat

ansible-playbook

在目标主机上执行指定的playbook

ansible-pull

一般用于机器从远程代码库上拉playbook, 然后本地执行. 可以用来执行定期巡检任务

ansible-pull -i localhost, -U git@xxx.com:test/test.git playbook.yaml

ansible-vault

用于加密变量文件, 保护密码等敏感信息

# 创建加密的vars.yaml文件, 按照提示输入密码
ansible-vault create vars.yaml
# 查看加密的文件内容
ansible-vault view vars.yaml
# 解密文件
ansible-vault decrypt vars.yaml
# 加密变量, password保存密码
ansible-vault encrypt_string --vault-password-file password "testencryptstr" --name myencstr
# 输出
Encryption successful
myencstr: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          35333334383837333233616438623739376331303739636331613663363563306439326461303366
          6464336536613431386432613366613565316466653937630a613961616263613835636264313131
          30616538393337343862666163336366306138623534316665396365323939633565313164666236
          6561396537383738350a653634386237646537356435643136623133323234646135383566343434
          3834
# 输出的变量保存到myencvar.yaml文件中, 然后运行下面的命令解密字符串
ansible localhost -m ansible.builtin.debug -a var="myencstr" -e "@myencvar.yaml" --vault-id password
# 输出结果
[WARNING]: No inventory was parsed, only implicit localhost is available
localhost | SUCCESS => {
    "myencstr": "testencryptstr"
}
posted @ 2023-08-18 16:13  Chinor  阅读(308)  评论(0编辑  收藏  举报