Ansible¶
Install Ansible¶
sudo apt-get install ansible
Setup SSH Keys¶
Generate SSH keys using ssh-keygen
Hosts¶
Ansible resolves hostnames used in playbooks into IP addresses using the hosts file: /etc/ansible/hosts
Edit the hostname file: sudo nano /etc/ansible/hosts
Format:
[group_name]
<alias> ansible_ssh_host=<ip_address>
- Examples:
- Ping all known servers:
ansible -m ping all
ansible -m ping droplets
ansible -m ping host1
ansible -m ping host1:host2
- Ping all known servers:
Example Plyabook¶
---
- hosts: droplets
tasks:
- name: Installs nginx web server
apt: pkg=nginx state=installed update_cache=true
notify:
- start nginx
- name: Upload default index.html for host
copy: src=static_files/index.html dest=/usr/share/nginx/www/ mode=0644
handlers:
- name: start nginx
service: name=nginx state=started
We can then make a directory called static_files in our current directory and place an index.html file inside.
mkdir static_files nano static_files/index.html Inside of this file, let’s just create a basic html structure:
<html>
<head>
<title>This is a sample page</title>
</head>
<body>
<h1>Here is a heading!</h1>
<p>Here is a regular paragraph. Wow!</p>
</body>
</html>
Pass arguments ansible -m apt -a 'whatever' all
running plyabook ansible-playbook playbook.yml
Filter Host List ansible-playbook -l host_subset playbook.yml
Splecify the Host:
---
- hosts: droplets
tasks:
- name: Installs nginx web server
apt: pkg=nginx state=installed update_cache=true
notify:
- start nginx
- name: Upload default index.php for host
copy: src=static_files/index.php dest=/usr/share/nginx/www/ mode=0644
register: php
ignore_errors: True
- name: Remove index.html for host
command: rm /usr/share/nginx/www/index.html
when: php|success
- name: Upload default index.html for host
copy: src=static_files/index.html dest=/usr/share/nginx/www/ mode=0644
when: php|failed
handlers:
- name: start nginx
service: name=nginx state=started
Limit to the specifed host ansible-playbook -l host3 nginx.yml
ansible-playbook -i 192.168.1.1 nginx.yml
Ansible Config¶
You may encounter an error about: failed to transfer file
Martyns-MBP:PySible martyn$ ansible -m ping -i 192.168.1.5, all 192.168.1.5 | FAILED! => { "failed": true, "msg": "failed to transfer file to /var/services/homes/martyn/.ansible/tmp/ansible-tmp-1477184543.86-120587186424143/ping:nsftp> put /var/folders/sx/5h8ln41145q6hc_lnyxvrdpm0000gn/T/tmpfHLPHA /var/services/homes/martyn/.ansible/tmp/ansible-tmp-1477184543.86-120587186424143/pingnnremote open("/var/services/homes/martyn/.ansible/tmp/ansible-tmp-1477184543.86-120587186424143/ping"): No such file or directoryrn" }
In this case enable SCP /etc/ansible/ansible.cfg
~/.ansible.cfg
[ssh_connection]
scp_if_ssh=True
Install ‘sshpass’ and use -c ssh Method
Change the SSH Connection -c smart (default) -c ssh (Use if you want sftp false [osx]) -c parimiko
Ansible Show Facts¶
You can use the show facts module ansible all -m setup -i 127.0.0.1:2002, -k -c ssh -u root