Post

Using Ansible to provision remote servers

Install Ansible

1
2
python3 -m pip install --user ansible
ansible --version

Structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.
├── ansible.cfg
├── inventory
│   └── my-cluster
│       ├── group_vars
│       │   └── all.yml
│       └── hosts.ini
├── roles
│   ├── download
│   │   └── tasks
│   │       └── main.yml
│   └── reset
│       └── tasks
│           └── main.yml
├── reset.yml
└── playbook.yml

I write a playbook for install nodejs from binaries on my k3s-cluster

Files

ansible.cfg

1
2
[defaults]
inventory = ./inventory/my-cluster/hosts.ini # setup your remote hosts information

inventory/my-cluster/hosts.ini

1
2
3
4
5
6
7
8
9
[master]
10.0.50.51
[node]
10.0.50.61
10.0.50.62

[k3s-cluster:children]
master
node

inventory/my-cluster/group_vars/all.yml

1
2
3
4
---
ansible_user: heston
ansible_private_key_file: /root/.ssh/id_rsa # ssh key have been setup packer/terraform before
NODEJS_VERSION: "20"

playbook.yml

1
2
3
4
5
6
7
---
- hosts: k3s-cluster
  remote_user: heston
  become: yes
  roles:
    - role: download # you can set a role to run the specific tasks
      become: true

roles/download/tasks/main.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
---
- name: Install the gpg key for nodejs LTS
  apt_key:
    url: "https://deb.nodesource.com/gpgkey/nodesource.gpg.key"
    state: present

- name: Install the nodejs LTS repos
  apt_repository:
    repo: "deb https://deb.nodesource.com/node_{{ NODEJS_VERSION }}.x {{ ansible_distribution_release }} main"
    state: present
    update_cache: yes

- name: Install the nodejs
  apt:
    name: nodejs
    state: present

Build

1
ansible-playbook playbook.yml -vv
This post is licensed under CC BY 4.0 by the author.