One place for hosting & domains

      blog

      How To Build A Security Information and Event Management (SIEM) System with Suricata and the Elastic Stack on Ubuntu 20.04


      Introduction

      The previous tutorials in this series guided you through installing, configuring, and running Suricata as an Intrusion Detection (IDS) and Intrusion Prevention (IPS) system. You also learned about Suricata rules and how to create your own.

      In this tutorial you will explore how to integrate Suricata with Elasticsearch, Kibana, and Filebeat to begin creating your own Security Information and Event Management (SIEM) system. SIEM tools are used to collect, aggregate, store, and analyze event data to search for security threats and suspicious activity on your networks and servers.

      The components that you will use to build your own SIEM tool are:

      • Elasticsearch to store, index, correlate, and search the security events that come from your Suricata server.
      • Kibana to display and navigate around the security event logs that are stored in Elasticsearch.
      • Filebeat to parse Suricata’s eve.json log file and send each event to Elasticsearch for processing.
      • Suricata to scan your network traffic for suspicious events, and either log or drop invalid packets.

      First you’ll install and configure Elasticsearch and Kibana with some specific authentication settings. Then you’ll add Filebeat to your Suricata system to send its eve.json logs to Elasticsearch.

      Finally, you’ll learn how to connect to Kibana using SSH and your web browser, and then load and interact with Kibana dashboards that show Suricata’s events and alerts.

      Prerequisites

      If you have been following this tutorial series then you should already have Suricata running on an Ubuntu 20.04 server. This server will be referred to as your Suricata server.

      You will also need a second server to host Elasticsearch and Kibana. This server will be referred to as your Elasticsearch server. It should be an Ubuntu 20.04 server with:

      For the purposes of this tutorial, both servers should be able to communicate using private IP addresses. You can use a VPN like WireGuard to connect your servers, or use a cloud-provider that has private networking between hosts. You can also choose to run Elasticsearch, Kibana, Filebeat, and Suricata on the same server for experimenting.

      Step 1 — Installing Elasticsearch and Kibana

      The first step in this tutorial is to install Elasticsearch and Kibana on your Elasticsearch server. To get started, add the Elastic GPG key to your server with the following command:

      • curl -fsSL https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -

      Next, add the Elastic source list to the sources.list.d directory, where apt will search for new sources:

      • echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list

      Now update your server’s package index and install Elasticsearch and Kibana:

      • sudo apt update
      • sudo apt install elasticsearch kibana

      Once you are done installing the packages, find and record your server’s private IP address using the ip address show command:

      You will receive output like the following:

      Output

      lo UNKNOWN 127.0.0.1/8 ::1/128 eth0 UP 159.89.122.115/20 10.20.0.8/16 2604:a880:cad:d0::e56:8001/64 fe80::b832:69ff:fe46:7e5d/64 eth1 UP 10.137.0.5/16 fe80::b883:5bff:fe19:43f3/64

      The private network interface in this output is the highlighted eth1 device, with the IPv4 address 10.137.0.5/16. Your device name, and IP addresses will be different. However, the address will be from the following reserved blocks of addresses:

      • 10.0.0.0 to 10.255.255.255 (10/8 prefix)
      • 172.16.0.0 to 172.31.255.255 (172.16/12 prefix)
      • 192.168.0.0 to 192.168.255.255 (192.168/16 prefix)

      If you would like to learn more about how these blocks are allocated visit the RFC 1918 specification)

      Record the private IP address for your Elasticsearch server (in this case 10.137.0.5). This address will be referred to as your_private_ip in the remainder of this tutorial. Also note the name of the network interface, in this case eth1. In the next part of this tutorial you will configure Elasticsearch and Kibana to listen for connections on the private IP address coming from your Suricata server.

      Step 2 — Configuring Elasticsearch

      Elasticsearch is configured to only accept local connections by default. Additionally, it does not have any authentication enabled, so tools like Filebeat will not be able to send logs to it. In this section of the tutorial you will configure the network settings for Elasticsearch and then enable Elasticsearch’s built-in xpack security module.

      Configuring Elasticsearch Networking

      Since Your Elasticsearch and Suricata servers are separate, you will need to configure Elasticsearch to listen for connections on its private network interface. You will also need to configure your firewall rules to allow access to Elasticsearch on your private network interface.

      Open the /etc/elasticsearch/elasticsearch.yml file using nano or your preferred editor:

      • sudo nano /etc/elasticsearch/elasticsearch.yml

      Find the commented out #network.host: 192.168.0.1 line between lines 50–60 and add a new line after it that configures the network.bind_host setting, as highlighted below:

      /etc/elasticsearch/elasticsearch.yml

      # By default Elasticsearch is only accessible on localhost. Set a different
      # address here to expose this node on the network:
      #
      #network.host: 192.168.0.1
      network.bind_host: ["127.0.0.1", "your_private_ip"]
      #
      # By default Elasticsearch listens for HTTP traffic on the first free port it
      # finds starting at 9200. Set a specific HTTP port here:
      

      Substitute your private IP in place of the your_private_ip address. This line will ensure that Elasticsearch is still available on its local address so that Kibana can reach it, as well as on the private IP address for your server.

      Next, go to the end of the file using the nano shortcut CTRL+v until you reach the end.

      Add the following highlighted lines to the end of the file:

      /etc/elasticsearch/elasticsearch.yml

      . . .
      discovery.type: single-node
      xpack.security.enabled: true
      

      The discovery.type setting allows Elasticsearch to run as a single node, as opposed to in a cluster of other Elasticsearch servers. The xpack.security.enabled setting turns on some of the security features that are included with Elasticsearch.

      Save and close the file when you are done editing it. If you are using nano, you can do so with CTRL+X, then Y and ENTER to confirm.

      Finally, add firewall rules to ensure your Elasticsearch server is reachable on its private network interface. If you followed the prerequisite tutorials and are using the Uncomplicated Firewall (ufw), run the following commands:

      • sudo ufw allow in on eth1
      • sudo ufw allow out on eth1

      Substitute your private network interface in place of eth1 if it uses a different name.

      Next you will start the Elasticsearch daemon and then configure passwords for use with the xpack security module.

      Starting Elasticsearch

      Now that you have configured networking and the xpack security settings for Elasticsearch, you need to start it for the changes to take effect.

      Run the following systemctl command to start Elasticsearch:

      • sudo systemctl start elasticsearch.service

      Once Elasticsearch finishes starting, you can continue to the next section of this tutorial where you will generate passwords for the default users that are built-in to Elasticsearch.

      Configuring Elasticsearch Passwords

      Now that you have enabled the xpack.security.enabled setting, you need to generate passwords for the default Elasticsearch users. Elasticsearch includes a utility in the /usr/share/elasticsearch/bin directory that can automatically generate random passwords for these users.

      Run the following command to cd to the directory and then generate random passwords for all the default users:

      • cd /usr/share/elasticsearch/bin
      • sudo ./elasticsearch-setup-passwords auto

      You will receive output like the following. When prompted to continue, press y and then RETURN or ENTER:

      Initiating the setup of passwords for reserved users elastic,apm_system,kibana,kibana_system,logstash_system,beats_system,remote_monitoring_user.
      The passwords will be randomly generated and printed to the console.
      Please confirm that you would like to continue [y/N]y
      
      
      Changed password for user apm_system
      PASSWORD apm_system = eWqzd0asAmxZ0gcJpOvn
      
      Changed password for user kibana_system
      PASSWORD kibana_system = 1HLVxfqZMd7aFQS6Uabl
      
      Changed password for user kibana
      PASSWORD kibana = 1HLVxfqZMd7aFQS6Uabl
      
      Changed password for user logstash_system
      PASSWORD logstash_system = wUjY59H91WGvGaN8uFLc
      
      Changed password for user beats_system
      PASSWORD beats_system = 2p81hIdAzWKknhzA992m
      
      Changed password for user remote_monitoring_user
      PASSWORD remote_monitoring_user = 85HF85Fl6cPslJlA8wPG
      
      Changed password for user elastic
      PASSWORD elastic = 6kNbsxQGYZ2EQJiqJpgl
      

      You will not be able to run the utility again, so make sure to record these passwords somewhere secure. You will need to use the kibana_system user’s password in the next section of this tutorial, and the elastic user’s password in the Configuring Filebeat step of this tutorial.

      At this point in the tutorial you are finished configuring Elasticsearch. The next section explains how to configure Kibana’s network settings and its xpack security module.

      Step 3 — Configuring Kibana

      In the previous section of this tutorial, you configured Elasticsearch to listen for connections on your Elasticsearch server’s private IP address. You will need to do the same for Kibana so that Filebeats on your Suricata server can reach it.

      First you’ll enable Kibana’s xpack security functionality by generating some secrets that Kibana will use to store data in Elasticsearch. Then you’ll configure Kibana’s network setting and authentication details to connect to Elasticsearch.

      Enabling xpack.security in Kibana

      To get started with xpack security settings in Kibana, you need to generate some encryption keys. Kibana uses these keys to store session data (like cookies), as well as various saved dashboards and views of data in Elasticsearch.

      You can generate the required encryption keys using the kibana-encryption-keys utility that is included in the /usr/share/kibana/bin directory. Run the following to cd to the directory and then generate the keys:

      • cd /usr/share/kibana/bin/
      • sudo ./kibana-encryption-keys generate -q

      The -q flag suppresses the tool’s instructions so that you only receive output like the following:

      Output

      xpack.encryptedSavedObjects.encryptionKey: 66fbd85ceb3cba51c0e939fb2526f585 xpack.reporting.encryptionKey: 9358f4bc7189ae0ade1b8deeec7f38ef xpack.security.encryptionKey: 8f847a594e4a813c4187fa93c884e92b

      Copy your output somewhere secure. You will now add them to Kibana’s /etc/kibana/kibana.yml configuration file.

      Open the file using nano or your preferred editor:

      • sudo nano /etc/kibana/kibana.yml

      Go to the end of the file using the nano shortcut CTRL+v until you reach the end. Paste the three xpack lines that you copied to the end of the file:

      /etc/kibana/kibana.yml

      . . .
      
      # Specifies locale to be used for all localizable strings, dates and number formats.
      # Supported languages are the following: English - en , by default , Chinese - zh-CN .
      #i18n.locale: "en"
      
      xpack.encryptedSavedObjects.encryptionKey: 66fbd85ceb3cba51c0e939fb2526f585
      xpack.reporting.encryptionKey: 9358f4bc7189ae0ade1b8deeec7f38ef
      xpack.security.encryptionKey: 8f847a594e4a813c4187fa93c884e92b
      

      Keep the file open and proceed to the next section where you will configure Kibana’s network settings.

      Configuring Kibana Networking

      To configure Kibana’s networking so that it is available on your Elasticsearch server’s private IP address, find the commented out #server.host: "localhost" line in /etc/kibana/kibana.yml. The line is near the beginning of the file. Add a new line after it with your server’s private IP address, as highlighted below:

      /etc/kibana/kibana.yml

      # Kibana is served by a back end server. This setting specifies the port to use.
      #server.port: 5601
      
      # Specifies the address to which the Kibana server will bind. IP addresses and host names are both valid values.
      # The default is 'localhost', which usually means remote machines will not be able to connect.
      # To allow connections from remote users, set this parameter to a non-loopback address.
      #server.host: "localhost"
      server.host: "your_private_ip"
      

      Substitute your private IP in place of the your_private_ip address.

      Save and close the file when you are done editing it. If you are using nano, you can do so with CTRL+X, then Y and ENTER to confirm.

      Next, you’ll need to configure the username and password that Kibana uses to connect to Elasticsearch.

      Configuring Kibana Credentials

      There are two ways to set the username and password that Kibana uses to authenticate to Elasticsearch. The first is to edit the /etc/kibana/kibana.yml configuration file and add the values there. The second method is to store the values in Kibana’s keystore, which is an obfuscated file that Kibana can use to store secrets.

      We’ll use the keystore method in this tutorial since it avoids editing Kibana’s configuration file directly

      If you prefer to edit the file instead, the settings to configure in it are elasticsearch.username and elasticsearch.password.

      If you choose to edit the configuration file, skip the rest of the steps in this section.

      To add a secret to the keystore using the kibana-keystore utility, first cd to the /usr/share/kibana/bin directory. Next, run the following command to set the username for Kibana:

      • sudo ./kibana-keystore add elasticsearch.username

      You will receive a prompt like the following:

      Username Entry

      Enter value for elasticsearch.username: *************
      

      Enter kibana_system when prompted, either by copying and pasting, or typing the username carefully. Each character that you type will be masked with an * asterisk character. Press ENTER or RETURN when you are done entering the username.

      Now repeat the same command for the password. Be sure to copy the password for the kibana_system user that you generated in the previous section of this tutorial. For reference, in this tutorial the example password is 1HLVxfqZMd7aFQS6Uabl.

      Run the following command to set the password:

      • sudo ./kibana-keystore add elasticsearch.password

      When prompted, paste the password to avoid any transcription errors:

      Password Entry

      Enter value for elasticsearch.password: ********************
      

      Starting Kibana

      Now that you have configured networking and the xpack security settings for Kibana, as well as added credentials to the keystore, you need to start it for the changes to take effect.

      Run the following systemctl command to restart Kibana:

      • sudo systemctl start kibana.service

      Once Kibana starts, you can continue to the next section of this tutorial where you will configure Filebeat on your Suricata server to send its logs to Elasticsearch.

      Step 4 — Installing Filebeat

      Now that your Elasticsearch and Kibana processes are configured with the correct network and authentication settings, the next step is to install and set up Filebeat on your Suricata server.

      To get started installing Filebeat, add the Elastic GPG key to your Suricata server with the following command:

      • curl -fsSL https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -

      Next, add the Elastic source list to the sources.list.d directory, where apt will search for new sources:

      • echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list

      Now update the server’s package index and install the Filebeat package:

      • sudo apt update
      • sudo apt install filebeat

      Next you’ll need to configure Filebeat to connect to both Elasticsearch and Kibana. Open the /etc/filebeat/filebeat.yml configuration file using nano or your preferred editor:

      • sudo nano /etc/filebeat/filebeat.yml

      Find the Kibana section of the file around line 100. Add a line after the commented out #host: "localhost:5601" line that points to your Kibana instance’s private IP address and port:

      /etc/filebeat/filebeat.yml

      . . .
      # Starting with Beats version 6.0.0, the dashboards are loaded via the Kibana API.
      # This requires a Kibana endpoint configuration.
      setup.kibana:
      
        # Kibana Host
        # Scheme and port can be left out and will be set to the default (http and 5601)
        # In case you specify and additional path, the scheme is required: http://localhost:5601/path
        # IPv6 addresses should always be defined as: https://[2001:db8::1]:5601
        #host: "localhost:5601"
        host: "your_private_ip:5601"
      
      . . .
      

      This change will ensure that Filebeat can connect to Kibana in order to create the various SIEM indices, dashboards, and processing pipelines in Elasticsearch to handle your Suricata logs.

      Next, find the Elasticsearch Output section of the file around line 130 and edit the hosts, username, and password settings to match the values for your Elasticsearch server:

      output.elasticsearch:
        # Array of hosts to connect to.
        hosts: ["your_private_ip:9200"]
      
        # Protocol - either `http` (default) or `https`.
        #protocol: "https"
      
        # Authentication credentials - either API key or username/password.
        #api_key: "id:api_key"
        username: "elastic"
        password: "6kNbsxQGYZ2EQJiqJpgl"
      
      . . .
      

      Substitute in your Elasticsearch server’s private IP address on the hosts line in place of the your_private_ip value. Uncomment the username field and leave it set to the elastic user. Change the password field from changeme to the password for the elastic user that you generated in the Configuring Elasticsearch Passwords section of this tutorial.

      Save and close the file when you are done editing it. If you are using nano, you can do so with CTRL+X, then Y and ENTER to confirm.

      Next, enable Filebeats’ built-in Suricata module with the following command:

      • sudo filebeat modules enable suricata

      Now that Filebeat is configured to connect to Elasticsearch and Kibana, with the Suricata module enabled, the next step is to load the SIEM dashboards and pipelines into Elasticsearch.

      Run the filebeat setup command. It may take a few minutes to load everything:

      Once the command finishes you should receive output like the following:

      Output

      Overwriting ILM policy is disabled. Set `setup.ilm.overwrite: true` for enabling. Index setup finished. Loading dashboards (Kibana must be running and reachable) Loaded dashboards Setting up ML using setup --machine-learning is going to be removed in 8.0.0. Please use the ML app instead. See more: https://www.elastic.co/guide/en/machine-learning/current/index.html It is not possible to load ML jobs into an Elasticsearch 8.0.0 or newer using the Beat. Loaded machine learning job configurations Loaded Ingest pipelines

      If there are no errors, use the systemctl command to start Filebeat. It will begin sending events from Suricata’s eve.json log to Elasticsearch once it is running.

      • sudo systemctl start filebeat.service

      Now that you have Filebeat, Kibana, and Elasticsearch configured to process your Suricata logs, the last step in this tutorial is to connect to Kibana and explore the SIEM dashboards.

      Step 5 — Navigating Kibana’s SIEM Dashboards

      Kibana is the graphical component of the Elastic stack. You will use Kibana with your browser to explore Suricata’s event and alert data. Since you configured Kibana to only be available via your Elasticsearch server’s private IP address, you will need to use an SSH tunnel to connect to Kibana.

      Connecting to Kibana with SSH

      SSH has an option -L that lets you forward network traffic on a local port over its connection to a remote IP address and port on a server. You will use this option to forward traffic from your browser to your Kibana instance.

      On Linux, macOS, and updated versions of Windows 10 and higher, you can use the built-in SSH client to create the tunnel. You will use this command each time you want to connect to Kibana. You can close this connection at any time and then run the SSH command again to re-establish the tunnel.

      Run the following command in a terminal on your local desktop or laptop computer to create the SSH tunnel to Kibana:

      • ssh -L 5601:your_private_ip:5601 sammy@203.0.113.5 -N

      The various arguments to SSH are:

      • The -L flag forwards traffic to your local system on port 5601 to the remote server.
      • The your_private_ip:5601 portion of the command specifies the service on your Elasticsearch server where your traffic will be fowarded to. In this case that service is Kibana. Be sure to substitute your Elasticsearch server’s private IP address in place of your_private_ip
      • The 203.11.0.5 address is the public IP address that you use to connect to and administer your server. Substitute your Elasticsearch server’s public IP address in its place.
      • The -N flag instructs SSH to not run a command like an interactive /bin/bash shell, and instead just hold the connection open. It is generally used when forwarding ports like in this example.

      If you would like to close the tunnel at any time, press CTRL+C.

      On Windows your terminal should resemble the following screenshot:

      Note: You may be prompted to enter a password if you are not using an SSH key. Type or paste it into the prompt and press ENTER or RETURN.

      Screenshot of Windows Command Prompt Showing SSH Command to Port Forward to Kibana

      On macOS and Linux your terminal will be similar to the following screenshot:

      Screenshot of Windows Command Prompt Showing SSH Command to Port Forward to Kibana

      Once you have connected to your Elasticsearch server over SSH with the port forward in place, open your browser and visit http://127.0.0.1:5601. You will be redirected to Kibana’s login page:

      Screenshot of a Browser on Kibana's Login Page

      If your browser cannot connect to Kibana you will receive a message like the following in your terminal:

      Output

      channel 3: open failed: connect failed: No route to host

      This error indicates that your SSH tunnel is unable to reach the Kibana service on your server. Ensure that you have specified the correct private IP address for your Elasticsearch server and reload the page in your browser.

      Log in to your Kibana server using elastic for the Username, and the password that you copied earlier in this tutorial for the user.

      Browsing Kibana SIEM Dashboards

      Once you are logged into Kibana you can explore the Suricata dashboards that Filebeat configured for you.

      In the search field at the top of the Kibana Welcome page, input the search terms type:dashboard suricata. This search will return two results: the Suricata Events and Suricata Alerts dashboards per the following screenshot:

      Screenshot of a Browser Using Kibana's Global Search Box to Locate Suricata Dashboards

      Click the [Filebeat Suricata] Events Overview result to visit the Kibana dashboard that shows an overview of all logged Suricata events:

      Screenshot of a Browser on Kibana's Suricata Events Dashboard

      To visit the Suricata Alerts dashboard, repeat the search or click the Alerts link that is included in the Events dashboard. Your page should resemble the following screenshot:

      Screenshot of a Browser on Kibana's Suricata Alerts Dashboard

      If you would like to inspect the events and alerts that each dashboard displays, scroll to the bottom of the page where you will find a table that lists each event and alert. You can expand each entry to view the original log entry from Suricata, and examine in detail the various fields like source and destination IPs for an alert, the attack type, Suricata signature ID, and others.

      Kibana also has a built-in set of Security dashboards that you can access using the menu on the left side of the browser window. Navigate to the Network dashboard for an overview of events displayed on a map, as well as aggregate data about events on your network. Your dashboard should resemble the following screenshot:

      Screenshot of a Browser on Kibana's Security -> Network Dashboard

      You can scroll to the bottom of the Network dashboard for a table that lists all of the events that match your specified search timeframe. You can also examine each event in detail, or select an event to generate a Kibana timeline, that you can then use to investigate specific traffic flows, alerts, or community IDs.

      Conclusion

      In this tutorial you installed and configured Elasticsearch and Kibana on a standalone server. You configured both tools to be available on a private IP address. You also configured Elasticsearch and Kibana’s authentication settings using the xpack security module that is included with each tool.

      After completing the Elasticsearch and Kibana configuration steps, you also installed and configured Filebeat on your Suricata server. You used Filebeat to populate Kibana’s dashboards and start sending Suricata logs to Elasticsearch.

      Finally, you created an SSH tunnel to your Elasticsearch server and logged into Kibana. You located the new Suricata Events and Alerts dashboards, as well as the Network dashboard.

      The last tutorial in this series will guide you through using Kibana’s SIEM functionality to process your Suricata alerts. In it you will explore how to create cases to track specific alerts, timelines to correlate network flows, and rules to match specific Suricata events that you would like to track or analyze in more detail.



      Source link

      How to Deploy to Kubernetes using Argo CD and GitOps


      Introduction

      Using Kubernetes to deploy your application can provide significant infrastructural advantages, such as flexible scaling, management of distributed components, and control over different versions of your application. However, with that increased control comes increased complexity. Continuous Integration and Continuous Deployment (CI/CD) systems usually work at a high level of abstraction in order to provide version control, change logging, and rollback functionality. A popular approach to this abstraction layer is called GitOps.

      GitOps, as originally proposed by Weaveworks in a 2017 blog post, uses Git as a “single source of truth” for CI/CD processes, integrating code changes in a single, shared repository per project and using pull requests to manage infrastructure and deployment.

      There are several tools that use Git as a focal point for DevOps processes on Kubernetes. In this tutorial, you will learn to use Argo CD, a declarative Continuous Delivery tool. Argo CD provides Continuous Delivery tooling that automatically synchronizes and deploys your application whenever a change is made in your GitHub repository. By managing the deployment and lifecycle of an application, it provides solutions for version control, configurations, and application definitions in Kubernetes environments, organizing complex data with an easy-to-understand user interface. It can handle several types of Kubernetes manifests, including Jsonnet, Kustomize applications, Helm charts, and YAML/json files, and supports webhook notifications from GitHub, GitLab, and Bitbucket.

      In this article, you will use Argo CD to synchronize and deploy an application from a GitHub repository.

      Prerequisites

      To follow this tutorial, you will need:

      Step 1 — Installing Argo CD on Your Cluster

      In order to install Argo CD, you should first have a valid Kubernetes configuration set up with kubectl, from which you can ping your worker nodes. You can test this by running kubectl get nodes:

      This command should return a list of nodes with the Ready status:

      Output

      NAME STATUS ROLES AGE VERSION pool-uqv8a47h0-ul5a7 Ready <none> 22m v1.21.5 pool-uqv8a47h0-ul5am Ready <none> 21m v1.21.5 pool-uqv8a47h0-ul5aq Ready <none> 21m v1.21.5

      If kubectl does not return a set of nodes with the Ready status, you should review your cluster configuration and the Kubernetes documentation.

      Next, create the argocd namespace in your cluster, which will contain Argo CD and its associated services:

      • kubectl create namespace argocd

      After that, you can run the Argo CD install script provided by the project maintainers.

      • kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

      Once the installation completes successfully, you can use the watch command to check the status of your Kubernetes pods:

      • watch kubectl get pods -n argocd

      By default, there should be five pods that eventually receive the Running status as part of a stock Argo CD installation.

      Output

      NAME READY STATUS RESTARTS AGE argocd-application-controller-0 1/1 Running 0 2m28s argocd-dex-server-66f865ffb4-chwwg 1/1 Running 0 2m30s argocd-redis-5b6967fdfc-q4klp 1/1 Running 0 2m30s argocd-repo-server-656c76778f-vsn7l 1/1 Running 0 2m29s argocd-server-cd68f46f8-zg7hq 1/1 Running 0 2m28s

      You can press Ctrl+C to exit the watch interface. You now have Argo CD running in your Kubernetes cluster! However, because of the way Kubernetes creates abstractions around your network interfaces, you won’t be able to access it directly without forwarding ports from inside your cluster. You’ll learn how to handle that in the next step.

      Step 2 — Forwarding Ports to Access Argo CD

      Because Kubernetes deploys services to arbitrary network addresses inside your cluster, you’ll need to forward the relevant ports in order to access them from your local machine. Argo CD sets up a service named argocd-server on port 443 internally. Because port 443 is the default HTTPS port, and you may be running some other HTTP/HTTPS services, it’s common practice to forward those to arbitrarily chosen other ports, like 8080, like so:

      • kubectl port-forward svc/argocd-server -n argocd 8080:443

      Port forwarding will block the terminal it’s running in as long as it’s active, so you’ll probably want to run this in a new terminal window while you continue to work. You can press Ctrl+C to gracefully quit a blocking process such as this one when you want to stop forwarding the port.

      In the meantime, you should be able to access Argo CD in a web browser by navigating to localhost:8080. However, you’ll be prompted for a login password which you’ll need to use the command line to retrieve in the next step. You’ll probably need to click through a security warning because Argo CD has not yet been configured with a valid SSL certificate.

      Note: Using LetsEncrypt HTTPS certificates with Kubernetes is best accomplished with the use of additional tooling like Cert-Manager.

      Step 3 — Working with Argo CD from the Command Line

      For the next steps, you’ll want to have the argocd command installed locally for interfacing with and changing settings in your Argo CD instance. Argo CD’s official documentation recommends that you install it via the Homebrew package manager. Homebrew is very popular for managing command line tools on MacOS, and has more recently been ported to Linux to facilitate maintaining tools like this one.

      If you don’t already have Homebrew installed, you can retrieve and install it with a one-line command:

      • ​​/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

      You may be prompted for your password during the installation process. Afterward, you should have the brew command available in your terminal. You can use it to install Argo CD:

      This in turn provides the argocd command. Before using it, you’ll want to use kubectl again to retrieve the admin password which was automatically generated during your installation, so that you can use it to log in. You’ll pass it a path to a particular JSON file that’s stored using Kubernetes secrets, and extract the relevant value:

      • kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d; echo

      Output

      fbP20pvw-o-D5uxH

      You can then log into your Argo CD dashboard by going back to localhost:8080 in a browser and logging in as the admin user with your own password:

      Argo CD app status

      Once everything is working, you can use the same credentials to log in to Argo CD via the command line, by running argocd login. This will be necessary for deploying from the command line later on:

      • argocd login localhost:8080

      You’ll receive the equivalent certificate warning again on the command line here, and should enter y to proceed when prompted. If desired, you can then change your password to something more secure or more memorable by running argocd account update-password. After that, you’ll have a fully working Argo CD configuration. In the final steps of this tutorial, you’ll learn how to use it to actually deploy some example applications.

      Step 4 — Handling Multiple Clusters (Optional)

      Before deploying an application, you should review where you actually want to deploy it. By default, Argo CD will deploy applications to the same cluster that Argo CD itself is running in, which is fine for a demo, but is probably not what you’ll want in production. In order to list all of the clusters known to your current machine, you can use kubectl config:

      • kubectl config get-contexts -o name

      Output

      test-deploy-cluster test-target-cluster

      Assuming that you’ve installed Argo CD into test-deploy-cluster, and you wanted to use it to deploy applications onto test-target-cluster, you could register test-target-cluster with Argo CD by running argocd cluster add:

      • argocd cluster add target-k8s

      This will add the additional cluster’s login details to Argo CD, and enable Argo CD to deploy services on the cluster.

      Step 5 — Deploying an Example Application (Optional)

      Now that you have Argo CD running and you have an understanding of how to deploy applications to different Kubernetes clusters, it’s time to put it into practice. The Argo CD project maintains a repository of example applications that have been architected to showcase GitOps fundamentals. Many of these examples are ports of the same guestbook demo app to different kinds of Kubernetes manifests, such as Jsonnet. In this case, you’ll be deploying the helm-guestbook example, which uses a Helm chart, one of the most durable Kubernetes management solutions.

      In order to do that, you’ll use the argocd app create command, providing the path to the Git repository, the specific helm-guestbook example, and passing your default destination and namespace:

      • argocd app create helm-guestbook --repo https://github.com/argoproj/argocd-example-apps.git --path helm-guestbook --dest-server https://kubernetes.default.svc --dest-namespace default

      After “creating” the application inside of Argo CD, you can check its status with argocd app get:

      • argocd app get helm-guestbook

      Output

      Name: helm-guestbook Project: default Server: https://kubernetes.default.svc Namespace: default URL: https://localhost:8080/applications/helm-guestbook Repo: https://github.com/argoproj/argocd-example-apps.git Target: Path: helm-guestbook SyncWindow: Sync Allowed Sync Policy: <none> Sync Status: OutOfSync from (53e28ff) Health Status: Missing GROUP KIND NAMESPACE NAME STATUS HEALTH HOOK MESSAGE Service default helm-guestbook OutOfSync Missing apps Deployment default helm-guestbook OutOfSync Missing

      The OutOfSync application status is normal. You’ve retrieved the application’s helm chart from Github and created an entry for it in Argo CD, but you haven’t actually spun up any Kubernetes resources for it yet. In order to actually deploy the application you’ll run argocd app sync:

      • argocd app sync helm-guestbook

      sync is synonymous with deployment here in keeping with the principles of GitOps – the goal when using Argo CD is for your application to always track 1:1 with its upstream configuration.

      Output

      TIMESTAMP GROUP KIND NAMESPACE NAME STATUS HEALTH HOOK MESSAGE 2022-01-19T11:01:48-08:00 Service default helm-guestbook OutOfSync Missing 2022-01-19T11:01:48-08:00 apps Deployment default helm-guestbook OutOfSync Missing 2022-01-19T11:01:48-08:00 Service default helm-guestbook Synced Healthy 2022-01-19T11:01:48-08:00 Service default helm-guestbook Synced Healthy service/helm-guestbook created 2022-01-19T11:01:48-08:00 apps Deployment default helm-guestbook OutOfSync Missing deployment.apps/helm-guestbook created 2022-01-19T11:01:49-08:00 apps Deployment default helm-guestbook Synced Progressing deployment.apps/helm-guestbook created Name: helm-guestbook Project: default Server: https://kubernetes.default.svc Namespace: default URL: https://localhost:8080/applications/helm-guestbook Repo: https://github.com/argoproj/argocd-example-apps.git Target: Path: helm-guestbook SyncWindow: Sync Allowed Sync Policy: <none> Sync Status: Synced to (53e28ff) Health Status: Progressing Operation: Sync Sync Revision: 53e28ff20cc530b9ada2173fbbd64d48338583ba Phase: Succeeded Start: 2022-01-19 11:01:49 -0800 PST Finished: 2022-01-19 11:01:50 -0800 PST Duration: 1s Message: successfully synced (all tasks run) GROUP KIND NAMESPACE NAME STATUS HEALTH HOOK MESSAGE Service default helm-guestbook Synced Healthy service/helm-guestbook created apps Deployment default helm-guestbook Synced Progressing deployment.apps/helm-guestbook created

      You have now successfully deployed an application using Argo CD! It is possible to accomplish the same thing from the Argo CD web interface, but it is usually quicker and more reproducible to deploy via the command line. However, it is very helpful to check on your Argo CD web dashboard after deployment in order to verify that your applications are running properly. You can see that by opening localhost:8080 in a browser:

      Argo CD app status

      At this point, the last thing to do is to ensure you can access your new deployment in a browser. To do that, you’ll forward another port, the way you did for Argo CD itself. Internally, the helm-guestbook app runs on the regular HTTP port 80, and in order to avoid conflicting with anything that might be running on your own port 80 or on the port 8080 you’re using for Argo CD, you can forward it to port 9090:

      • kubectl port-forward svc/helm-guestbook 9090:80

      As before, you’ll probably want to do this in another terminal, because it will block that terminal until you press Ctrl+C to stop forwarding the port. You can then open localhost:9090 in a browser window to see your example guestbook app:

      Guestbook app

      Any further pushes to this Github repository will automatically be reflected in ArgoCD, which will resync your deployment while providing continuous availability.

      Conclusion

      You’ve now seen the fundamentals of installing and deploying applications using Argo CD. Because Kubernetes requires so many layers of abstraction, it’s important to ensure that your deployments are as maintainable as possible, and the GitOps philosophy is a good solution.

      Next, you may want to learn about deploying TOBS, The Observability Stack, for monitoring the uptime, health, and logging of your Kubernetes cluster.



      Source link

      How To Style Figure and Image HTML Elements with CSS


      The author selected the Diversity in Tech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      When styling images on a web page with CSS, there are many important ideas to keep in mind. By default, web browsers display images in a raw format at their default size. This can lead to images being larger than the rest of the content, or can introduce unexpected spacing problems for your page layout. This tutorial will lead you through examples of image styling for web pages, allowing you to make informed decisions about how images are displayed and altered to fit the context.

      In this tutorial, you will create a web page consisting of content and three images. The first image will be loaded as an <img /> element on its own, the second will be wrapped in the <figure> element with an appropriate <figcaption>, and the third will use the <picture> element to load different images at different screen sizes and use the object-fit and object-position properties to resize the image. You will also explore some of the fundamentals of responsive web design and ensure the accessibility of your images.

      Prerequisites

      Setting Up the Base HTML and CSS

      In this section, you will set up the base HTML for all the visual styles you will write throughout the tutorial. You will also create your styles.css file and add styles that set the layout of the content.

      Start by opening index.html in your text editor. Then, add the following HTML to the file:

      index.html

      <!doctype html>
      <html>
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>City Night</title>
          <link rel="preconnect" href="https://fonts.googleapis.com"> 
          <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> 
          <link href="https://fonts.googleapis.com/css2?family=Inconsolata:wght@300;400&display=swap" rel="stylesheet">
          <link rel="stylesheet" href="styles.css" />
        </head>
        <body>
        </body>
      </html>
      

      There are several page aspects defined inside the <head> element. The first <meta> element specifies the character set to use for the text. This way, special characters like accent marks will render without special HTML codes. The second <meta> element tells browsers (mobile browsers in particular) how to treat the width of the content; otherwise, the browser would simulate a 960px desktop width. Next, the <title> element provides the browser with the title of the page. The <link> elements load in the page styles. The first three load in the font, Inconsolata, from Google Fonts, and the last loads the styles you will write in this tutorial.

      Next, the page will need content to style. You will use sample content from Cupcake Ipsum as filler text to use with the styles. Throughout the tutorial, additions to code from previous steps will be highlighted. Return to index.html in your text editor and add the highlighted HTML from the following code block:

      index.html

      <!doctype html>
      <html>
        <head>
          ...
        </head>
        <body>
          <main>
            <h2>City Night</h2>
            <p> Candy bonbon carrot cake jelly beans shortbread fruitcake. Donut lollipop shortbread soufflé cotton candy cupcake cake. Pastry bear claw powder shortbread gingerbread.</p>
            <p>Caramels jelly-o marshmallow muffin macaroon bear claw candy canes gummies. Muffin shortbread sweet roll pastry marzipan pudding.</p>
            <p>Danish gummies oat cake marzipan shortbread pudding chocolate cake. Donut biscuit danish chocolate cake marzipan. Bonbon cheesecake gingerbread sesame snaps brownie ice cream caramels halvah.</p>
          </main>
        </body>
      </html>
      

      The <main> element contains the primary content of the page, with an <h2> text heading of City Night followed by three <p> elements of content. As you work through the tutorial, you will add images to the page between the content.

      Save your changes to index.html, then create a file in the same directory called styles.css. Open this file in your text editor. In your styles.css file, add the CSS from the following code block:

      styles.css

      body {
        margin: 0;
        font: 100% / 1.5 Inconsolata, monospace;
        color: hsl(230, 100%, 95%);
        background-color: hsl(230, 40%, 10%);
      }
      
      h2 {
        font-size: 3.5rem;
        font-weight: 300;
        text-shadow: 0 0 1em hsla(320, 100%, 50%, 0.5),
          0 0 0.125em hsla(320, 100%, 60%, 0.5),
          -0.25em -0.125em 0.125em hsla(40, 100%, 60%, 0.125),
          0.25em 0.125em 0.125em hsla(200, 100%, 60%, 0.25);
      }
      
      main {
        margin: 2rem auto 4rem;
        width: 90%;
        max-width: 70rem;
      }
      
      p {
        font-size: 1.25rem;
        max-width: 75ch;
      }
      

      These styles add the visual aesthetic and layout to the page. The body rule set adjusts the defaults to load the Inconsolata font, then changes the color to be light blue and the background color to a dark blue-purple. Next, the h2 header gets resized, uses a thinner font weight, and gains a unique effect with the use of the text-shadow property. The main element is set up to remain in the center of the page and stop growing in width once it reaches a size of 70rem, which is approximately 1120px. Lastly,the p selector sets the font-size a bit larger to 1.25rem and sets a separate max-width to 75ch, which is 75 characters at the current font-size.

      Save your changes to styles.css and then open your web browser. Select the File menu item, then select the Open option and load your index.html file in the browser. The following image demonstrates how this HTML will render in the browser:

      White monospace text on a dark blue purple background.

      In this section, you created the initial HTML and CSS for this tutorial. You loaded a custom font on the page and created a distinctive headline by using the text-shadow property. In the next section, you will add your first image to the page using the <img /> element, learn about its default browser styles, and set up the images on the page to be responsive.

      Setting Fluid Widths with the <img /> Element

      There are several things to be aware of when working with images on the web. First, images are by default shown on a page pixel for pixel. This means that if an image is 2048 pixels tall and wide it will occupy that much space on the browser, often causing horizontal and vertical scrolling. Next, images are considered inline flow content, which means images are treated like text in a browser and can be placed inline. This can be beneficial when wrapping text around an image with a float property, but otherwise it is best to separate images from text content to improve the final layout.

      To start working with images in your web page, create a new directory called images by running the following in your command prompt:

      Next, you will download a photo of a building with brightly colored doors by Luke Stackpoole. This image comes from the stock photography website Unsplash. Run the following curl command to download the photo into the new images directory:

      • curl -sL https://assets.digitalocean.com/articles/68128/night-doors.jpg -o images/night-doors.jpg

      Now that you have the image available on your computer to use, open index.html in your text editor. After the first paragraph in the content, add an <img /> self-closing element with a src attribute, as highlighted in the following code block:

      index.html

      ...
      <main>
        <h2>City Nights</h2>
        <p>Candy bonbon carrot cake jelly beans shortbread fruitcake. Donut lollipop shortbread soufflé cotton candy cupcake cake. Pastry bear claw powder shortbread gingerbread.</p>
        <img src="https://www.digitalocean.com/community/tutorials/images/night-doors.jpg" />
        ...
      </main>
      ...
      

      The src attribute directs the browser to the image you downloaded from Unsplash.

      A very important aspect of working with an image is to provide an alt attribute with a description of the image. This will help various users of your website know the image content, especially those using a screen reader. It is helpful to provide details around the context of the image, especially as it pertains to the rest of the text content. If an image is purely for decorative purposes, an alt attribute set to an empty string is acceptable, as otherwise a screen reader would read the file name.

      The highlighted HTML in the following code block provides a alt text description of this image:

      index.html

      ...
      <img src="https://www.digitalocean.com/community/tutorials/images/night-doors.jpg" alt="Three floors of several brightly-colored doors with a person walking on the second floor" />
      ...
      

      Save the addition of an image to index.html, then open the file in your web browser. The image will load between the first and second paragraph. Resizing the browser will have no effect on the image, as shown in the following animation:

      Animation of a page with an image causing a horizontal scrollbar to appear as the window width shrinks.

      As mentioned at the beginning of the section, images are shown at their native size, regardless of screen size. In order to make this image fit more screen sizes, you will next give the image fluid dimensions. Fluid image media is a key tenet of responsive web design, a method of web development that emphasizes code that adjusts to the constraints of the screen or browser size.

      In order to define fluid images, open styles.css in your text editor. Create an img element selector, then add a max-width property with a value of 100%, as highlighted in the following code block:

      styles.css

      ..
      p {
        font-size: 1.25rem;
        max-width: 75ch;
      }
      
      img {
        max-width: 100%;
      }
      

      The max-width property tells images they can scale down to fit a space. It also allows the image to grow until it hits the native pixel size. This different from using the width property set to 100%, which would allow the image to grow beyond the native size if the container were larger than the image. Additionally, the default behavior of a browser is to scale an image proportionally, so no height property is necessary.

      Save your changes to styles.css and then return to the browser and refresh index.html. Resize the browser so that the images scales down and back up until it reaches its full pixel size. The following animation depicts how this resizing interaction is rendered in a browser:

      Animation of a web page with an image, which shrinks as the window size shrinks.

      In this section you worked with the <img /> tag and successfully loaded an image on the page. You used the alt attribute on an image and applied a sufficient description of the image. Lastly, you tried out a way to resize all image to fit the space available. In the next section, you will use the <figure> and <figcaption> elements and change their default styling values.

      Providing Captions with <figure> and <figcaption>

      Often an image needs accompanying descriptive text to give the reader more context about the image, such as who is in the image or where the image is from. For this kind of situation, it is useful to place the <img /> inside a <figure> element with a <figcaption> element to hold the descriptive text. In this section, you will use these elements and adjust their default styles to overlay the text on a photo of a street in Tokyo by Jezael Melgoza.

      First, run this curl command in the following code block to download the image into the images directory:

      • curl -sL https://assets.digitalocean.com/articles/68128/tokyo-street.jpg -o images/tokyo-street.jpg

      Next, open index.html in your text editor. In between the second and third paragraphs, add a <figure> element. Within the <figure>, add a <img /> element with a src attribute pointing to the image you just downloaded. Then, add alt text that describes the contents of the photo. These updates are highlighted in the following code block:

      index.html

      ...
      <p>Caramels jelly-o marshmallow muffin macaroon bear claw candy canes gummies. Muffin shortbread sweet roll pastry marzipan pudding.</p>
      
      <figure>
        <img src="https://www.digitalocean.com/community/tutorials/images/tokyo-street.jpg" alt="A motion blurred street with an in-focus taxi." />
      </figure>
      
      <p>Danish gummies oat cake marzipan shortbread pudding chocolate cake. Donut biscuit danish chocolate cake marzipan. Bonbon cheesecake gingerbread sesame snaps brownie ice cream caramels halvah.</p>
      ...
      

      Save these updates, then return to your browser to load index.html. The image is displayed between the second and third paragraphs, but due to default styling has some inset spacing applied, as shown in the following image:

      White monospace text above and below an inset image of a taxi in Tokyo at night.

      The extra spacing of the <figure> is applied with the margin property on the left and right sides of the element. This is the default styling found on most browsers, which puts a 40px margin on the left and right and a 1em margin on the top and bottom.

      To adjust this default style, return to styles.css in your text editor. Create a new figure element selector and inside add a margin property set to 2rem 0, as highlighted in the following code block:

      styles.css

      ...
      img {
        max-with: 100%;
      }
      
      figure {
        margin: 2rem 0;
      }
      

      Setting the margin to 2rem 0 will apply 2rem spacing to the top and bottom of the figure and remove the spacing on the sides. This gives the image more space between the text, but allows it to occupy more space.

      Save your changes to styles.css and return to your browser to refresh the page. The following image shows how the figure spacing is now rendered:

      White monospace text above and below an image aligned to the text depicting a taxi in Tokyo at night.

      Next, to add a caption for the image, return to index.html in your text editor. Inside the <figure> element and beneath the <img /> element, add a <figcaption> tag. The highlighted HTML in the following code block demonstrates this setup with caption text:

      index.html

      ...
      <figure>
        <img src="https://www.digitalocean.com/community/tutorials/images/tokyo-street.jpg" alt="A motion blurred street with an in focus taxi." />
        <figcaption>Taxi in Tokyo, Japan</figcaption>
      </figure>
      ...
      

      The contents of a caption are useful to provide further information about the image that is not clearly evident. This is unlike the alt text, which describes in words the contents of the image. In this case, a useful caption is the location where the photo was taken.

      Due to the HTML order, the <figcaption> content will display below the image, but next you will style it so that it overlays the image with a dark gradient to help make the text legible.

      Return to styles.css in your text editor. In order to create an overlay, a position: relative property value will need to be added to the figure selector. Then, create a figcaption element selector and add the following highlighted CSS:

      styles.css

      ...
      figure {
        margin: 2rem 0;
        position: relative;
      }
      
      figcaption {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 5rem 1rem 1rem;
        background: linear-gradient(to top, hsla(230, 40%, 5%, 0.95), hsla(230, 40%, 5%, 0));
      }
      

      The figcaption styles set the container to overlay the bottom of the image with the position, bottom, right, and left properties. Next, the padding property is large on the top side with 5rem to give ample space for the gradient to spread above the text content, and the left, right, and bottom sides have a smaller 1rem spacing. Lastly, you create the gradient with the background property’s linear-gradient() value that transition’s a dark blue at 95% opacity up to the same color with 0% opacity. Together, this creates a shadowed edge at the bottom to contain the caption.

      Save your changes to styles.css and return to your browser to refresh the page. The gradient background of the <figcaption> shows up at the bottom of the image, but it overshoots the image on the bottom and right sides. The following image shows a close-up view of the difference between the image and the gradient:

      A misaligned dark blue gradient covering a photo on a dark blue-purple background.

      There are two different issues that cause this misalignment, which require two methods to adjust the styles and correct the issue.

      The first deals with how <img /> elements are treated as inline text by default. This extra space at the bottom is the line-height spacing that makes space between lines of text. There are two ways to adjust this, by either changing the line-height of the <figure> element or setting the <img> to have a display property set to block.

      The second issue is the difference in size between the image’s pixel-to-pixel dimensions and the max-width of the <main> element. Since the <figure> is a block element and the <figcaption> is set to span from the left edge to the right edge, it grows to fill a space larger than the image. The first way to fix this issue is to change the <img /> to have a width set to 100%. By setting this width the image will ignore the max-width: 100% default and instead fill the whole space. Note that this approach can cause image distortion depending on the difference in size. The second strategy to fix this is to change the <figure> to have a display property set to inline-block. This approach will cause the <figure> element’s size to shrink to fit its contents.

      Return to styles.css in the text editor and add the display approach for each issue. In the figure selector, add a display property set to a value of inline-block. Then, create a figure img descendant combinator selector with a display: block, as highlighted in the following code block:

      styles.css

      ...
      figure {
        margin: 2rem 0;
        position: relatve;
        display: inline-block;
      }
      
      figure img {
        display: block;
      }
      
      figcaption {
        ...
      }
      

      Save your changes to styles.css and then refresh index.html in the web browser. The <figure> shrinks down to the natural size of the image and the image is no longer treated as text. The following image shows how this adjustment to the display properties is rendered:

      White monospace text above and below an inset image of a taxi in Tokyo at night with a gradient and descriptive text overlaying the image.

      In this section, you used the <figure> and <figcaption> elements. You learned about the default styles of the <figure> and <img /> elements and how to change them for a more controlled outcome. Lastly, you created a caption that overlays the image with contextual information about the photo. In the last section, you will work with styling the <picture> element using the object-fit and object-position properties.

      Using Responsive Image Swapping with <picture>

      When working with images across various screen sizes, there are times when the image isn’t the right size and needs to adapt to the layout. The <picture> element exists to meet this need by defining different images to display at different screen sizes. The images can then be more tightly controlled with the object-fit and object-position properties, which set how an image scales between the specific sizes.

      To begin working with the <picture> element, you will need a series of different-sized images of the same source image. Use the following curl command to download a zip archive of three images of the same aerial photo of Tokyo by Pawel Nolbert:

      • curl -sL https://assets.digitalocean.com/articles/68128/picture.zip -o images/picture.zip

      Once the zip file finishes downloading, extract the content to your image folder. Run the following command in your prompt to place the files in the images directory:

      • unzip images/picture.zip -d ./images

      Now, open index.html in your text editor. First, you will create a <div> with a class attribute of hero between the opening <body> and <main> elements. Then add the remaining highlighted <picture> elements from the following code block:

      index.html

      ...
      <body>
        <div class="hero">
          <picture>
            <source  media="(min-width:70rem)" />
            <source  media="(min-width:40rem)" />
            <img class="hero-image" src="https://www.digitalocean.com/community/tutorials/images/tokyo-small.jpg" alt="Time-lapse exposure of a city at night." />
          </picture>
        </div>
        <main>
      ...
      

      The <picture> element requires a specific structure consisting of as many <source /> elements as needed and one <img /> element as the last item inside. All the accessibility and styling of the <picture> element comes from the <img /> element, which is why the <img /> has a class and the <picture> does not.

      The <img /> is the default image that is used to start when there are no media query requirements. The <source /> elements define two things: the location of the image file with the srcset attribute, and the screen size scenario with the media attribute. The browser will then access and load the appropriate image for the stated screen size, swapping out the image if the size changes.

      Save your changes to index.html, then open the file in your web browser. The following animation depicts the browser swapping the images as the window grows in size:

      Animation depicting an image changing to new cropped versions of the image as the window size increases.

      As the screen size changes, the image size changes as well, causing the text below to be pushed further down the page. In order to create a consistent spacing between this hero image area and the content, height properties can be set to maintain a consistent size.

      Return to styles.css in your text editor. At the bottom of the page, create a class selector for .hero. In the selector block, add the highlighted CSS from the following code block:

      styles.css

      ...
      .hero {
        height: 80vh;
        max-height: 40rem;
      }
      

      The height value set to 80vh means that the .hero container will at the least take up 80% of the browser’s screen height. Then the max-height property ensures that the .hero will not grow larger than 40rem, which is equivalent to 640 pixels tall.

      Save your changes to styles.css and refresh index.html in the browser. As the following animation illustrates, the text now maintains a consistent position. Meanwhile the visual distance between the image and content adjusts to the point that the image slides behind the text:

      Animation depicting shifting spacing between an image and the page content as the window size increases with the image and text, eventually overlapping.

      This overlap of the text and the image is a result of the browser erring on the side of content remaining visible, even if it goes beyond its ancestor’s container. A quick fix for this would be to apply an overflow: hidden on the .hero element, but that does not address the extra space when the image is scaled down smaller. To create a solution for both issues, the object-fit property can help by giving an image similar controls as a background image has with the background-size property.

      To begin working with object-fit, return to styles.css in your text editor. Since the <img /> element is the element that controls styling for a <picture> element, create a class selector for .hero-image and add the highlighted CSS from the following code block:

      styles.css

      ...
      .hero {
        height: 80vh;
        max-height: 40rem;
      }
      
      .hero-image {
        height: 100%;
        width: 100%;
        object-fit: cover;
      }
      

      In order to work with the object-fit property, the image needs to be able to grow both vertically and horizontally. By setting the height and width properties to 100%, you give the object-fit property full control of resizing the image. Without the object-fit property, the image would be squashed to fit the parent container. The cover value allows the image to be edge to edge either vertically or horizontally, depending on the orientation of the container. The object-fit property can accept the same values as the background-size property, including contain and dimension values.

      Save this new addition to styles.css and refresh index.html in your web browser. The following animation illustrates how the object-fit property allows the image to grow to fill the whole space of the .hero container and be hidden when it crosses the edge of the container, just like a background image:

      Animation depicting a defined spacing between image and text, where as the window size increases the image grows, and portions of the image are hidden as they grow beyond the bounds.

      Lastly, there is the object-position property. This works similarly to the background-position property to allow an image to be anchored to a specific area.

      Return to styles.css in your text editor and add an object-position property to the .hero-image selector. Set the value of the property to bottom right, which will anchor the image to the bottom right area as it resizes. The highlighted CSS in the following code block demonstrate how this is written:

      styles.css

      ...
      .hero-image {
        height: 100%;
        width: 100%;
        object-fit: cover;
        object-position: bottom right;
      }
      

      Save this change to styles.css, then return to your browser and refresh index.html.

      This time as the browser width changes and the image scales, the scaling stems from the center of the container, as shown in the following animation:

      Animation depicting a defined spacing between image and text, where as the window size increases the image grows, and portions of the image are hidden as they grow beyond the bounds, anchored at the bottom right of the image.

      This section introduced you to the <picture> media elements, the object-fit property, and the object-position property. You used this combination of elements and properties to create a resizing and adjusting large image at the top of the page.

      Conclusion

      With the techniques you practiced throughout this tutorial, you are now prepared to write styles that will format images to fit your design and layout. You created responsive images by setting a global max-width: 100% to all <img /> elements on the page. Next, you formatted an image caption to overlay the image and grow and shrink with the image. Then, you used the <picture> element along with the object-fit and object-position properties to swap and scale images to best fit the screen size. Using these strategies will help you solve more complex situations involving images and page layout.

      If you would like to read more CSS tutorials, try out the other tutorials in the How To Style HTML with CSS series.



      Source link