Back to the main page

Ansible roles


Ansible role is like framework, basically directory, having variables, tasks, files, etc.
A role is like a script function, that can be reused in script multiple times. Same here, ansible role can be reused in playbook multiple times.


The role is created with the command:
$ ansible-galaxy init <role-name>


$ ansible-galaxy init role_iad
- Role role_iad was created successfully
And directory created is:
$ tree role_iad
|-- defaults
|   |-- main.yml
|-- files
|-- handlers
|   |-- main.yml
|-- meta
|   |-- main.yml
|-- tasks
|   |-- main.yml
|-- templates
|-- tests
|   |-- inventory
|   |-- test.yml
|-- vars
    |-- main.yml


This example provision OCI compute, one idea is to have a role for each region, this is role for IAD.

The file defaults/main.yml is usually for variables that can be overwritten in playbook.
# defaults file for iad, this can be overwritten
compartment_id: "ocid1.compartment.oc1..aaaa.........rrwa" 
ad: "DSdu:US-ASHBURN-AD-1"
shape: "VM.Standard2.8" 
compute_name: "my-compute-test"
subnet: "ocid1.subnet.oc1.iad.aaaaa..........p74va" 
ip: "100.x.x.x"
image: "ocid1.image.oc1.iad.aaaaaaa........6cara"   # OL-6.10
The file vars/main.yml is usually for variables that are not supposed to be overwritten in playbook.
# vars file for iad, this should not be overwritten
profile: "DEFAULT"
The file tasks/main.yml is main task, which can also include other tasks.
- name: Create OCI IAD compute
  oracle.oci.oci_compute_instance:    # must start with oracle.oci (see oracle/oci-ansible-collections on github)
     config_profile_name: "{{ profile }}"  # can be omitted for default profile, which is IAD
     availability_domain: "{{ ad }}"
     compartment_id: "{{ compartment_id }}"
     shape: "{{ shape }}"
        source_type: image
        image_id: "{{ image }}"
     #preserve_boot_volume: no   # remove boot volume when compute is terminated, false is default
     display_name: "{{ compute_name }}"  # compute name (it can differ from create_vnic_details.hostname_label)
        hostname_label: "{{ compute_name }}"   # FQDN of compute
        private_ip: "{{ ip }}"  
        subnet_id: "{{ subnet }}"   
     # adding ssh public key
     metadata: {
        "ssh_authorized_keys": "ssh-rsa AAAABF0c.......+BK6ZSyCoWosR linux...virt"
     freeform_tags: {"What": "SVN 1.6 in OCI IAD"}
Finally, there is playbook (file provision-compute-iad.yml) that calls role to provision OCI compute.
- name: Provision OCI-IAD Compute 
  connection: local
  hosts: localhost

    - role: role_iad
      # if you want to overwrite default/main.yml variables
      #ip: "x.x.x.x"
      #compute_name: "some-hostname"
To provision OCI IAD compute, run the command:
$ ansible-playbook provision-compute-iad.yml

Back to the main page