Pocket Theories

Ansible

Updated: September 10, 2024


# Test

ansible localhost -m ansible.builtin.gather_facts

#
# /etc/ansible/ansible.cfg
#

[ssh_connection]
pipelining = True
[defaults]
nocows = True
interpreter_python = /usr/bin/python3
gathering = False
forks = 2
strategy = free
host_key_checking = False
[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s

#
# /etc/ansible/hosts  # ini format (alt: yaml)
#

genpurpose1host.localdomain  # ungrouped
[web]
webserver1 ansible_connection=ssh ansible_host=webserver1.localdomain ansible_port=2022 ansible_user=webadmin
localhost ansible_connection=local

#
# playbook  # ansible-playbook your_playbook.yml
#

- name: Add repository
  ansible.builtin.yum_repository:
    name: epel
    description: EPEL YUM repo
    baseurl: https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
    gpgcheck: no

- name: Install the latest version of Apache
  ansible.builtin.yum:
    name: httpd
    state: latest  # present|absent|latest

- name: Install package.
  yum:
     name: /tmp/package.rpm
     state: present

- name: Remote RPM install with yum
  yum: name=http://example.com/some_package.rpm

- name: Add specified repository into sources list
  ansible.builtin.apt_repository:
    repo: deb http://archive.canonical.com/ubuntu hardy partner
    state: present

- name: Update repositories cache and install "foo" package
  ansible.builtin.apt:
    name: foo
    update_cache: yes
    state: present

- name: Install a .deb package from the internet
  ansible.builtin.apt:
    deb: https://example.com/python-ppq_0.1-1_all.deb

- name: Copy rpm file to server
  copy:
     src: package.rpm
     dest: /tmp/package.rpm

- name: Generate sshd_config
  hosts: web
  tasks:
    - name: Template sshd_config
      template:
        src: /path/to/sshd_config.j2
        dest: /etc/ssh/sshd_config
      vars:
        ssh_port: 22
        permit_root_login: no

- name: Execute the command in remote shell; stdout goes to the specified file on the remote
  ansible.builtin.shell: somescript.sh >> somelog.txt

- ansible.posix.sysctl:
    name: net.ipv4.ip_forward
    value: '1'
    sysctl_set: true
    state: present
    reload: true

# Using http_proxy on servers
- hosts: appservers
  user: www
  become: yes
  tasks:
  - name: Download file
    get_url:
      url: http://example.com/file.tgz
      dest: /Users/nitin/Downloads
    environment:
      http_proxy: https://example.com:8080
      https_proxy: https://example.com:8080

# Variables can be used for an entire block
- name: Demonstrate environment variable in block
  hosts: localhost
  connection: local
  gather_facts: false
  vars:
    motd: Hello World
  tasks:
  - block:
    - name: Print variable
      shell: "echo $motd"
      register: theoutput
    - debug: var=theoutput.stdout
      environment:
        motd: "{{ motd }}"

# Using roles
- hosts: example_host
  roles:
    - php
    - nginx
	  

Also see: