One place for hosting & domains

      Ansible

      Secrets Management with Ansible


      Ansible stands out for its capabilities in automating server provisioning and management. Ansible’s playbooks, its ability to group and organize resources, and numerous other features make it a great asset for administering servers.

      However, Ansible’s operations often necessitate that your playbooks leverage secrets like server passwords, access tokens, and API keys.

      To bring security to the convenience of your Ansible setup, you should use a secrets management process. Secrets management continues to let Ansible automate your server tasks, with all the access it needs. At the same time, secrets management keeps your secrets safely out of plain text files and other vulnerable locations.

      In this tutorial, learn the most useful methods for implementing secrets management with your Ansible setup. The tutorial covers a range of methods, from simple to scalable, and helps you choose the right fit.

      Before You Begin

      1. If you have not already done so, create a Linode account. See our Getting Started with Linode guide.

      2. Follow our guide on Getting Started With Ansible: Basic Installation and Setup. Specifically, follow the sections on setting up a control node and managed nodes, configuring Ansible, and creating an Ansible inventory.

      3. Refer to our guide Automate Server Configuration with Ansible Playbooks for an overview of Ansible playbooks and their operations.

      Secrets in Ansible

      A secret refers to a key or other credential that allows access to a resource or system. Secrets include things like access tokens, API keys, and database & system passwords.

      When managing nodes with Ansible, you often need to provide it with secrets. Typically, you can provide these secrets within Ansible playbooks, but doing so exposes them to possible interception and exploitation.

      To secure your secrets, you should implement secrets management with your Ansible playbooks. Secrets management refers to the ways in which secrets are stored safely, with different methods balancing between accessibility and security.

      Managing Secrets in Ansible

      Several options exist for managing secrets with your Ansible playbooks. The option that fits your needs depends on your particular setup. How accessible you need your secrets to be and how secure you want to make them determine which solutions work best for you.

      The upcoming sections outline some of the most useful options for managing secrets with Ansible. These attempt to cover a range of use cases, from interactive and manual, to automated and integrated.

      All of the examples that follow use an Ansible setup with one control node and two managed nodes. The managed nodes are given the example IP addresses 192.0.2.1 and 192.0.2.2 throughout, and are listed in an ansiblenodes group in the control node’s Ansible inventory.

      Using Prompts to Manually Enter Secrets

      Ansible playbooks include the option to prompt users for variables. This is actually an option for managing secrets within your Ansible setup.

      With this option, you configure your Ansible playbook to prompt users to manually input secrets. The secrets never need to be persisted on the system, allowing you to safeguard them otherwise. This method is the easiest of the options covered here.

      Of course, this option comes with some significant drawbacks. By not storing the secrets, you also prevent Ansible from accessing them automatically, reducing the ability to integrate your playbooks into automated processes. Additionally, leaving the secrets to manual entry introduces its own risks, as users can mishandle secrets.

      Here is an example Ansible playbook from our Automate Server Configuration with Ansible Playbooks guide. This playbook adds a new non-root user to the managed nodes.

      The playbook uses the vars_prompt option to prompt the user to input a password for the new user. Ansible then hashes the password and deploys the new user to each of the managed nodes.

      Note

      This playbook assumes you have an SSH public key on your control node. The public key allows for secure passwordless connections to the new user in the future. Learn more in our guide Using SSH Public Key Authentication.

      This tutorial also assumes that your control node’s SSH key is secured by a password, and hence uses the --ask-pass option in some of the Ansible playbook commands below. If your SSH key is not secured by a password, remove the --ask-pass option from the Ansible playbook commands shown in this tutorial.

      File: add_limited_user.yml
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      
      ---
      - hosts: ansiblenodes
        remote_user: root
        vars:
          limited_user_name: 'example-user'
        vars_prompt:
          - name: limited_user_password
            prompt: Enter a password for the new non-root user
        tasks:
          - name: "Create a non-root user"
            user: name={{ limited_user_name }}
                  password={{ limited_user_password | password_hash }}
                  shell=/bin/bash
          - name: Add an authorized key for passwordless logins
            authorized_key: user={{ limited_user_name }} key="{{ lookup('file', '~/.ssh/id_rsa.pub') }}"
          - name: Add the new user to the sudoers list
            lineinfile: dest=/etc/sudoers
                        regexp="{{ limited_user_name }} ALL"
                        line="{{ limited_user_name }} ALL=(ALL) ALL"
                        state=present

      To run the playbook, first make sure you’re in the same directory as the playbook, then execute the following command:

      Ansible Control Node

      ansible-playbook --ask-pass add_limited_user.yml

      Ansible prompts for the SSH password first, then for a password for the new user. The output should resemble what is shown below:

      SSH password:
      Enter a password for the new non-root user:
      
      PLAY [ansiblenodes] ************************************************************
      
      TASK [Gathering Facts] *********************************************************
      ok: [192.0.2.2]
      ok: [192.0.2.1]
      
      TASK [Create a non-root user] **************************************************
      changed: [192.0.2.1]
      changed: [192.0.2.2]
      
      TASK [Add remote authorized key to allow future passwordless logins] ***********
      ok: [192.0.2.1]
      ok: [192.0.2.2]
      
      TASK [Add normal user to sudoers] **********************************************
      ok: [192.0.2.1]
      ok: [192.0.2.2]
      
      PLAY RECAP *********************************************************************
      192.0.2.1              : ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
      192.0.2.2              : ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

      Using the Ansible Vault to Manage Secrets

      Ansible has a tool, Ansible Vault, that can facilitate secrets management. The Vault encrypts information, which you can then use within your Ansible playbooks.

      With some setup, Ansible Vault can make secrets both secure and accessible. Secrets are encrypted, meaning that no one can get to them without your password. The secrets are, at the same time, made accessible to Ansible. A password file can give Ansible everything it needs to run in an automated setup.

      The vault password can either be entered manually or automatically through a password file. You can even use an external password manager, and implement a script or other solution to retrieve the password.

      This example of Ansible Vault deploys rclone to the managed nodes and configures it to connect to a Linode Object Storage instance. The secrets are the access keys for the object storage instance.

      To follow along, you need to set up a Linode Object Storage instance with access keys and at least one bucket. You can learn how to do so in our guide Object Storage – Get Started.

      1. Create a file with the access keys for your Linode Object Storage instance. You can do so with the following command, just replace the text in arrow brackets with your corresponding object storage keys:

        Ansible Control Node

        echo "s3_access_token: <S3_ACCESS_TOKEN>" > s3_secrets.enc
        echo "s3_secret_token: <S3_SECRET_TOKEN>" >> s3_secrets.enc
        ansible-vault encrypt s3_secrets.enc

        Ansible Vault prompts you to create a vault password before encrypting the file’s contents.

        New Vault password:
        Confirm New Vault password:
        Encryption successful
      2. Create a password file in the same directory you intend to create the Ansible playbook in. The file needs to contain only the password for your encrypted secrets file. The example in this next command assumes your password is examplepassword:

        Ansible Control Node

        echo "examplepassword" > example.pwd
      3. Create a new Ansible playbook with the following contents. This playbook connects to the non-root users created using the playbook in the previous section of this tutorial. The playbook then installs rclone and creates a configuration file for it. The playbook also inserts the access keys from the s3_secrets.enc file into the configuration file.

        File: set_up_rclone.yml
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        
        ---
        - hosts: ansiblenodes
          remote_user: 'example-user'
          become: yes
          become_method: sudo
          vars:
            s3_region: 'us-southeast-1'
          tasks:
            - name: "Install rclone"
              apt:
                pkg:
                  - rclone
                state: present
                update_cache: yes
            - name: "Create the directory for the rclone configuration"
              file:
                path: "/home/example-user/.config/rclone"
                state: directory
            - name: "Create the rclone configuration file"
              copy:
                dest: "/home/example-user/.config/rclone/rclone.conf"
                content: |
                  [linodes3]
                  type = s3
                  env_auth = false
                  acl = private
                  access_key_id = {{ s3_access_token }}
                  secret_access_key = {{ s3_secret_token }}
                  region = {{ s3_region }}
                  endpoint = {{ s3_region }}.linodeobjects.com          
      4. Run the Ansible playbook. The playbook command here adds the variables from the secrets file using the -e option, and gets the password for decrypting them from the --vault-password-file. The --ask-become-pass option has Ansible prompt for the limited user’s sudo password.

        Ansible Control Node

        ansible-playbook -e @s3_secrets.enc --vault-password-file example.pwd --ask-pass --ask-become-pass set_up_rclone.yml

        The result should resemble:

        SSH password:
        BECOME password[defaults to SSH password]:
        
        PLAY [ansiblenodes] ************************************************************
        
        TASK [Gathering Facts] *********************************************************
        ok: [192.0.2.2]
        ok: [192.0.2.1]
        
        TASK [Install rclone] **********************************************************
        changed: [192.0.2.1]
        changed: [192.0.2.2]
        
        TASK [Create the directory for the rclone configuration] ***********************
        changed: [192.0.2.2]
        changed: [192.0.2.1]
        
        TASK [Create the rclone configuration file] ************************************
        changed: [192.0.2.2]
        changed: [192.0.2.1]
        
        PLAY RECAP *********************************************************************
        192.0.2.1              : ok=4    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
        192.0.2.2              : ok=4    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
      5. To verify that everything is working as expected, log into either of the managed nodes as the non-root user. Then use the following command to list the buckets on your Linode Object Storage instance:

        Ansible Managed Node

        You should see something like the following for each bucket, where ansible-test-bucket is the name of the bucket:

        -1 2022-12-08 00:00:00        -1 ansible-test-bucket

      Using a Secrets Manager

      Dedicated solutions exist for managing secrets, and many password managers are capable of doing so for your Ansible playbooks. In terms of their underlying methods, many of these tools function similarly to Ansible Vault. Despite being external tools, several are supported by official or community plugins for Ansible.

      The primary advantage of an external secrets management solution is using a tool already adopted more widely among your team or organization. Ansible Vault may offer a default integration with Ansible, but you are not likely using it more widely for password management within your organization.

      One of the more popular solutions for secret management is HashiCorp’s Vault. HashiCorp’s Vault is a centralized secrets management system with a dynamic infrastructure to keep passwords, keys, and other secrets secure.

      Ansible maintains a plugin for interacting with HashiCorp’s Vault, the hashi_vault plugin.

      The following steps walk you through an example using HashiCorp’s Vault with Ansible. The example accomplishes the same ends as the example in the previous section, so you can more easily compare the two.

      1. Follow along with our guide on Setting Up and Using a Vault Server. By the end, you should have HashiCorp’s Vault installed, a vault server running and unsealed, and be logged into the vault.

      2. Ensure that the key-value (kv) engine is enabled for the secret path:

        Vault Server

        vault secrets enable -path=secret/ kv
        Success! Enabled the kv secrets engine at: secret/
      3. Add the access keys for your Linode Object Storage instance to the secret/s3 path in the vault. Replace the text in arrow brackets below with your corresponding keys:

        Vault Server

        vault kv put secret/s3 s3_access_token=<S3_ACCESS_TOKEN> s3_secret_token=<S3_SECRET_TOKEN>
        Success! Data written to: secret/s3
      4. On your Ansible control node, install hvac via pip in order to use the hashi_vault plugin referenced in the Ansible playbook below.

        Ansible Control Node

      5. Create a new Ansible playbook with the contents shown below. This parallels the playbook built in the previous section, which installs and configures rclone to connect to a Linode Object Storage instance. This version simply fetches the secrets from a HashiCorp vault instead of an Ansible vault:

        Replace both instances of <HASHI_VAULT_IP> below with the IP address for your HashiCorp Vault server. Similarly, replace both instances of <HASHI_VAULT_TOKEN> with your login token for the HashiCorp Vault server.

        File: another_rclone_setup.yml
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        
        ---
        - hosts: ansiblenodes
          remote_user: 'example-user'
          become: yes
          become_method: sudo
          vars:
            s3_region: 'us-southeast-1'
          tasks:
            - name: "Install rclone"
              apt:
                pkg:
                  - rclone
                state: present
                update_cache: yes
            - name: "Create the directory for the rclone configuration"
              file:
                path: "/home/example-user/.config/rclone"
                state: directory
            - name: "Create the rclone configuration file"
              copy:
                dest: "/home/example-user/.config/rclone/rclone.conf"
                content: |
                  [linodes3]
                  type = s3
                  env_auth = false
                  acl = private
                  access_key_id = {{ lookup('hashi_vault', 'secret=secret/s3:s3_access_token token=<HASHI_VAULT_TOKEN> url=http://<HASHI_VAULT_IP>:8200')}}
                  secret_access_key = {{ lookup('hashi_vault', 'secret=secret/s3:s3_secret_token token=<HASHI_VAULT_TOKEN> url=http://<HASHI_VAULT_IP>:8200')}}
                  region = {{ s3_region }}
                  endpoint = {{ s3_region }}.linodeobjects.com          
      6. Run the Ansible playbook, providing the appropriate passwords when prompted:

        Ansible Control Node

        ansible-playbook --ask-pass --ask-become-pass another_rclone_setup.yml

        The result should resemble:

        SSH password:
        BECOME password[defaults to SSH password]:
        
        PLAY [ansiblenodes] ********************************************************
        
        TASK [Gathering Facts] *****************************************************
        ok: [192.0.2.2]
        ok: [192.0.2.1]
        
        TASK [Install rclone] ******************************************************
        changed: [192.0.2.2]
        changed: [192.0.2.1]
        
        TASK [Create the directory for the rclone configuration] *******************
        changed: [192.0.2.2]
        changed: [192.0.2.1]
        
        TASK [Create the rclone configuration file] ********************************
        changed: [192.0.2.1]
        changed: [192.0.2.2]
        
        PLAY RECAP *****************************************************************
        192.0.2.1              : ok=4    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
        192.0.2.2              : ok=4    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
      7. Just like the previous section, you can verify the setup by logging into one of the managed nodes and running an rclone ls command, such as rclone lsd linodes3:.

      Conclusion

      You now have some options to ensure that your Ansible setup has secure secrets. Choosing between these options comes down to scale and accessibility. Manual entry is simple to start with, but only suits smaller projects and teams. Ansible Vault is in many ways ideal, but an external solution may better fit your team and organization.

      To keep learning about Ansible and efficiently automating your server tasks, read more of our guides on Ansible.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      How to Use the Linode Ansible Collection to Deploy a Linode


      Ansible is a popular open-source Infrastructure as Code (IaC) tool that can be used to complete common IT tasks like cloud provisioning and configuration management across a wide array of infrastructure components. Commonly seen as a solution to multi-cloud configurations, automation, and continuous delivery issues, Ansible is considered by many to be an industry standard in the modern cloud landscape.

      Ansible Collections are the latest standard for managing Ansible content, empowering users to install roles, modules, and plugins with less developer and administrative overhead than ever before.
      The Linode Ansible collection provides the basic plugins needed to get started using Linode services with Ansible right away.

      This guide shows how to:

      Caution

      Before You Begin

      Note

      The steps outlined in this guide require
      Ansible version 2.9.10 or greater and were tested on a Linode running Ubuntu 22.04. The instructions can be adapted to other Linux distributions or operating systems.
      1. Provision a server that acts as the Ansible
        control node, from which other compute instances are deployed. Follow the instructions in our
        Creating a Compute Instance guide to create a Linode running Ubuntu 22.04. A shared CPU 1GB Nanode is suitable. You can also use an existing workstation or laptop if you prefer.

      2. Add a limited Linux user to your control node Linode by following the
        Add a Limited User Account section of our
        Setting Up and Securing a Compute Instance guide. Ensure that all commands for the rest of this guide are entered as your limited user.

      3. Ensure that you have performed system updates:

        sudo apt update && sudo apt upgrade
        
      4. Install Ansible on your control node. Follow the steps in the
        Install Ansible section of the
        Getting Started With Ansible – Basic Installation and Setup guide.

      5. Ensure you have Python version 2.7 or higher installed on your control node. Issue the following command to check your system’s Python version:

        python --version
        

        Many operating systems, including Ubuntu 22.04, instead have Python 3 installed by default. The Python 3 interpreter can usually be invoked with the python3 command, and the remainder of this guide assumes Python 3 is installed and used. For example, you can run this command to check your Python 3 version:

        python3 --version
        
      6. Install the pip package manager:

        sudo apt install python3-pip
        
      7. Generate a Linode API v4 access token with permission to read and write Linodes and record it in a password manager or other safe location. Follow the
        Get an Access Token section of the
        Getting Started with the Linode API guide.

      Install the Linode Ansible Collection

      The Linode Ansible collection is currently open-source and hosted on both a
      public Github repository and on
      Ansible Galaxy. Ansible Galaxy is Ansible’s own community-focused repository, providing information on and access to a wide array of
      Ansible collections and
      Ansible roles. Ansible Galaxy support is built into the latest versions of Ansible by default. While users can install the Linode Ansible collection
      from source or by
      using git, these steps show how to use Ansible Galaxy:

      1. Install required dependencies for Ansible:

        sudo -H pip3 install -Iv 'resolvelib<0.6.0'
        
      2. Download the latest version of the Linode Ansible collection using the ansible-galaxy command:

        ansible-galaxy collection install linode.cloud
        

        Once the collection is installed, all configuration files are stored in the default ~/.ansible/collections/ansible_collections/ collections folder.

      3. Install the Python module dependencies required for the Linode Ansible collection. The Linode collection’s installation directory contains a requirements.txt file that lists the Python dependencies, including the official
        Python library for the Linode API v4. Use pip to install these dependencies:

        sudo pip3 install -r .ansible/collections/ansible_collections/linode/cloud/requirements.txt
        

      The Linode Ansible collection is now installed and ready to deploy and manage Linode services.

      Configure Ansible

      When interfacing with the Linode Ansible collection, it is generally good practice to use variables to securely store sensitive strings like API tokens. This section shows how to securely store and access the
      Linode API Access token (generated in the
      Before You Begin section) along with a root password that is assigned to new Linode instances. Both of these are encrypted with
      Ansible Vault.

      Create an Ansible Vault Password File

      1. From the control node’s home directory, create a development directory to hold user-generated Ansible files. Then navigate to this new directory:

        mkdir development && cd development
        
      2. In the development directory, create a new empty text file called .vault-pass (with no file extension). Then generate a unique, complex new password (for example, by using a password manager), copy it into the new file, and save it. This password is used to encrypt and decrypt information stored with Ansible Vault:

        File: ~/development/.vault-pass
        1
        
        <PasteYourAnsibleVaultPasswordHere>

        This is an Ansible Vault password file. A password file provides your Vault password to Ansible Vault’s encryption commands. Ansible Vault also offers other options for password management. To learn more about password management, read Ansible’s
        Providing Vault Passwords documentation.

      3. Set permissions on the file so that only your user can read and write to it:

        chmod 600 .vault-pass
        

        Caution

        Do not check this file into version control. If this file is located in a Git repository, add it to your
        .gitignore file.

      Create an Ansible Configuration File

      Create an Ansible configuration file called ansible.cfg with a text editor of your choice. Copy this snippet into the file:

      File: ~/development/ansible.cfg
      1
      2
      
      [defaults]
      VAULT_PASSWORD_FILE = ./vault-pass

      These lines specify the location of your password file.

      Encrypt Variables with Ansible Vault

      1. Create a directory to store variable files used with your
        Ansible playbooks:

        mkdir -p ~/development/group_vars/
        
      2. Make a new empty text file called vars.yml in this directory. In the next steps, your encrypted API token and root password are stored in this file:

        touch ~/development/group_vars/vars.yml
        
      3. Generate a unique, complex new password (for example, by using a password manager) that should be used as the root password for new compute instances created with the Linode Ansible collection. This should be different from the Ansible Vault password specified in the .vault-pass file.

      4. Use the following ansible-vault encrypt_string command to encrypt the new root password, replacing MySecureRootPassword with your password. Because this command is run from inside your ~/development directory, the Ansible Vault password in your .vault-pass file is used to perform the encryption:

         ansible-vault encrypt_string 'MySecureRootPassword' --name 'password' | tee -a group_vars/vars.yml
        

        In the above command, tee -a group_vars/vars.yml appends the encrypted string to your vars.yml file. Once completed, output similar to the following appears:

        password: !vault |
            $ANSIBLE_VAULT;1.1;AES256
            30376134633639613832373335313062366536313334316465303462656664333064373933393831
            3432313261613532346134633761316363363535326333360a626431376265373133653535373238
            38323166666665376366663964343830633462623537623065356364343831316439396462343935
            6233646239363434380a383433643763373066633535366137346638613261353064353466303734
            3833
      5. Run the following command to add a newline at the end of your vars.yml file:

        echo "" >> group_vars/vars.yml
        
      6. Use the following ansible-vault encrypt_string command to encrypt your Linode API token and append it to your vars.yml file, replacing MyAPIToken with your own access token:

        ansible-vault encrypt_string 'MyAPIToken' --name 'api-token' | tee -a group_vars/vars.yml
        
      7. Run the following command to add another newline at the end of your vars.yml file:

        echo "" >> group_vars/vars.yml
        

        Your vars.yml file should now resemble:

        File: ~/development/group_vars/vars.yml
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        
        password: !vault |
                  $ANSIBLE_VAULT;1.1;AES256
                  30376134633639613832373335313062366536313334316465303462656664333064373933393831
                  3432313261613532346134633761316363363535326333360a626431376265373133653535373238
                  38323166666665376366663964343830633462623537623065356364343831316439396462343935
                  6233646239363434380a383433643763373066633535366137346638613261353064353466303734
                  3833
        token: !vault |
                  $ANSIBLE_VAULT;1.1;AES256
                  65363565316233613963653465613661316134333164623962643834383632646439306566623061
                  3938393939373039373135663239633162336530373738300a316661373731623538306164363434
                  31656434356431353734666633656534343237333662613036653137396235353833313430626534
                  3330323437653835660a303865636365303532373864613632323930343265343665393432326231
                  61313635653463333630636631336539643430326662373137303166303739616262643338373834
                  34613532353031333731336339396233623533326130376431346462633832353432316163373833
                  35316333626530643736636332323161353139306533633961376432623161626132353933373661
                  36663135323664663130

      Understanding Fully Qualified Collection Namespaces

      Ansible is now configured and the Linode Ansible collection is installed. You can create
      playbooks to leverage the collection and create compute instances and other Linode resources.

      Within playbooks, the Linode Ansible collection is further divided by resource types through the
      Fully Qualified Collection Name(FQCN) affiliated with the desired resource. These names serve as identifiers that help Ansible to more easily and authoritatively delineate between modules and plugins within a collection.

      Modules

      Below is a table of all FQCNs currently included with the Linode Ansible collection and a short overview of their purpose:

      The links in the table above correspond to the GitHub pages for each FQCN. These pages contain a list of all available configuration options for the resource the module applies to. A full dynamically updated list of all resources can be found in the
      Linode Ansible Collections Github Repo.

      Inventory Plugins

      Deploy a Linode with the Linode Ansible Collection

      This section shows how to write a playbook that leverages the Linode Ansible collection and your encrypted API token and root password to create a new Linode instance:

      1. Create a playbook file called deploylinode.yml in your ~/development directory. Copy this snippet into the file and save it:

        File: ~/development/deploylinode.yml
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        
        - name: Create Linode Instance
          hosts: localhost
          vars_files:
              - ./group_vars/vars.yml
          tasks:
            - name: Create a Linode instance
              linode.cloud.instance:
                api_token: "{{ api_token }}"
                label: my-ansible-linode
                type: g6-nanode-1
                region: us-east
                image: linode/ubuntu22.04
                root_pass: "{{ password }}"
                state: present
        • The playbook contains the Create Linode Instance play. When run, the control node receives the necessary instructions from Ansible and uses the Linode API to deploy infrastructure as needed.

        • The vars_files key provides the location of the variable file or files used to populate information related to tasks for the play.

        • The task in the playbook is defined by the name, which serves as a label, and the FQCN used to configure the resource, in this case a Linode compute instance.

        • The configuration options associated with the FQCN are defined. The configuration options for each FQCN are unique to the resource.

          For options where secure strings are used, the encrypted variables in the ./group_vars/vars.yml file are inserted. This includes the API token and root password.

      2. Once the playbook is saved, enter the following command to run it and create a Linode Nanode instance. Because this command is run from inside your ~/development directory, the Ansible Vault password in your .vault-pass file is used by the playbook to decrypt the variables:

        ansible-playbook deploylinode.yml
        

        Once completed, output similar to the following appears:

        PLAY [Create Linode] *********************************************************************
        
        TASK [Gathering Facts] *******************************************************************
        ok: [localhost]
        
        TASK [Create a new Linode.] **************************************************************
        changed: [localhost]
        
        PLAY RECAP *******************************************************************************
        localhost                  : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      Creating and Running your First Ansible Playbook



      Part of the Series:
      How To Write Ansible Playbooks

      Ansible is a modern configuration management tool that doesn’t require the use of an agent software on remote nodes, using only SSH and Python to communicate and execute commands on managed servers. This series will walk you through the main Ansible features that you can use to write playbooks for server automation. At the end, we’ll see a practical example of how to create a playbook to automate setting up a remote Nginx web server and deploy a static HTML website to it.

      Playbooks use the YAML format to define one or more plays. A play is a set of ordered tasks that are arranged in a way to automate a process, such as setting up a web server or deploying an application to production.

      In a playbook file, plays are defined as a YAML list. A typical play starts off by determining which hosts are the target of that particular setup. This is done with the hosts directive.

      Setting the hosts directive to all is a common choice because you can limit the targets of a play at execution time by running the ansible-playbook command with the -l parameter. That allows you to run the same playbook on different servers or groups without the need to change the playbook file every time.

      Start by creating a new directory on your home folder where you can save your practice playbooks. First, make sure you’re in your Ubuntu user’s home directory. From there, create a directory named ansible-practice and then navigate into that directory with the cd command:

      • cd ~
      • mkdir ansible-practice
      • cd ansible-practice

      If you followed all prerequisites, you should already have a working inventory file. You can copy that file into your new ansible-practice directory now. For instance, if you created your test inventory file in an ansible directory in your home folder, you could copy the file to the new directory with:

      • cp ~/ansible/inventory ~/ansible-practice/inventory

      Next, create a new playbook file:

      The following playbook defines a play targeting all hosts from a given inventory. It contains a single task to print a debug message.

      Note: We’ll learn more about tasks in the next section of this series.

      Add the following content to your playbook-01.yml file:

      ~/ansible-practice/playbook-01.yml

      ---
      - hosts: all
        tasks:
          - name: Print message
            debug:
              msg: Hello Ansible World
      

      Save and close the file when you’re done. If you’re using nano, you can do that by typing CTRL+X, then Y and ENTER to confirm.

      To try this playbook on the server(s) that you set up in your inventory file, run ansible-playbook with the same connection arguments you used when running a connection test within the introduction of this series. Here, we’ll be using an inventory file named inventory and the sammy user to connect to the remote server, but be sure to change these details to align with your own inventory file and administrative user:

      • ansible-playbook -i inventory playbook-01.yml -u sammy

      You’ll see output like this:

      Output

      PLAY [all] *********************************************************************************** TASK [Gathering Facts] *********************************************************************** ok: [203.0.113.10] TASK [Update apt cache] ********************************************************************** ok: [203.0.113.10] => { "msg": "Hello Ansible World" } PLAY RECAP *********************************************************************************** 203.0.113.10 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

      You might have noticed that even though you have defined only one task within your playbook, two tasks were listed in the play output. At the beginning of each play, Ansible executes by default an additional task that gathers information — referred to as facts — about the remote nodes. Because facts can be used on playbooks to better customize the behavior of tasks, the fact-gathering task must happen before any other tasks are executed.

      We’ll learn more about Ansible facts in a later section of this series.



      Source link