Introduction to Ansible

Posted by 4Aiur on 01/31/2014 in SysAdmin |

Introduction to Ansible


I don’t want input password every time when I run ansible, so prepare ssh key authentication agent for auto login.

# Generate ssh public private key pair
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa
ssh-agent | head -2 > ~/.ssh/.agent.env
source ~/.ssh/.agent.env
ssh-add ~/.ssh/id_rsa

Install Ansible on a isolation environment.

mkdir ~/Ansible
cd  ~/Ansible  # or press Escape + .
sudo easy_install pip
pip install virtualenv
virtualenv .venv
source .venv/bin/activate
pip install ansible

Setup autoenv for load ansible environment automatically.

git clone git:// ~/.autoenv
echo "source ~/.autoenv/" >> ~/.bash_profile
source ~/.autoenv/
cat > ~/Ansible/.active_ansible <<\EOF
source ~/Ansible/.venv/bin/activate  # Activeate virtualenv
source ~/.ssh/.agent.env  # Load ssh-agent env
# or use private key file
# export ANSIBLE_PRIVATE_KEY_FILE=~/.ssh/id_rsa
export ANSIBLE_HOSTS=~/Ansible/inventory
export ANSIBLE_HOST_KEY_CHECKING=False  # Set ansible config
export ANSIBLE_FORKS=20  # Specify ansible parallel processes
echo "source ~/Ansible/.active_ansible" > .env

Usage examples

Inventory file

cat ~/Ansible/inventory


Run some ad-hoc commands

ansible web -m shell -a "uptime"

File Transfer

ansible web -m copy -a "src=foo dest=/tmp/foo"

Gathering Facts

ansible web -m setup


Distribute the public_key to remote hosts with playbook

cat > playbook.yaml <

Write a customize playbook

Here is a Ansbile playbook example.

Playbook directory structure.

$ tree
|---example      # Role name
|-----files      # Statistic files
|-----tasks      # Put tasks here
|-----templates  # Template files
|-----vars       # Variabals

# roles/example/vars/main.yml
  ssh_dir: /home/mlf4aiur/.ssh
  owner: mlf4aiur
  group: mlf4aiur

# roles/example/files/
# roles/example/tasks/main.yml
- name: set attributes of .ssh
  action: file path={{ ssh_dir }} owner={{ owner }} group={{ group }} mode=0700 state=directory
- name: put public key in ~/.ssh/
  action: copy src={{ authorized_keys }} dest={{ ssh_dir }}/authorized_keys owner={{ owner }} group={{ group }} mode=0600

Apply this playbook to distribute public_key.

# distribute_public_key.yml
- hosts: all
  gather_facts: False
    - example

ansible-playbook distribute_public_key.yml

Related links:


Copyright © 2010-2019 4Aiur All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from