Handling files using cloud-init

An early need we all face is to have a file, a license, or a script in place right from the beginning of the instance life. Cloud-init proposes different ways of sending those files over the new instance. We'll see how to send files using plain text and base64 data encodings.

Getting ready

To step through this recipe, you will need:

  • Access to a cloud-config enabled infrastructure

How to do it…

The first file we'll write is a MOTD (short for Message Of The Day) with root read-write permissions, read-only for everyone else. This file will have its content declared right from the cloud-config file:

#cloud-config
write_files:
  - path: /etc/motd
    content: |
      This server is configured using cloud-init.
      Welcome.
    owner: root:root
    permissions: '0644'

This machine, when booted, will have /etc/motd in place and display the string at login:

$ ssh ubuntu@server_ip
Welcome to Ubuntu 16.04.1 LTS (GNU/Linux 4.4.0-36-generic x86_64)
[...]
This server is configured using cloud-init.
Welcome.
[...]
ubuntu@ip-172-31-44-177:~$

Another way of including file content is to encode it in base64. Let's say we want to create a file named /etc/server-id with the content abc-123, with permissions 0600. Begin by obtaining the base64 version of the file:

$ base64 server-id
YWJjLTEyMwo=

This is the output we'll integrate into the content field of the cloud-config file:

  - path: /etc/server-id
    content: YWJjLTEyMwo=
    encoding: b64
    permissions: '0600'

Let's verify the remote content is what we expected:

$ ls -al /etc/server-id
-rw------- 1 root root 8 Sep 20 10:15 /etc/server-id
$ sudo cat /etc/server-id
abc-123

It works! Our file is read/write for the owner only, and the content is abc-123.

Another possibility is to compress the file using gzip, or even to base64 encode the resulting compressed gzip file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.158.148