Ansible playbooks and templates

Posted by Scratches on September 1, 2022

ansible playbook to replace text in config file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
---
- hosts: labservers
  become: yes
  handlers:
    - name: restart apache
      service: name="httpd" state="restarted"
      listen: "restart web"
  tasks:
    - name: make directory
      file:
        path: /opt/www
        state: directory
        mode: "0755"
    - name: change config
      replace:
        path: /etc/httpd/conf/httpd.conf
        regexp: "^DocumentRoot.*$"
        replace: 'DocumentRoot "/opt/www"'
        backup: yes
      notify: "restart web"

Download URL and replace string in downloaded file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
---
- hosts: all
  become: yes
  name: download list
    block:
      - get_url:
          url: http://apps.l33t.example.com/transaction_list
           dest: "/home/ansible/transaction_list"
    rescue:
      - debug: msg="l33t.com appears to be down. Try again later."
    always:
        - debug: msg="Attempt Completed"
  tasks:
  - name: remove blank lines
    replace:
      path: "/home/ansible/transaction_list"
      regexp: '#BLANKLINE'
      replace: '\n'

ansible playbook to loop over strings to create users

1
2
3
4
5
6
7
8
9
10
11
---
- hosts: labservers
  become: yes
  tasks:
    - name: create users
      user:
        name: ""
      with_items:
        - sam
        - john
        - bob

ansible playbook using when to conditionally add line to files

1
2
3
4
5
6
7
8
9
10
---
- hosts: labservers
  become: yes
  tasks:
    - name: edit index.html
      lineinfile:
        path: /var/www/html/index.html
        line: "I'm back!!!"
      when:
        - ansible_hostname == "b320bd293e2c"

ansible playbook configure error handling

  • ignoring acceptable errors
  • defining failure conditions
  • defining “changed”
  • try-catch blocks
    • block-rescue blocks
    • optional always block

ignoring acceptable errors, i.e. apache stopped

1
2
3
4
5
6
7
8
9
10
11
12
---
- hosts: labservers
  become: yes
  tasks:
    - name: get files
      get_url:
        url: http:///index.html
        dest: "/tmp/"
      ignore_errors: yes
      with_items:
        - b320bd293e2c
        - b320bd293e1c

Blocks and Rescues - Rescue debug msg appears instead of error

1
2
3
4
5
6
7
8
9
10
11
---
- hosts: labservers
  name: get file
  block:
    - get_url:
      url: http://localhost/index.html
      dest: "/tmp/index_file"
  rescue:
    - debug: msg="The file does not exist"
  always:
    - debug: msg="Play done!"

Blocks and Rescues - multiple plays in same block-rescue-always block

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
---
- hosts: localhost
  tasks:
    - name: download file and replace line in it
      block:
        - get_url:
            url: http://apps.example.com/transaction_list
            dest: /home/ansible/transaction_list
        - replace:
            path: /home/ansible/transaction_list
            regexp: "#BLANKLINE"
            replace: '\n'
        - debug: msg="File downloaded"
      rescue:
        - debug: msg="example.com appears to be down. Try again later."
      always:
        - debug: msg="Attempt completed!"

Selectively run specific tasks using tags

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
---
- hosts: labservers
  become: yes
  tasks:
    - name: deploy app binary
      copy:
        src: /home/user/apps/hello
        dest: /var/www/html/hello
      tags:
        - webdeploy
- hosts: db
  become: yes
  tasks:
    - name: make scripts directory
      file:
        path: /opt/deb/scripts
        state: directory
        mode: "0755"
    - name:
      copy:
        src: /home/user/apps/script.sql
        dest: /opt/db/scripts/script.sql
      tags:
        - dbdeploy

Download compressed file and unzip to local directory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
---
- hosts: web
  become: yes
  tasks:
    - name: install httpd
      yum:
        name: httpd
        state: latest
    - name: start httpd
      service:
        name: httpd
        state: started
        enabled: yes
    - name: download and unzip remote file
      unarchive:
        src: http://repo.example.com/website.tgz
        dest: /var/www/html
        remote_src: yes

Use template module to copy template to apache conf directory

  • template files are text files with extension .j2
  • templates have access to variables in play’s scope
1
2
3
4
5
6
7
---
- hosts: all
  tasks:
    - name: ensure apache at latest version
      yum: name=httpd state=latest
    - name: write the apache config file
      template: src=/srv/httpd.j2 dest=/etc/httpd.conf

Sample ansible template

  • ansible fact to pull IPv4 address
    1
    2
    
    IP ADDRESS: 
    OS DISTRO: 
    

Ansible playbook to deploy a file created with a template

1
2
3
4
5
6
7
---
- hosts: localhost
  tasks:
  - name: deploy local net file
    template:
      src: /home/user/template/network.j2
      dest: /home/user/template/network.txt

Ansible Variables and Facts

  • ansible variables
  • vars, var_files and vars_prompt
  • ansible-playbook play.yml -e ‘{“varKey”:”varValue”,”varKey2”:”varValue2”}’
    • debug: msg=”This is the variable: { varKey }”
  • dictionary variables
  • varName[‘KeyName’] or varName.KeyName
  • magic variables and filters
  • special variables i.e. hostvars allows looking at facts about other hosts in inventory
  • `` - look at ansible_distribution fact for node1
  • `` - get list of servers in a group in inventory
  • Jinja2 filters can be used to modify ansible variables
  • `` turn list of hosts into space-separated list
  • https://jinja.palletsprojects.com/en/3.1.x/templates/#list-of-builtin-filters
  • ansible facts
  • Facts.d - create your own custom facts
  • To use facts.d, create an /etc/ansible/facts.d directory on the remote host or hosts.
  • Add files to the directory to supply your custom facts. All file names must end with .fact.
  • The files can be JSON, INI, or executable files returning JSON.
    1
    2
    3
    
    [general]
    users=[dsmith,bjones,rthompson]
    flowers=[daisy,hyacinth,rose]
    
  • To view custom facts: ansible <hostname> -m ansible.builtin.setup -a "filter=ansible_local"