标签 ansible 下的文章

新手学习教程:
https://www.w3cschool.cn/automate_with_ansible

官方文档:
https://docs.ansible.com/

安装:

yum install -y ansible

配置文件:/etc/ansible/hosts (例子:https://www.w3cschool.cn/automate_with_ansible/automate_with_ansible-1khc27p1.html)

#ansible_ssh_host
#ansible_ssh_port
#ansible_ssh_user
#ansible_ssh_pass
#ansible_ssh_private_key_file

[dev]
192.168.0.200 ansible_ssh_port=123456

[online]
pc1 ansible_ssh_host=192.168.0.200 ansible_ssh_user=root ansible_ssh_port=123456

若有对 Control Machine 本机操作的需求,建议于 /etc/ansible/hosts 补上 local 的设定。

# For root user.
$ /bin/echo -e "[local]\nlocalhost ansible_connection=local" >> /etc/ansible/hosts

# For sudo user.
$ sudo su -c '/bin/echo -e "[local]\nlocalhost ansible_connection=local" >> /etc/ansible/hosts'

Hello World
当已上的设置都完成了,您可以试著在终端机里用 Ansible 呼叫本机印出 Hello World。

$ ansible dev -m command -a 'echo Hello World.'
localhost | SUCCESS | rc=0 >>
Hello World.

欢迎来到 Ansible 的世界!:D

如果遇到第一次连接会检查是否有链接过的记录时,可能需要把下面这个设置启用(不检查):
Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host.

配置:/etc/ansible/ansible.conf

host_key_checking = False 

实操技巧:
使用剧本的时候 -e :

# 多个变量间用空格隔开,遇到值有空格时用引号
ansible-playbook xxx.yml -e "var1=val1 var2=val2 var3='val val'"

# 将参数写到文件中,再引用,文件内容格式为json: {"a":"123", "b": "321"}
ansible-playbook xxx.yml -e "@path/to/file"

# 刷本中写变量,-e 传入的变量会覆盖的, xxx.yml:
- name: xxx
  hosts: xxx
  vars_files:
    - xxx.json
  vars:
    a: 123
    b: 321

上传文件的时候,可能需要上传多个文件,怎么写:

tasks:
    - name: upload cert files
      copy: src={{ item.src }} dest={{ item.dest }}
      with_items:
        - { src: '/root/site/{{ mark }}.key', dest: '/data/cert/{{ mark }}.key' }
        - { src: '/root/site/{{ mark }}.pem', dest: '/data/cert/{{ mark }}.pem' }